由于 android 中的空指针异常,我无法获取我的数据

当我尝试使用我的视图数据方法从我的数据库中获取数据时,即使我的数据库有数据,视图数据方法也只会给我空指针异常:


        public String viewdata3(){

   SQLiteDatabase sqLiteDatabase4 = dataBase.getWritableDatabase();

   String [] classdetail = {DataBase.classname,DataBase.studentsnumber};

   @SuppressLint("Recycle") Cursor cursor = sqLiteDatabase4.query(DataBase.tablename1,classdetail,null,

           null,null,null,null,null);

   StringBuilder stringBuilder = new StringBuilder();

   while (cursor.moveToNext()){

       String classnamee = cursor.getString(0);

       int stdntnmbr = cursor.getInt(1);

       stringBuilder.append(classnamee+" "+stdntnmbr+" "+"/n");

   }

   return viewdata3();

每当我调用此方法时,应用程序就会崩溃,对于任何其他类似的方法,数据恢复方法也是如此:


        DataBaseConnection db;

 ArrayAdapter<String> adapter;

 String [] data = {Objects.requireNonNull(db).viewdata3()};



@Override

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main3);

    ListView classes = findViewById(R.id.ListView);

  adapter= new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,data);

  classes.setAdapter(adapter);


婷婷同学_
浏览 181回答 2
2回答

catspeake

我认为问题出在这里&nbsp;String [] data = {Objects.requireNonNull(db).viewdata3()};您应该在调用上面的行之前初始化数据库。&nbsp;@Override&nbsp; &nbsp; protected void onCreate(Bundle savedInstanceState) {&nbsp; &nbsp; &nbsp; &nbsp; super.onCreate(savedInstanceState);&nbsp; &nbsp; &nbsp; &nbsp; setContentView(R.layout.activity_main3);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;db = .... // initialize your db;&nbsp; &nbsp; &nbsp; &nbsp; data = {Objects.requireNonNull(db).viewdata3()};&nbsp; &nbsp; &nbsp; &nbsp; ....&nbsp; &nbsp; }

呼啦一阵风

似乎您想在写入数据之前先读取数据库。我将从android sqllite-example开始:https&nbsp;:&nbsp;//developer.android.com/reference/android/database/sqlite/package-summary不要忘记它是一个内存数据库,这可能意味着当应用程序关闭时你会丢失你的 DB-Data。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java