使用AndroidStudio

时间:2015-06-01 19:54:49

标签: android

我正在尝试在MyProduct表中插入数据,但每次运行程序时都会显示"空指针异常"在MainActivity中的db.insertData()和MyHelper类中的方法insertData()中。有谁能告诉我什么出错?谢谢

MainActivity

public class MainActivity extends Activity {
    MyHelper helper;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        helper=new MyHelper(this);
        SQLiteDatabase sqLiteDatabase=helper.getWritableDatabase();
        // helper.onCreate(sqLiteDatabase);
        helper.insertData();
    }
}

MyHelper.class

public class MyHelper extends SQLiteOpenHelper {
    static final String DATABASE_NAME="MyDatabase";
    static final int DATABASE_VERSION=1;
    static final String TABLE_NAME="MyCatalog";
    static final String UID="ID";
    static final String UTITLE="TITLE";
    static final String UPRICE="PRICE";
    static final String UDESCP="DESCP";

    static final String CREATE_TABLE="CREATE TABLE"+TABLE_NAME+"("+UID+"VARCHAR(25) PRIMARY KEY,"+UTITLE+ "  VARCHAR(255),"+UPRICE+"  VARCHAR(255),"+UDESCP+"  VARCHAR(255));";
    private static final String DROP_TABLE="DROP TABLE" +TABLE_NAME+"IF EXISTS";

    private Context context;

    public MyHelper(Context context)
    {
        super(context,DATABASE_NAME,null,DATABASE_VERSION);
        this.context=context;
        Message.message(context,"Constructor called");
    }

    public void onCreate(SQLiteDatabase db)
    {
        Message.message(context,"on create");
        db.execSQL(CREATE_TABLE);
        Message.message(context,"table created");
    }

    public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion) 
    {
        Message.message(context,"upgrade called");
        db.execSQL(DROP_TABLE);
        onCreate(db);
    }

    ContentValues contentValues;
    public  SQLiteDatabase db;

    public void insertData()
    {
        contentValues.put(UID,"W");
        contentValues.put(UTITLE,"w");
        contentValues.put(UPRICE,"10");
        contentValues.put(UDESCP, "abc");
        db.insert(TABLE_NAME, null, contentValues);
    }
}

1 个答案:

答案 0 :(得分:2)

您尚未初始化dbcontentValues个对象。在insertData方法开始时,请尝试执行以下操作:

db = getWriteableDatabase();
contentValues = new ContentValues();