创建数据库时Android Null指针异常

时间:2013-03-05 11:04:50

标签: android nullpointerexception sqlite

我有一个示例应用程序,用于创建数据库,表并插入一行值。

这是我的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;
}

}

当我逐行调试时,Null pointer exception会在行附近引发:

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

我发现sampleDB为空,并且未创建Database

我的代码有什么问题吗?

3 个答案:

答案 0 :(得分:3)

您正在使用null

初始化您的Context
protected static final android.content.Context Context = null;

因此,当您使用空上下文时,它将抛出一个NPE,您可以使用您的活动上下文设置您的上下文然后使用您的上下文

Context = MainActivity.this;

或只是使用此

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

答案 1 :(得分:1)

您正在初始化为protected static final android.content.Context Context = null; 然后将其用作Context.openOrCreateDatabase("WaterElectricityReading", MODE_WORLD_READABLE, null);

它会产生空指针异常,显而易见。

答案 2 :(得分:1)

Repalce

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

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

原因:

  1. ActivityContext的子类,因此您可以使用this
  2. openOrCreateDatabase不是静态方法,因此您无法使用类名称来调用它。