Algor7 Algor7 - 5 months ago 201
Android Question

Sqlite giving NullPointerException error in android

I am trying to use sqlite DB to store images along with other information in my android app but i am getting this error

06-20 12:00:51.411 4132-4132/braindottech.com.fishid E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: braindottech.com.fishid, PID: 4132
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 braindottech.com.fishid.PhotoDBMS.<init>(PhotoDBMS.java:65)
at braindottech.com.fishid.CameraScan$6.onClick(UseSqliteDB.java:23)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21153)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)


Here is my "UseSqliteDB.java" code:

public class UseSqliteDB extends Fragment {

private Button saveResult;

public UseSqliteDB(){}

@Override
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); }

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, final Bundle savedInstanceState) {

View v = inflater.inflate(R.layout.fragment_camera, container, false);

context = this.getActivity();
saveResult = (Button) v.findViewById(R.id.button_save_CameraPreview);

saveResult.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {

try {
PhotoDBMS photoDBMS = new PhotoDBMS(getActivity());
String nameImage = "IMAGE";
Calendar calendar = Calendar.getInstance();
nameImage += calendar.get(Calendar.DATE) + calendar.get(Calendar.HOUR) + calendar.get(Calendar.MINUTE) +
calendar.get(Calendar.SECOND) + calendar.get(Calendar.MILLISECOND);
Boolean response = photoDBMS.insertData(nameImage, resultTV.getText().toString(), finalBitmap);
if (!response) {
Toast.makeText(context, "Database entry failed!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Database entry successful!", Toast.LENGTH_LONG).show();
}

}catch(Exception e){
Log.d("HIP","E = "+e);
}

}
});

return v;
}

}


PhotoDBMS.java

public class PhotoDBMS {

private Context context;

public PhotoDBMS(Context c){
context = c;
}

public static abstract class DBMS_Constants implements BaseColumns {
public static final String TABLE_NAME = "MY_COLLECTION";
public static final String COLUMN_NAME_NAME = "Name";
public static final String COLUMN_NAME_INFO = "Info";
public static final String COLUMN_NAME_IMAGE = "Image";
}

private static final String TEXT_TYPE = " TEXT";
private static final String COMMA_SEP = ",";
private static final String BLOB = "BLOB";
private static final String SQL_CREATE_TABLE = "CREATE TABLE " + DBMS_Constants.TABLE_NAME + " (" +
DBMS_Constants._ID + " INTEGER PRIMARY KEY," +
DBMS_Constants.COLUMN_NAME_NAME + TEXT_TYPE + COMMA_SEP +
DBMS_Constants.COLUMN_NAME_INFO + TEXT_TYPE + COMMA_SEP +
DBMS_Constants.COLUMN_NAME_IMAGE + BLOB + " )";

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

public class DbHelper extends SQLiteOpenHelper {
// 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 DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_TABLE);
}
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);
}

}

DbHelper dbHelper = new DbHelper(context);
SQLiteDatabase collectionDB = dbHelper.getWritableDatabase();

public boolean insertData(String name, String info, Bitmap bm){

bitmapUtility utility = new bitmapUtility();
byte[] image = utility.getBytes(bm);
ContentValues cv = new ContentValues();
cv.put(DBMS_Constants.COLUMN_NAME_NAME, name);
cv.put(DBMS_Constants.COLUMN_NAME_INFO, info);
cv.put(DBMS_Constants.COLUMN_NAME_IMAGE, image);
return collectionDB.insert( DBMS_Constants.TABLE_NAME, null, cv ) > 0;

}

public boolean deleteData(String name){
return collectionDB.delete(DBMS_Constants.TABLE_NAME, DBMS_Constants.COLUMN_NAME_NAME + " = " + name, null) > 0;
}

}


I am getting this error on try-catch section inside UseSqliteDB.java. Please help me to solve this error. Thankx in advance!

Answer

Problem is due to:

DbHelper dbHelper = new DbHelper(context);
SQLiteDatabase collectionDB = dbHelper.getWritableDatabase();

lines added at class level instead of inside any method.

Either create a method and call it using photoDBMS to create and get database object:

public void createDB(){
    DbHelper dbHelper = new DbHelper(context);
    SQLiteDatabase collectionDB = dbHelper.getWritableDatabase();
}

and in Button onClick method call it :

PhotoDBMS photoDBMS = new PhotoDBMS(getActivity());
photoDBMS.createDB();

OR move both lines inside PhotoDBMS class constructor

Comments