I built a gridview with SQLite database, and used cursor to uptade Imageview. It worked well in my last project, but when I combine it with customized toolbar,error shows up
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.playah.medcare01/com.playah.medcare01.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.Cursor com.playah.medcare01.SQLiteHelper.getData(java.lang.String)' on a null object reference"
MainActivity
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolBar);
setSupportActionBar(toolbar);
//grid view
gridView = (GridView) findViewById(R.id.gridView);
list = new ArrayList<>();
adapter = new MedicineListAdapter(this, R.layout.medicine_items, list);
gridView.setAdapter(adapter);
// get all data from sqlite
Cursor cursor = AddNewMedicine.sqLiteHelper.getData("SELECT * FROM MEDICINE");
list.clear();
while (cursor.moveToNext()) {
int id = cursor.getInt(0);
String name = cursor.getString(1);
String dose = cursor.getString(2);
byte[] image = cursor.getBlob(3);
list.add(new Medicine(name, dose, image, id));
}
adapter.notifyDataSetChanged();
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if(requestCode == 888){
if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 888);
}
else {
Toast.makeText(getApplicationContext(), "You don't have permission to access file location!", Toast.LENGTH_SHORT).show();
}
return;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 888 && resultCode == RESULT_OK && data != null){
Uri uri = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imageViewMedicine.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
SQLiteHelper
public class SQLiteHelper extends SQLiteOpenHelper{
public SQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
public void queryData(String sql){
SQLiteDatabase database = getWritableDatabase();
database.execSQL(sql);
}
public void insertData(String name, String dose, byte[] image){
SQLiteDatabase database = getWritableDatabase();
String sql = "INSERT INTO MEDICINE VALUES (NULL, ?, ?, ?)";
SQLiteStatement statement = database.compileStatement(sql);
statement.clearBindings();
statement.bindString(1, name);
statement.bindString(2, dose);
statement.bindBlob(3, image);
statement.executeInsert();
}
public void updateData(String name, String dose, byte[] image, int id) {
SQLiteDatabase database = getWritableDatabase();
String sql = "UPDATE MEDICINE SET name = ?, dose = ?, image = ? WHERE id = ?";
SQLiteStatement statement = database.compileStatement(sql);
statement.bindString(1, name);
statement.bindString(2, dose);
statement.bindBlob(3, image);
statement.bindDouble(4, (double)id);
statement.execute();
database.close();
}
public void deleteData(int id) {
SQLiteDatabase database = getWritableDatabase();
String sql = "DELETE FROM MEDICINE WHERE id = ?";
SQLiteStatement statement = database.compileStatement(sql);
statement.clearBindings();
statement.bindDouble(1, (double)id);
statement.execute();
database.close();
}
public Cursor getData(String sql){
SQLiteDatabase database = getReadableDatabase();
return database.rawQuery(sql, null);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
} }
AddNewMedicine
public class AddNewMedicine extends AppCompatActivity{
EditText editName, editDose;
ImageButton bn_photo;
Button bn_Save;
ImageView imageView;
final int REQUEST_CODE_GALLERY = 999;
public static SQLiteHelper sqLiteHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_new_medicine);
init();
sqLiteHelper = new SQLiteHelper(this, "MedicineDB.sqlite", null, 1);
sqLiteHelper.queryData("CREATE TABLE IF NOT EXISTS MEDICINE(Id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, dose VARCHAR, image BLOB)");
bn_photo.setOnClickListener(new View.OnClickListener() {
//Select picture button
@Override
public void onClick(View view) {
ActivityCompat.requestPermissions(
AddNewMedicine.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_CODE_GALLERY
);
}
});
bn_Save.setOnClickListener(new View.OnClickListener() {
//Add picture button
@Override
public void onClick(View view) {
try{
sqLiteHelper.insertData(
editName.getText().toString().trim(),
editDose.getText().toString().trim(),
imageViewToByte(imageView)
);
Toast.makeText(getApplicationContext(), "Added successfully!", Toast.LENGTH_SHORT).show();
editName.setText("");
editDose.setText("");
imageView.setImageResource(R.mipmap.ic_launcher);
}
catch (Exception e){
e.printStackTrace();
}
//Go to the home page
Intent to_intent = new Intent(AddNewMedicine.this, Alarm.class);
startActivity(to_intent);
}
});
}
//Implement image insertion
public static byte[] imageViewToByte(ImageView image) {
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
return byteArray;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//Permission confirmation
if(requestCode == REQUEST_CODE_GALLERY){
if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_CODE_GALLERY);
}
else {
Toast.makeText(getApplicationContext(), "You don't have permission to access file location!", Toast.LENGTH_SHORT).show();
}
return;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_CODE_GALLERY && resultCode == RESULT_OK && data != null){
Uri uri = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void init(){
editName = (EditText) findViewById(R.id.editName);
editDose = (EditText) findViewById(R.id.editDose);
bn_photo = (ImageButton) findViewById(R.id.bn_photo);
bn_Save = (Button) findViewById(R.id.bn_Save);
imageView = (ImageView) findViewById(R.id.imageView);
}
}