I am trying to use SQLite DB to store data along with other information in my android app but i am getting this error:
Caused by: 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.
Here is my ViewProductList.java:
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
RecyclerAdapter adapter;
ArrayList<Contact> arrayList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_product_list);
//DbHelper dbHelper= new DbHelper(this);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapter = new RecyclerAdapter(arrayList);
recyclerView.setAdapter(adapter);
readFromLocalStorage();
}
public void readFromLocalStorage(){
arrayList.clear();
DbHelper dbHelper = new DbHelper(this);
SQLiteDatabase database= dbHelper.getReadableDatabase();
Cursor cursor = dbHelper.readFromLocalDatabase(database);
while (cursor.moveToNext()){
String name=cursor.getString(cursor.getColumnIndex(DbContract.NAME));
String quantity=cursor.getString(cursor.getColumnIndex(DbContract.QUANTITY));
String price=cursor.getString(cursor.getColumnIndex(DbContract.PRICE));
int sync_status =cursor.getInt(cursor.getColumnIndex(DbContract.SYNC_STATUS));
arrayList.add(new Contact(name,quantity,price,sync_status));
}
adapter.notifyDataSetChanged();
cursor.close();
dbHelper.close();
}
}
the error is inside readFromLocalStorage() method please help me to solve it! thank you!
DbHelper.java
public class DbHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION =1;
private static final String CREATE_TABLE="create table "+DbContract.TABLE_NAME+
"(id integer primary key autoincrement,"+DbContract.NAME+" text,"+DbContract.QUANTITY+" text,"+DbContract.PRICE+" text,"+DbContract.SYNC_STATUS+
" integer);";
private static final String DROP_TABLE="drop table if exists "+DbContract.TABLE_NAME;
public DbHelper(Context context){
super(context,DbContract.DATABASE_NAME,null,DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
}
I am getting this error on readFromLocalStorage() method inside ViewProductList.java. Please help me to solve this error. Thankx in advance!