Reputation: 2737
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?
Upvotes: 0
Views: 523
Reputation: 8186
Repalce
SQLiteDatabase sampleDB = Context.openOrCreateDatabase("WaterElectricityReading", MODE_WORLD_READABLE, null);
with
SQLiteDatabase sampleDB = this.openOrCreateDatabase("WaterElectricityReading", MODE_WORLD_READABLE, null);
Reason :
Activity
is subclass of Context
so you can use this
.openOrCreateDatabase
is not a static method so you cannot call it using class name.Upvotes: 1
Reputation: 10395
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);
Upvotes: 3
Reputation: 2596
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.
Upvotes: 1