无法从sqlite数据库获取数据

时间:2017-12-14 04:50:05

标签: android sqlite kotlin kotlin-android-extensions

问题在于,当我运行我的代码时,应用程序正在停止并出现错误(java.lang.RuntimeException:无法启动活动ComponentInfo {com.twixt.pranav.pos / com.twixt.pranav.pos.View。 Activity.Cart}:java.lang.NullPointerException:尝试在空对象引用上调用虚方法'java.io.File android.content.Context.getDatabasePath(java.lang.String)' 在代码中你可以看到我手动插入了一个数据

我见过类似的问题,但没有解决方法

这是我的课程

  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帮助程序类

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;
    }


}

和错误

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 个答案:

答案 0 :(得分:2)

传递给SQLiteHelper的param为null。将片段附加到活动后,您可以获取活动上下文。

检查片段https://developer.android.com/guide/components/fragments.html

的生命周期

更改

private val database: SQLiteHelper = SQLiteHelper(activity)

private var database: SQLiteHelper? = null

在Fragment中覆盖onAttach并初始化数据库

database = SQLiteHelper(activity)

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