0

I have a sample app which creates a database, table and inserts a row of values.

Here is my MainActivity.java:

public class MainActivity extends Activity {

protected static final android.content.Context Context = null;
public String ReadingMode="";

@Override
protected void onCreate(Bundle savedInstanceState) {


             SQLiteDatabase sampleDB =  Context.openOrCreateDatabase("WaterElectricityReading", MODE_WORLD_READABLE, null);

             sampleDB.execSQL("CREATE TABLE IF NOT EXISTS " +
                        "SampleTable " +
                        " (LastName VARCHAR, FirstName VARCHAR," +
                        " Country VARCHAR, Age INT(3));");

             sampleDB.execSQL("INSERT INTO " +
                        "SampleTable " +
                        " Values ('Makam','sample','India',25);");

             sampleDB.close();                       
        }


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

}

When I debug line by line, Null pointer exception is raised near the line:

 SQLiteDatabase sampleDB =  Context.openOrCreateDatabase("WaterElectricityReading", MODE_WORLD_READABLE, null); 

I see that sampleDB is null and Database is not being created.

Is any thing wrong with my code?

3 Answers 3

3

you are initializing your Context with null

protected static final android.content.Context Context = null;

so when you are using your null Context , it will throw an NPE, you can Set your Context with your Activity Context and then use your Context

Context = MainActivity.this;

or just use this

SQLiteDatabase sampleDB =  this.openOrCreateDatabase("WaterElectricityReading", MODE_WORLD_READABLE, null);
Sign up to request clarification or add additional context in comments.

Comments

1

You are initializing as protected static final android.content.Context Context = null; and then using it as Context.openOrCreateDatabase("WaterElectricityReading", MODE_WORLD_READABLE, null);

It will produce null pointer exception for obvious.

Comments

1

Repalce

  SQLiteDatabase sampleDB =  Context.openOrCreateDatabase("WaterElectricityReading", MODE_WORLD_READABLE, null);

with

  SQLiteDatabase sampleDB =  this.openOrCreateDatabase("WaterElectricityReading", MODE_WORLD_READABLE, null);

Reason :

  1. Activity is subclass of Context so you can use this.
  2. openOrCreateDatabase is not a static method so you cannot call it using class name.

Comments

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.