在SQLiteDatabase Android中越来越多的表清除模拟器数据的必要性

时间:2015-01-09 05:51:22

标签: android android-sqlite

我有一个小疑问,我无法得到令人满意的答案。这是场景:

当我增加现有数据库中的表数时,我在OpenHelper类的onCreate方法中得到一个NPE,但是当我清除模拟器数据后运行相同的应用程序时,一切似乎都奇迹般地运行.... / p>

我不知道为什么会这样,任何解释都会有所帮助......

public static final String DATABASE_NAME = "MONEY_DATABASE";
public static final String TABLE_NAME = "MONEY_TABLE";
public static final String TABLE_FIELDS = "FIELD_TABLE";

public static final int DATABASE_VERSION = 4;

public static final String KEY_ID = "_id";
public static final String KEY_AMOUNT = "amount";
public static final String KEY_DATE = "date_int";

public static final String KEY_TYPE_ID = "type_id";
public static final String KEY_TYPE = "type";
public static final String KEY_TITLE = "field_title";

Context localContext;

public HelperMethods (Context c)
{
    Log.d("dev","HelperMethods object created");
    this.localContext = c;
    localopenhelper = new OpenHelper(localContext);

    if(localContext == null)
    {
        Log.d("dev","localContext is null");
    }

}


public SQLiteDatabase database ;

class OpenHelper extends SQLiteOpenHelper
{
    // CREATE TABLE MONEY_TABLE ( _id INTEGER PRIMARY KEY AUTOINCREMENT, amount DOUBLE);

    private String query = "CREATE TABLE " + TABLE_NAME + " ( " + KEY_ID +  " INTEGER PRIMARY KEY AUTOINCREMENT, "
            + KEY_AMOUNT + " DOUBLE, " + KEY_DATE + " DOUBLE);";

    private String query1 = "CREATE TABLE " + TABLE_FIELDS + " ( " + KEY_TYPE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
           + KEY_TYPE + " TEXT NOT NULL, " + KEY_TITLE + " TEXT NOT NULL);";

    Context helperContext;

    public OpenHelper(Context context)
    {
        super(context, DATABASE_NAME, null , DATABASE_VERSION);

        this.helperContext = context;

    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {
        // NPE occurs exactly at this line..
        db.execSQL(query);

        db.execSQL(query1);
    }

和LogCat的东西:

Process: com.giridharkarnik.moneymanager, PID: 1149
java.lang.NullPointerException
        at com.giridharkarnik.moneymanager.HelperMethods$OpenHelper.onCreate(HelperMethods.java:77)
        at com.giridharkarnik.moneymanager.HelperMethods$OpenHelper.onUpgrade(HelperMethods.java:88)

1 个答案:

答案 0 :(得分:0)

从堆栈跟踪看起来,onUpgrade()包含类似的内容:

onCreate(null);

你需要将你作为参数获得的数据库传递给onUpgrade()onCreate()