2

I can't seem work out why I am getting a null pointer on this?

This is my AsyncTask that I call to grab the data. It passes it to a JSON Parser and an array of Objects is returned. This is then passed to my DBHelper where it was passing to my database through a ContentResolver....

public class getFilms extends AsyncTask<String, Void, Void> {

public int LIMIT_FILMS = 10;
String KEY = "apikey";
String LIMIT = "limit";
private static final String URL = "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json?";
private static final String API_KEY = "******************";
ArrayList<HashMap<String, String>> filmArrayList = new ArrayList<HashMap<String, String>>();
Context mContext;

@Override
protected Void doInBackground(String... params) {

    Uri RottenUrl = Uri.parse(URL).buildUpon()
            .appendQueryParameter(KEY, API_KEY)
            .appendQueryParameter(LIMIT, Integer.toString(LIMIT_FILMS))
            .build();

    JSONParser jParser = new JSONParser();
    Film[] json = jParser.getJSONFromUrl(RottenUrl.toString());
    sortData(json);
    return null;
}

public void sortData(Film[] jsonlist) {
    DatabaseHelper dbHelper = new DatabaseHelper(mContext, null, null, 1);
    dbHelper.deleteAll();
    for (int i = 0; i < jsonlist.length; i++) {
        dbHelper.contentAddFilm(jsonlist[i]);
    }
}
}

This is my Database Helper

