Mohit G Mohit G - 4 years ago 69
Java Question

String keeps on calling NullPointerException, Not sure where it's getting it from

I was following a tutorial to implementing a SQLite database when I ran into this issue upon running the app for the first time.

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.montymason.sqlitedatabaseproject.MyDBHandler.databaseToString()' on a null object reference


I'm unsure where this null pointer reference is coming from. Below is my code for both the main activity, and the function it calls to in the database handler class.

Any help towards a resolution will be greatly appreciated.

Code for Main activity display function:

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

public class MainActivity extends AppCompatActivity {
// Database Helper
MyDBHandler db;

// TextView
TextView database_contents;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

displayItems();
}

// New entry button.
public void addNewItem_butt(View v){
Intent addnewItem = new Intent(MainActivity.this, addItem.class);
startActivity(addnewItem);
}

public void displayItems(){
String dbItems;
dbItems = db.databaseToString();

if(dbItems != null){
//database_contents.setText("No items to display.");
database_contents.setText(dbItems);
}
else{
//database_contents.setText(dbItems);
database_contents.setText("No items to display.");
}
}}


Code for database handler class returning results to main activity:

public String databaseToString(){
String displayItem = "";

SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME + "WHERE 1";

// Cursor
Cursor readDB = db.rawQuery(query, null);

readDB.moveToFirst();

while(!readDB.isAfterLast()){
if(readDB.getString(readDB.getColumnIndex("productname")) != null){
displayItem += "Product Name - " + readDB.getString(readDB.getColumnIndex("productname")) +
"\nProduct Color - " + readDB.getString(readDB.getColumnIndex("productcolor"));

displayItem += "\n";
}
else{
displayItem += "No items to display.";
}
}
db.close();
return displayItem;
}

Answer Source

The problem is in the line

dbItems = db.databaseToString();

Make sure that you are pulling data in db.

If there is a possibility it will be null, wrap it with a null checker.

if (db != null){
    dbItems = db.databaseToString();
    //then all your related code
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download