The Contact Manager application crashes when I try to open an activity that uses SQLite

advertisements

So basically I am a REAL amateur with a very keen interest in programming. I am well versed in core Java and even Swing. Now I started developing a module for a larger project that me and my programming enthusiast buddies are working on, and I need some help. I am developing a very simple contact manager activity that uses the ViewPager to display three screens, namely an introduction screen that is just two labels, an add contact screen and an list contact screen. Now everything upto opening the pager FragmentActivity is going smoothly, but as soon as I set the pager to open the add contact Fragment, the app crashes. I am using the simple SQLite way and for now am attaching the Fragment class, the database adapter class and the database helper class, with the error messages from logcat. Please help.

ContactEdit.class

package com.example.nikhil.test1;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

public class ContactEdit extends Fragment {
    ContactsAdapter databaseAdapter = new ContactsAdapter(this.getActivity());
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        ViewGroup rootView = (ViewGroup) inflater.inflate(
                R.layout.fragment_contact_edit, container, false);
databaseAdapter.open();

        Button SaveBTN = (Button) getActivity().findViewById(R.id.BtnSave);
        SaveBTN.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                EditText _Name = (EditText) getView().findViewById(R.id.textName);
                EditText _Mobile = (EditText) getView().findViewById(R.id.textMobile);
                EditText _Home = (EditText) getView().findViewById(R.id.textHome);
                EditText _Address = (EditText) getView().findViewById(R.id.textAddress);

                String name = _Name.getText().toString();
                String mobile = _Mobile.getText().toString();
                String home = _Home.getText().toString();
                String address = _Address.getText().toString();

             databaseAdapter.addFriend(name, address, mobile, home);

            }
        });
databaseAdapter.close();
        return rootView;

    }

}

ContactsAdapter.class

package com.example.nikhil.test1;
import android.content.ContentValues;
import android.content.Context;
import android.database.*;
import android.database.sqlite.*;
public class ContactsAdapter {
    private static final String DATABASE_NAME ="myDatabase.db";
    private static final String DATABASE_TABLE ="mainTable";
    private static final int DATABASE_VERSION = 1;

     private SQLiteDatabase db;

    private final Context context;

    private MyDatabaseHelper dbHelper;
    public ContactsAdapter(Context _context){
        context = _context;
        dbHelper = new MyDatabaseHelper(context, DATABASE_NAME, null,DATABASE_VERSION);
    }
    public ContactsAdapter open() throws SQLException {
        try {
            db = dbHelper.getWritableDatabase();
        }
        catch(SQLException ex){
            db=dbHelper.getReadableDatabase();
        }
        return this;
    }
    public void close() {
        db.close();
    }
    public void addFriend(String name, String address, String mobile, String home)

    {

        ContentValues values=new ContentValues(4);

        values.put("name", name);
        values.put("address", address);
        values.put("mobile", mobile);
        values.put("home", home);

        db.insert(DATABASE_TABLE, null, values);

    }
    public Cursor getFriend(int id)
    {
        Cursor res = db.rawQuery( "SELECT * FROM " + DATABASE_TABLE + " WHERE _id=", new String[] { Integer.toString(id) } );
        return res;
    }
    public Cursor getAllFriends() {
        Cursor res = db.rawQuery( "SELECT * FROM friends", null );
        return res;
    }
}

MyDatabaseHelper.class

package com.example.nikhil.test1;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MyDatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_TABLE ="mainTable";
    public static final String KEY_ID="_id";
    public static final String KEY_NAME="name";
    public static final int NAME_COLUMN = 1;

    public static final String KEY_Phone="phone";
    public static final int Phone_COLUMN = 2;

    public static final String KEY_Home="home";
    public static final int Home_COLUMN = 3;

    public static final String KEY_Address="address";
    public static final int Address_COLUMN = 4;

    private static final String DATABASE_CREATE = "create table " +
            DATABASE_TABLE + " (" + KEY_ID +" integer primary key autoincrement, " +KEY_NAME + " text not null,"+KEY_Phone+" text not null,"+KEY_Home+" text,"+KEY_Address+" text);";

    private SQLiteDatabase db;
    public MyDatabaseHelper(Context context, String name,
                            SQLiteDatabase.CursorFactory factory, int version) {

        super(context, name, factory, version);

    }

    @Override
    public void onCreate(SQLiteDatabase database) {

        database.execSQL(DATABASE_CREATE);
    }

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

        onCreate(db);
    }

}

Here is the logcat error log:

06-14 22:31:59.660  30738-30738/com.example.nikhil.test1 E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.nikhil.test1, PID: 30738
    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 com.example.nikhil.test1.ContactsAdapter.open(ContactsAdapter.java:24)
            at com.example.nikhil.test1.ContactEdit.onCreateView(ContactEdit.java:21)
            at android.support.v4.app.Fragment.performCreateView(Fragment.java:1789)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
            at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:490)
            at android.support.v4.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:163)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:1072)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:918)
            at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1440)
            at android.view.View.measure(View.java:17565)
            at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:728)
            at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:464)
            at android.view.View.measure(View.java:17565)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5545)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
            at android.view.View.measure(View.java:17565)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5545)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
            at android.view.View.measure(View.java:17565)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5545)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2652)
            at android.view.View.measure(View.java:17565)
            at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2027)
            at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1185)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1391)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1073)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5903)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:828)
            at android.view.Choreographer.doCallbacks(Choreographer.java:588)
            at android.view.Choreographer.doFrame(Choreographer.java:558)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:814)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5268)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)

I realise it might be something incredibly stupid and obvious, but please be patient and help out a friend. Peace out!


Write it like this:

public class ContactEdit extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    ViewGroup rootView = (ViewGroup) inflater.inflate(
            R.layout.fragment_contact_edit, container, false);
    ContactsAdapter databaseAdapter = new ContactsAdapter(this.getActivity());
    databaseAdapter.open();

    // Rest of your code..!!
}

Initializing ContactsAdapter inside onCreateView() will help in getting Activity by getActivity()

EDIT 1:

Instead of :

 Button SaveBTN = (Button) getActivity().findViewById(R.id.BtnSave);

write this :

 Button SaveBTN = (Button) rootView.findViewById(R.id.BtnSave);