0

I am getting a NullPointerException related to a certain method within my Android activity.

This activity invokes methods from a database helper class.

The error is related the displayAverageOfAllAttValues() method.

It is important to note that the code was working perfectly with just the displayAverageOfAllMedLevels(), before I added the problem method.

What is the error in my code?

Is it related to not closing the database instance db?

Activity

public class thirdActivity extends ActionBarActivity {

    TextView count;
    TextView avgMed;
    TextView avgAtt;

    DatabaseHelper db = new DatabaseHelper(this);

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

        initialiseVars();

        displayAllResults();
    }

    public void initialiseVars(){
        count= (TextView) findViewById(R.id.tvSummary1);
        avgMed= (TextView) findViewById(R.id.tvSummary2);
        avgAtt= (TextView) findViewById(R.id.tvSummary3);
    }

    //Facade method that then calls all the rest
    public void displayAllResults(){
        displayNumberofGamesPlayed();
        displayAverageOfAllMedValues();
        displayAverageOfAllAttValues();
    }

    public void displayNumberofGamesPlayed(){
        //show how many games have been played
        int totalGamesPlayed = db.getTotalGamesPlayed();
        count.setText("games played " + totalGamesPlayed);
    }

    public void displayAverageOfAllMedValues() {
        //Setting cursor to return value of the method?
        int i = db.getTotalOfAllAvgMedLevels();
        avgMed.setText("Total of med" + i );
    }

    public void displayAverageOfAllAttValues() {
        //Setting cursor to return value of the method?
        int i = db.getTotalOfAllAvgAttLevels();
        avgAtt.setText("Total of att" + i );
    }
}

displayAverageOfAllAttValues() method in databaseHelper class:

public int getTotalOfAllAvgAttLevels(){
    SQLiteDatabase db = this.getWritableDatabase();

    String query = "SELECT SUM(avgattention) FROM " + TABLE_SCORE;

    Cursor c = db.rawQuery(query, null);

    c.moveToFirst(); 
    int i=c.getInt(0);

    return i;
}

LogCat

08-08 00:36:45.400: E/AndroidRuntime(10219): FATAL EXCEPTION: main
08-08 00:36:45.400: E/AndroidRuntime(10219): Process: com.example.brianapp, PID: 10219
08-08 00:36:45.400: E/AndroidRuntime(10219): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.brianapp/com.example.brianapp.thirdActivity}: java.lang.NullPointerException
08-08 00:36:45.400: E/AndroidRuntime(10219):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at android.app.ActivityThread.startActivityNow(ActivityThread.java:2140)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:135)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:347)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:749)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at android.widget.TabHost.setCurrentTab(TabHost.java:413)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at android.widget.TabHost$2.onTabSelectionChanged(TabHost.java:154)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at android.widget.TabWidget$TabClickListener.onClick(TabWidget.java:625)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at android.view.View.performClick(View.java:4633)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at android.view.View$PerformClick.run(View.java:19330)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at android.os.Handler.handleCallback(Handler.java:733)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at android.os.Handler.dispatchMessage(Handler.java:95)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at android.os.Looper.loop(Looper.java:157)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at android.app.ActivityThread.main(ActivityThread.java:5356)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at java.lang.reflect.Method.invokeNative(Native Method)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at java.lang.reflect.Method.invoke(Method.java:515)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at dalvik.system.NativeStart.main(Native Method)
08-08 00:36:45.400: E/AndroidRuntime(10219): Caused by: java.lang.NullPointerException
08-08 00:36:45.400: E/AndroidRuntime(10219):    at com.example.brianapp.thirdActivity.displayAverageOfAllAttValues(thirdActivity.java:78)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at com.example.brianapp.thirdActivity.displayAllResults(thirdActivity.java:55)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at com.example.brianapp.thirdActivity.onCreate(thirdActivity.java:34)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at android.app.Activity.performCreate(Activity.java:5426)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
08-08 00:36:45.400: E/AndroidRuntime(10219):    ... 18 more

The table structure in Database helper class (for reference):

public class DatabaseHelper extends SQLiteOpenHelper {

    // Database Version
    private static final int DATABASE_VERSION = 10;

    // Database Name
    private final static String DATABASE_NAME = "MeditationDatabase";

    // Contacts table name
    private static final String TABLE_SCORE = "scores";

