Grayson Gould
Grayson Gould

Reputation: 107

Android, context not found in database construction

So I am trying to use a database to fill a listview within a fragment. So far I am to the point where I am trying to insert data into an empty table, but whenever I run my insert method the app crashes. As far as I can tell, the error is a NullPointerException when the database is being created, caused by the context not being returned properly. However, I don't see what's wrong with the context. I will try to include any relevant classes.

Contract Class

public final class NotesContract {

//Empty Constructor
public NotesContract(){}

/* Inner class that defines the table contents */
public static abstract class FeedEntry implements BaseColumns {
    public static final String TABLE_NAME = "notes";
    public static final String COLUMN_NAME_TITLE = "title";
    public static final String COLUMN_NAME_BODY = "body";
    //add more columns for database here
}

}

SQLiteOpenHelper

public class MySQLiteHelper extends SQLiteOpenHelper {

private static final String TEXT_TYPE = " TEXT";
private static final String INT_TYPE = " INTEGER";
private static final String COMMA_SEP = ",";
private static final String SQL_CREATE_ENTRIES =
        "CREATE TABLE " + FeedEntry.TABLE_NAME + " (" +
                FeedEntry._ID + " INTEGER PRIMARY KEY," +
                FeedEntry.COLUMN_NAME_TITLE + TEXT_TYPE + COMMA_SEP +
                FeedEntry.COLUMN_NAME_BODY + TEXT_TYPE +
        " )";

private static final String SQL_DELETE_ENTRIES =
        "DROP TABLE IF EXISTS " + FeedEntry.TABLE_NAME;



// If you change the database schema, you must increment the database version.
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "FeedReader.db";

public MySQLiteHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
    db.execSQL(SQL_CREATE_ENTRIES);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // This database is only a cache for online data, so its upgrade policy is
    // to simply to discard the data and start over
    db.execSQL(SQL_DELETE_ENTRIES);
    onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    onUpgrade(db, oldVersion, newVersion);
}
}

MainActivityFragment

public class MainActivityFragment extends Fragment {

//Databse instatiation
MySQLiteHelper mDbHelper = new MySQLiteHelper(getActivity());

//other stuff

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    //Primary View Inflator
    final View rootView = inflater.inflate(R.layout.fragment_main, container, false);

//other stuff

final ImageButton button2 = (ImageButton) rootView.findViewById(R.id.addNoteButton);

    button2.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

        if((noteTitle.getText().toString().trim()).equals("")){
            Toast.makeText(getActivity().getBaseContext(), "No Title Specified", Toast.LENGTH_SHORT).show();
        }else {
            String noteTitleString = noteTitle.getText().toString();
            String noteBodyString = noteBody.getText().toString();

            Toast.makeText(getActivity().getBaseContext(), "Added: " + noteTitleString, Toast.LENGTH_SHORT).show();

            //Clear text fields and hide keyboard
            noteTitle.getText().clear();
            noteBody.getText().clear();
            final InputMethodManager imm = (InputMethodManager)
                    getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);

            addNotes(noteTitleString, noteBodyString);
        }
        }
    });

}

private void addNotes(String title, String body){

    // Gets the data repository in write mode
    SQLiteDatabase db = mDbHelper.getWritableDatabase();

// Create a new map of values, where column names are the keys
    ContentValues values = new ContentValues();
    values.put(FeedEntry.COLUMN_NAME_TITLE, title);
    values.put(FeedEntry.COLUMN_NAME_BODY, body);

// Insert the new row, returning the primary key value of the new row
    long newRowId;
    newRowId = db.insert(
            FeedEntry.TABLE_NAME,
            null,
            values);

    db.close();
}

Error stack

Process: com.example.ggould.scribble, PID: 21011
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase(java.lang.String, int, android.database.sqlite.SQLiteDatabase$CursorFactory, android.database.DatabaseErrorHandler)' on a null object reference
            at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:223)
            at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
            at com.example.ggould.scribble.MainActivityFragment.addNotes(MainActivityFragment.java:228)
            at com.example.ggould.scribble.MainActivityFragment.access$000(MainActivityFragment.java:26)
            at com.example.ggould.scribble.MainActivityFragment$2.onClick(MainActivityFragment.java:136)
            at android.view.View.performClick(View.java:4756)
            at android.view.View$PerformClick.run(View.java:19749)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

Upvotes: 0

Views: 233

Answers (1)

Mateus Brandao
Mateus Brandao

Reputation: 900

When you are calling MySQLiteHelper mDbHelper = new MySQLiteHelper(getActivity()); the Fragment it not yet attached to the Activity, so getActivity() returns null. Try creating the MySQLiteHelper Object in the onCreateView method.

Upvotes: 3

Related Questions