Unable to get data from sqlite database

2019-03-05 05:14发布

问题:

The problem is that when I run my code the app is stopping with an error (java.lang.RuntimeException: Unable to start activity ComponentInfo{com.twixt.pranav.pos/com.twixt.pranav.pos.View.Activity.Cart}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getDatabasePath(java.lang.String)' on a null object reference) in the code you could see that I have inserted one data manually

I have seen similar questions but no solutions for it

This is my class

  class FragmentCart : Fragment() {
    private val database: SQLiteHelper = SQLiteHelper(activity)

     override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
            val mView = inflater!!.inflate(R.layout.fragment_cart, container, false)
     if (database != null) {
                val array_list = database.cartdatas()
                Toast.makeText(activity, "" , Toast.LENGTH_SHORT).show()
            }
 return mView
    }

Sqlite helper class

public class SQLiteHelper extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "POS_SQLiteDatabase.db";

    public SQLiteHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table CATEGORIES (ID INTEGER, NAME VARCHAR, COLOR VARCHAR)");
        db.execSQL("create table CART (ITEM_ID INTEGER, ITEM_NAME VARCHAR, QUANTITY FLOAT, PRICE FLOAT, ONLINE INTEGER, DATE_ VARCHAR, FLAG INTEGER)");

        db.execSQL("insert into CART values(321,'test name',1.1,50,1,'test date',0)");
    }

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

    public  Boolean  insetCartData(int item_id,String item_name,float quantity,float price,int online,String date, String flag){
        SQLiteDatabase database = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();

        contentValues.put("ITEM_ID",item_id);
        contentValues.put("ITEM_NAME",item_name);
        contentValues.put("QUANTITY",quantity);
        contentValues.put("PRICE",price);
        contentValues.put("ONLINE",online);
        contentValues.put("DATE_",date);
        contentValues.put("FLAG",flag);

        database.insert("CART",null,contentValues);

        return true;
    }

    public ArrayList<String> cartdatas(){
       /* SQLiteDatabase database=this.getReadableDatabase();
        Cursor cursor=database.rawQuery("SELECT * FROM CART where ITEM_ID="+id+"",null);
        return cursor;*/
        ArrayList<String> array_list = new ArrayList<String>();

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res =  db.rawQuery( "select * from CART", null );
        res.moveToFirst();

        while(res.isAfterLast() == false){
            array_list.add(res.getString(res.getColumnIndex("ITEM_NAME")));
            res.moveToNext();
        }
        return array_list;
    }


}

And error

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.twixt.pranav.pos, PID: 4602
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.twixt.pranav.pos/com.twixt.pranav.pos.View.Activity.Cart}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getDatabasePath(java.lang.String)' on a null object reference
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
                      at android.app.ActivityThread.-wrap11(Unknown Source:0)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
                      at android.os.Handler.dispatchMessage(Handler.java:106)
                      at android.os.Looper.loop(Looper.java:164)
                      at android.app.ActivityThread.main(ActivityThread.java:6494)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getDatabasePath(java.lang.String)' on a null object reference
                      at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:292)
                      at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:262)
                      at com.twixt.pranav.pos.Controller.SQLiteHelper.cartdatas(SQLiteHelper.java:62)
                      at com.twixt.pranav.pos.View.Fragment.FragmentCart.onCreateView(FragmentCart.kt:38)
                      at android.app.Fragment.performCreateView(Fragment.java:2508)
                      at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1279)
                      at android.app.FragmentManagerImpl.addAddedFragments(FragmentManager.java:2407)
                      at android.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2186)
                      at android.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2142)
                      at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2043)
                      at android.app.FragmentManagerImpl.dispatchMoveToState(FragmentManager.java:3032)
                      at android.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:2979)
                      at android.app.FragmentController.dispatchActivityCreated(FragmentController.java:178)
                      at android.app.Activity.performCreate(Activity.java:7006)
                      at android.app.Activity.performCreate(Activity.java:6991)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) 
                      at android.app.ActivityThread.-wrap11(Unknown Source:0) 
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) 
                      at android.os.Handler.dispatchMessage(Handler.java:106) 
                      at android.os.Looper.loop(Looper.java:164) 
                      at android.app.ActivityThread.main(ActivityThread.java:6494) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 
Application terminated.

回答1:

Your param passed to SQLiteHelper is null. You can get the activity context once the fragment is attached to the activity.

Check the lifecycle of fragment https://developer.android.com/guide/components/fragments.html

Change

private val database: SQLiteHelper = SQLiteHelper(activity)

to

private var database: SQLiteHelper? = null

Overide onAttach in Fragment and initialize database

database = SQLiteHelper(activity)

https://developer.android.com/reference/android/app/Fragment.html#onAttach(android.app.Activity)