0

I am trying to create a new database holding the following components:

  • Name String
  • ImageSource Drawable
  • Location LatLng
  • UniqueId String

Here is the code for the database helper:

public class ContactsDatabaseHelper extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "contactList.db";
    private static final String TABLE_NAME = "contact_table";
    public static final String COL1 = "ID";
    private static final String COL2 = "PERSON_NAME";
    private static final String COL3 = "IMAGESOURCE";
    private static final String COL4 = "LOCATION";
    private static final String COL5 = "UNIQUE_ID";
    private Context context;

    public ContactsDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1/**version**/);
        this.context = context;

    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        String createTable = "CREATE TABLE " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, "
                + " PERSON_NAME TEXT, IMAGESOURCE BLOB, LOCATION TEXT, UNIQUE_ID TEXT)";
        sqLiteDatabase.execSQL(createTable);

        Log.v("onCreate","Database Created!");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME);
        onCreate(db);

        Log.v("onUpgrade","Database Created!");
    }

    public boolean addData(String person_name,int imageSource, LatLng location, String unique_id){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();

        Log.v("addData","Database Created!");

        Gson gson = new Gson();
        String gsonLocation = "";
        if(location != null) {
            gsonLocation = gson.toJson(location, LatLng.class);
        }else{
            gsonLocation = null;
        }

        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), imageSource);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] image = baos.toByteArray();

        contentValues.put(COL2, person_name);
        contentValues.put(COL3, image);
        contentValues.put(COL4, gsonLocation);
        contentValues.put(COL5, unique_id);

        long result  = db.insert(TABLE_NAME, null, contentValues);

        if(result == -1){
            return false;
        }else{
            return true;
        }

    }

I copied this code off from some other database helper, and changed the variables around. However, after the changes, it is causing NullPointerException errors.

Here is the code for adding data to the database from an activity.

@Override
    protected void onResume(){
        //Stuff

        addcontacts = (FloatingActionButton) findViewById(R.id.fabcontacts);

        final ContactsDatabaseHelper contactManager = new ContactsDatabaseHelper(context);

        addcontacts.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final AlertDialog.Builder mBuilder = new AlertDialog.Builder(ContactActivity.this);
                View mView = getLayoutInflater().inflate(R.layout.inital_contactcommit,null);

                mBuilder.setView(mView);
                final AlertDialog dialog = mBuilder.create();
                dialog.show();

                //Get reference to the views in the dialog.

                tempName = nameedit.getText().toString();
                tempUniqueId = uniqueidedit.getText().toString();

                cancelbutton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog.dismiss();
                    }
                });
                doneButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        final AlertDialog.Builder m2Builder = new AlertDialog.Builder(ContactActivity.this);
                        View m2View = getLayoutInflater().inflate(R.layout.contactadd_dialog,null);

                        m2Builder.setView(m2View);
                        final AlertDialog dialog2 = m2Builder.create();


                        //Get reference to views

                        uniqueidfinal.setText(tempUniqueId);
                        nameedit2.setText(tempName);

                        dialog2.show();
                        cancelbutton2.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();
                            }
                        });
                        doneButton2.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {

                                boolean insertData = contactManager.addData(tempName,R.drawable.angelinajolie,null,"hello");

                                if (insertData == true) {
                                    Toast.makeText(ContactActivity.this, "Data Successfully Inserted!", Toast.LENGTH_LONG).show();
                                    Log.v("Database","Data Successfully Inserted!");
                                } else {
                                    Toast.makeText(ContactActivity.this, "Something went wrong :(.", Toast.LENGTH_LONG).show();
                                    Log.v("Database","Data Insert Failed!");
                                }
                            }
                        });
                    }
                });
            }
        });

    }

Here is the error log:

08-26 15:28:15.940 6935-6935/com.example.android.gatheraround E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.android.gatheraround, PID: 6935
                                                                                java.lang.RuntimeException: Unable to resume activity {com.example.android.gatheraround/com.example.android.gatheraround.ContactActivity}: java.lang.NullPointerException
                                                                                    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2788)
                                                                                    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2817)
                                                                                    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250)
                                                                                    at android.app.ActivityThread.access$800(ActivityThread.java:135)
                                                                                    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
                                                                                    at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                    at android.os.Looper.loop(Looper.java:136)
                                                                                    at android.app.ActivityThread.main(ActivityThread.java:5017)
                                                                                    at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                    at java.lang.reflect.Method.invoke(Method.java:515)
                                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
                                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
                                                                                    at dalvik.system.NativeStart.main(Native Method)
                                                                                 Caused by: java.lang.NullPointerException
                                                                                    at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
                                                                                    at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
                                                                                    at com.example.android.gatheraround.ContactsDatabaseHelper.<init>(ContactsDatabaseHelper.java:41)
                                                                                    at com.example.android.gatheraround.ContactActivity.onResume(ContactActivity.java:53)
                                                                                    at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1192)
                                                                                    at android.app.Activity.performResume(Activity.java:5310)
                                                                                    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2778)
                                                                                    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2817) 
                                                                                    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250) 
                                                                                    at android.app.ActivityThread.access$800(ActivityThread.java:135) 
                                                                                    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
                                                                                    at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                                    at android.os.Looper.loop(Looper.java:136) 
                                                                                    at android.app.ActivityThread.main(ActivityThread.java:5017) 
                                                                                    at java.lang.reflect.Method.invokeNative(Native Method) 
                                                                                    at java.lang.reflect.Method.invoke(Method.java:515) 
                                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 
                                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
                                                                                    at dalvik.system.NativeStart.main(Native Method) 
  • `...new ContactsDatabaseHelper(context);` – `context` is null. Don't keep a field for a `Context` in an `Activity`. Just use the `Activity` - i.e., `this`, or `ContactActivity.this`. – Mike M. Aug 26 '17 at 06:43
  • 1
    Thank you! that solved the problem. I thought context was some static variable that you do not really have to asign anything to. –  Aug 26 '17 at 06:47
  • Nope. Anything you declare, you have to initialize. In this case, though, you don't need to, because the current object - the `Activity` instance - is a `Context`, so you just give it that. – Mike M. Aug 26 '17 at 06:50

0 Answers0