vendredi 6 février 2015

SQLiteOpenHelper suddenly becomes null

I am new to Android and am making my first app. I made a SQLite table using a contract and helper class. That works fine. I then wrap the database in a ContentProvider, which also seems to work just fine. Here's how I instantiate the SQLiteOpenHelper in my Content Provider class:



public boolean onCreate() {
mTestDb = new TestDbHelper(getContext());
return true;
}


I then have two helper methods in the onCreate() method of the MainActivity:



@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}

provider = new TestProvider();
providerInsert();
providerShow();
}


provider was declared as a class variable previously. Here are the helper methods:



public void providerInsert() {
ContentValues values = new ContentValues();
values.put(TestContract.FIRST_COLUMN, 3);
values.put(TestContract.SECOND_COLUMN, "hello.");
final Uri uri = getContentResolver().insert(TestContract.CONTENT_URI, values);
}

public void providerShow() {
Cursor cursor = provider.query(
TestContract.CONTENT_URI,
new String[] {TestContract._ID, TestContract.FIRST_COLUMN, TestContract.SECOND_COLUMN},
null,
null,
null
);
int id = cursor.getInt(0);
int first = cursor.getInt(1);
String second = cursor.getString(2);

String print = "At column" + id + ": " + first + ", " + second;

Toast.makeText(getBaseContext(), print, Toast.LENGTH_LONG)
.show();
}


Heres the kicker: providerInsert() works just fine! I'm getting a values for url and everything looks great. Then, it goes to providerShow() and mTestDb is now suddenly null! Here are the insert() and query() methods for my Content Provider:



public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = mTestDb.getWritableDatabase();

switch(matcher.match(uri)) {

case FIRST_CASE: {
long id = db.insert(
TestContract.TABLE_NAME,
null,
values
);

return ContentUris.withAppendedId(TestContract.CONTENT_URI, id);

}

default: {
return null;
}
}
}

public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
SQLiteDatabase db = mTestDb.getReadableDatabase();
Cursor rCursor;

switch(matcher.match(uri)) {

case FIRST_CASE: {
rCursor = db.query(
TestContract.TABLE_NAME,
projection,
selection,
selectionArgs,
null,
null,
sortOrder
);
break;
}

default: {
rCursor = null;
}
}

return rCursor;
}


As I previously said, mTestDb becomes null by the time the code gets to query(). I feel like this is just a silly error and it has a simple fix, but I've been pouring over the code for hours to no avail. Could someone please help me out?


Thanks in advance! :)


Aucun commentaire:

Enregistrer un commentaire