public class DatabaseHelper extends SQLiteOpenHelper {

private ContentResolver myCR;

public DatabaseHelper(Context context, String name,
                      SQLiteDatabase.CursorFactory factory, int version) {
    super(context, FilmDataContract.DATABASE_NAME, factory, FilmDataContract.DATABASE_VERSION);
    myCR = context.getContentResolver();

}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(FilmDataContract.FilmEntry.SQL_CREATE_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL(FilmDataContract.FilmEntry.DELETE_TABLE);
    onCreate(db);
}

public void addFilm(Film film) {

    ContentValues values = new ContentValues();
    values.put(FilmDataContract.FilmEntry.COLUMN_FILM_TITLE, film.getTitle());
    values.put(FilmDataContract.FilmEntry.COLUMN_FILM_RATING, film.getRating());
    values.put(FilmDataContract.FilmEntry.COLUMN_FILM_RUNTIME, film.getRuntime());
    values.put(FilmDataContract.FilmEntry.COLUMN_FILM_CRITICS, film.getCritics());
    values.put(FilmDataContract.FilmEntry.COLUMN_FILM_AUDIENCE, film.getAudience());
    values.put(FilmDataContract.FilmEntry.COLUMN_FILM_SYNOPSIS, film.getSynopsis());
    values.put(FilmDataContract.FilmEntry.COLUMN_FILM_PROFILE, film.getProfile());

    SQLiteDatabase db = this.getWritableDatabase();
    db.insert(FilmDataContract.TABLE_NAME,
            null,
            values);
    db.close();
}


public Film getFilm(int id) {

    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor =
            db.query(FilmDataContract.TABLE_NAME,
                    FilmDataContract.FilmEntry.COLUMNS,
                    "_id = ?",
                    new String[]{String.valueOf(id)},
                    null,
                    null,
                    null,
                    null);

    if (cursor != null)
        cursor.moveToFirst();

    Film film = new Film();
    film.setTitle(cursor.getString(1));
    film.setRating(cursor.getString(2));
    film.setRuntime(cursor.getString(3));
    film.setCritics(cursor.getString(4));
    film.setAudience(cursor.getString(5));
    film.setSynopsis(cursor.getString(6));
    film.setProfile(cursor.getString(7));

    return film;
}

public List<Film> getAllFilms() {
    List<Film> films = new LinkedList<Film>();

    String query = "SELECT  * FROM " + FilmDataContract.TABLE_NAME;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(query, null);

    Film film = null;
    if (cursor.moveToFirst()) {
        do {
            film = new Film();
            film.setId(Integer.parseInt(cursor.getString(0)));
            film.setTitle(cursor.getString(1));
            film.setRating(cursor.getString(2));
            film.setRuntime(cursor.getString(3));
            film.setCritics(cursor.getString(4));
            film.setAudience(cursor.getString(5));
            film.setSynopsis(cursor.getString(6));
            film.setProfile(cursor.getString(7));

            films.add(film);
        } while (cursor.moveToNext());
    }

    return films;
}

public int updateFilm(Film film) {

    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(FilmDataContract.FilmEntry.COLUMN_FILM_TITLE, film.getTitle());
    values.put(FilmDataContract.FilmEntry.COLUMN_FILM_RATING, film.getRating());
    values.put(FilmDataContract.FilmEntry.COLUMN_FILM_RUNTIME, film.getRuntime());
    values.put(FilmDataContract.FilmEntry.COLUMN_FILM_CRITICS, film.getCritics());
    values.put(FilmDataContract.FilmEntry.COLUMN_FILM_AUDIENCE, film.getAudience());
    values.put(FilmDataContract.FilmEntry.COLUMN_FILM_SYNOPSIS, film.getSynopsis());
    values.put(FilmDataContract.FilmEntry.COLUMN_FILM_PROFILE, film.getProfile());

    int i = db.update(FilmDataContract.FilmEntry.TABLE_NAME,
            values,
            "_id+ = ?",
            new String[]{String.valueOf(film.getId())});

    db.close();

    return i;
}

public int getFilmsCount() {
    String countQuery = "SELECT  * FROM " + FilmDataContract.FilmEntry.TABLE_NAME;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    int cnt = cursor.getCount();
    cursor.close();
    return cnt;
}

public void deleteAll() {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(FilmDataContract.FilmEntry.TABLE_NAME, null, null);
}

public boolean contentDelete(String filmName) {

    boolean result = false;
    String selection = "title = \"" + filmName + "\"";

    int rowsDeleted = myCR.delete(FilmProvider.CONTENT_URI,
            selection, null);

    if (rowsDeleted > 0)
        result = true;

    return result;
}

public Film contentFindFilm(String filmName) {
    String[] projection = FilmDataContract.FilmEntry.COLUMNS;

    String selection = "title = \"" + filmName + "\"";

    Cursor cursor = myCR.query(FilmProvider.CONTENT_URI,
            projection, selection, null,
            null);

    Film film = new Film();

    if (cursor.moveToFirst()) {
        cursor.moveToFirst();

        film.setId(Integer.parseInt(cursor.getString(0)));
        film.setTitle(cursor.getString(1));
        film.setRating(cursor.getString(2));
        film.setRuntime(cursor.getString(3));
        film.setCritics(cursor.getString(4));
        film.setAudience(cursor.getString(5));
        film.setSynopsis(cursor.getString(6));
        film.setProfile(cursor.getString(7));

        cursor.close();
    } else {
        film = null;
    }
    return film;
}

public void contentAddFilm(Film film) {

    ContentValues values = new ContentValues();
    values.put(FilmDataContract.FilmEntry.COLUMN_FILM_TITLE, film.getTitle());
    values.put(FilmDataContract.FilmEntry.COLUMN_FILM_RATING, film.getRating());
    values.put(FilmDataContract.FilmEntry.COLUMN_FILM_RUNTIME, film.getRuntime());
    values.put(FilmDataContract.FilmEntry.COLUMN_FILM_CRITICS, film.getCritics());
    values.put(FilmDataContract.FilmEntry.COLUMN_FILM_AUDIENCE, film.getAudience());
    values.put(FilmDataContract.FilmEntry.COLUMN_FILM_SYNOPSIS, film.getSynopsis());
    values.put(FilmDataContract.FilmEntry.COLUMN_FILM_PROFILE, film.getProfile());

    myCR.insert(FilmProvider.CONTENT_URI, values);
}

This is my stack trace... Seems to be happening when I am passing the context.

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.ContentResolver android.content.Context.getContentResolver()' on a null object reference
        at com.purewowstudio.topmovies.data.DatabaseHelper.<init>(DatabaseHelper.java:25)
        at com.purewowstudio.topmovies.util.getFilms.sortData(getFilms.java:48)
        at com.purewowstudio.topmovies.util.getFilms.doInBackground(getFilms.java:43)
        at com.purewowstudio.topmovies.util.getFilms.doInBackground(getFilms.java:16)
        at android.os.AsyncTask$2.call(AsyncTask.java:288)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)

             at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)             

5
  • You are initiating your DatabaseHelper class with a Context null parameter. But you did not post the code where you did. Commented Mar 22, 2015 at 20:19
  • Ok. The code is there. You better check json for null before calling sortData on it otherwise you will soon have the next NullPointerException. Commented Mar 22, 2015 at 20:31
  • Thanks for the quick response. I'm not sure how to get context to pass. Nothing seems to be working for me. Commented Mar 22, 2015 at 20:49
  • Well you pass it already but mContext is null. Initialise it in OnCreate with mContext=this;. Commented Mar 22, 2015 at 21:14
  • Thanks for the help. I was in a background thread so used this instead... stackoverflow.com/questions/2002288/… Commented Mar 22, 2015 at 21:45

1 Answer 1

1
DatabaseHelper dbHelper = new DatabaseHelper(mContext, null, null, 1);

mContext is null, because you never assign a value to it.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, That's what I thought but I seem to be having trouble getting context outside the UI Thread. Is this an issue or is it me not understand context correctly?
You can't access context from other thread, so you need to pass the context when you create the AsyncTask through a customized constructor.
Thanks for the help. I ended up using this... stackoverflow.com/questions/2002288/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.