Imposible get datos de la database sqlite

El problema es que cuando ejecuto mi código, la aplicación se detiene con un error (java.lang.RuntimeException: no se puede iniciar la actividad ComponentInfo {com.twixt.pranav.pos / com.twixt.pranav.pos.View.Activity.Cart }: java.lang.NullPointerException: Intento de invocar el método virtual 'java.io.File android.content.Context.getDatabasePath (java.lang.String)' en una reference de object nulo) en el código que podría ver que he insertado uno datos manualmente

He visto preguntas similares pero no hay soluciones para eso

Esta es mi 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 } 

Clase de ayuda 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; } } 

Y 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. 

Tu parámetro pasado a SQLiteHelper es nulo. Puede get el context de actividad una vez que el fragment se adjunta a la actividad.

Verifique el ciclo de vida del fragment https://developer.android.com/guide/components/fragments.html

Cambio

 private val database: SQLiteHelper = SQLiteHelper(activity) 

a

 private var database: SQLiteHelper? = null 

Overide onAttach in Fragment e initialization de la database

 database = SQLiteHelper(activity) 

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

  • ¿Cómo puedo unirme a tres entidades en GreenDao?
  • Por qué las entidades Room no funcionan con properties inmutables en Android
  • Agregar / Consultar / Analizar SQLite usando Anko
  • Error al hacer que Enum sea la key principal en la biblioteca de la database de la sala
  • Android (Kotlin): sobrescribe el nombre para la input del logging de llamadas