1

When i try to get the data from my data base using my view data method, it's just gives me null pointer exception even if my data base have data, the view data method :

        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();

whenever i call this method the app just crashes and the same to any other method like this, the data restoration method :

        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);
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Martin Zeitler Oct 30 '18 at 01:54

2 Answers2

0
user3606183
  • 157
  • 9
0

I think the issue is here

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

You should initialize the db before you call above line.

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);
         db = .... // initialize your db;
        data = {Objects.requireNonNull(db).viewdata3()};
        ....
    }
John Joe
  • 12,412
  • 16
  • 70
  • 135
  • i have initialized my data base from my data base class,can you please explain? – Mohnad Mahmoud Oct 31 '18 at 19:37
  • i have initialized before the @override does this matter? because i was able to call it as a variable from the data base class named data base connection,does this matter? – Mohnad Mahmoud Nov 01 '18 at 18:04