    // Contacts Table Columns names
    private static final String COL_SESSION = "sessionid";
    private static final String COL_GAMETITLE = "game";
    private static final String COL_NAME = "name";
    private static final String COL_MED = "avgmeditation";
    private static final String COL_MAX = "maxmeditation";
    private static final String COL_AVGATT = "avgattention";
    private static final String COL_MAXATT = "maxattention";
    private static final String COL_SCORE = "score";
    private static final String COL_DATE = "date";

    /**
     * Constructor
     * 
     * @param context
     */
    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    /**
     * Method that creates the database
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        //VERY IMPORTANT: ALWAYS CHECK THAT THERE ARE SPACES AND COMMAS IN CORRECT PLACE IN CODE BELOW:

        String CREATE_TABLE_SCORE = "CREATE TABLE " + TABLE_SCORE + "(" + COL_SESSION
            + " STRING PRIMARY KEY, " + COL_GAMETITLE + " STRING, "  + COL_NAME + " STRING, " + COL_MED + " INTEGER, "
            + COL_MAX + " INTEGER, " + COL_AVGATT + " INTEGER, " + COL_MAXATT + " INTEGER, "  + COL_SCORE +  " INTEGER, " + COL_DATE + " STRING " + ")";

        db.execSQL(CREATE_TABLE_SCORE);
    }
3
  • It could be any of the variables in getTotalOfAllAvgAttLevels() not getting set properly. We can offer guesses but you really need to just log them one by one until you find out where it's dying. Commented Aug 8, 2014 at 1:10
  • Where is line 78 of thirdActivity.java? Commented Aug 8, 2014 at 1:19
  • There are only 2 possibilities: db is null, or avgAtt is null. However, since there is nothing wrong with db in other methods, the only possibility is avgAtt is null. Have you checked if the TextView ID is correct? Post your layout XML if you're not sure. Commented Aug 8, 2014 at 1:23

4 Answers 4

1

This

DatabaseHelper db = new DatabaseHelper(this);

is wrong because you are initializing the new DatabaseHelper(Context), when your activity is not created yet, check my code if is not working please tell me.

DatabaseHelper db;////Correction


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

    initialiseVars();

    displayAllResults();



}

public void initialiseVars(){

    count= (TextView) findViewById(R.id.tvSummary1);
    avgMed= (TextView) findViewById(R.id.tvSummary2);
    avgAtt= (TextView) findViewById(R.id.tvSummary3);
    db = new DatabaseHelper(this);////Initializing variable.
}
Sign up to request clarification or add additional context in comments.

7 Comments

Please can you check your logcat and verify if is the same error for focus in that.
yes it is the same error,the null pointer exception, could the error be realted to me not closing the db?
Could be, but i don't think so.
Thank, I do not have a clue what is causing the issue. It is important to note that the code was working perfectly with just the displayAverageOfAllMedLevels(), before I added the problem method.
No i dont speak spanish, sorry!
|
1

I found the solution to my problem.

It was due to the fact that I was setting the content view to the wrong corresponding XML.

I.e. within onCreate():

setContentView(R.layout.summary);

This is the incorrect XML to set to, as a result, there was a null pointer exception as the required TextViews were not able to be found within this layout.

Comments

0

as moveToFirst() returns boolean, try using, :

if(c.moveToFirst()){
    return c.getInt(0);
}

Have something like this:

public int getTotalOfAllAvgAttLevels(){
    SQLiteDatabase db = this.getWritableDatabase();
    String query = "SELECT SUM(avgattention) FROM " + TABLE_SCORE;
    Cursor c = db.rawQuery(query, null);
    if(c.moveToFirst()){
    return c.getInt(0);
}

    return -1; //return whatever you want when c.moveToFirst() condition fails.

    }

Comments

0

I believe the problem is when you are creating the DatabaseHelper instance.

When you do this:

DatabaseHelper db = new DatabaseHelper(this);

at the variable declaration, you're violating the Activity lifecycle. The Activity is considered created when the onCreate method is called. So, instantiate your DatabaseHelper on onCreate method and don't forget to dispose it on onDestroy method:

public class MyActivity extends Activity {
    private DatabaseHelper db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        db = new DatabaseHelper(this);
        ...

        initialiseVars();

        displayAllResults();
    }

    @Override
    protected void onDestroy() {
        db.close();
    }
}

1 Comment

This has not solved the issue, I am still getting the null point exception?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.