Shah Zeb Shah Zeb - 3 months ago 26
Android Question

Call SQLiteOpenHelper method from fragment

i want to call this method getAllData(); from Fragment, this method return cursor data from SQlite Database and i want to use that data inside my Fragment to create listView, i use these lines of code to access that data

PackagesDbHelper mydb = new PackagesDbHelper(getActivity());
Cursor result = mydb.getAllData();


but on app launch i get this error "unfortunately app has stopped" but if i exclude this line of code

Cursor result = mydb.getAllData();


my app works fine

PackagesDbHelper

public class PackagesDbHelper extends SQLiteOpenHelper {

public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor result = db.rawQuery("SELECT * FROM " + PackagesContract.ufoneEntry.TABLE_NAME, null);
return result;
}


}

PackagesFragment

public class PackagesFragment extends Fragment {

private PackagesAdapter packagesAdapter;
PackagesDbHelper mydb = new PackagesDbHelper(getActivity());

@Override
public void onCreate(Bundle savedInstanceState) {
Cursor result = mydb.getAllData();

super.onCreate(savedInstanceState);
}


}

Answer

Here:

PackagesDbHelper mydb = new PackagesDbHelper(getActivity());

line causing issue because calling getActivity() at class level will return invalid Activity Context.

Initialize mydb object inside onCreate or any other method :

mydb = new PackagesDbHelper(getActivity());
Cursor result = mydb.getAllData();