Android数据持久性 - 插入数据

时间:2015-06-09 00:35:53

标签: java android android-sqlite

我正在尝试创建数据库并在按钮单击时插入新数据。但我收到异常,应用程序关闭。我认为我在按钮点击事件中传递上下文时出错了。

创建数据库的类:

public class DB_Config_SQLLite extends SQLiteOpenHelper{

    private static final String DB_NAME = "mining.db";
    private static final int DB_VERSION = 1;

    //Mining Table functionality
    public static final String MINING_TABLE = "MINING";
    public static final String COLUMN_MINING_DBFIELD1 = "DBFIELD1";
    public static final String COLUMN_MINING_DBEMAIL = "DBEMAIL";

    public static String Create_Mining = 
            "CREATE TABLE "+ MINING_TABLE+"("
            +BaseColumns._ID +"INTEGER PRIMARY KEY SUTOINCREMENT,"+
            COLUMN_MINING_DBFIELD1 +"TEXT," +
            COLUMN_MINING_DBEMAIL +"TEXT)";

  public DB_Config_SQLLite(Context context){ super (context, DB_NAME, null, DB_VERSION);}
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(Create_Mining);
    }

要插入数据的类

public class MiningDataSource {
    private Context mContext;
    private DB_Config_SQLLite mMiningSqliteHelper;

    public MiningDataSource(Context context){
        mContext = context;
        mMiningSqliteHelper = new DB_Config_SQLLite(context);
    } 

    public void create(Datamining_DB_Fields fields)
    {
        SQLiteDatabase database= open();
        database.beginTransaction();

        ContentValues field_values = new ContentValues();
        field_values.put(DB_Config_SQLLite.COLUMN_MINING_DBFIELD1, fields.getVariable_field1name() );
        field_values.put(DB_Config_SQLLite.COLUMN_MINING_DBEMAIL, fields.getVariable_field2email());
        long fieldsID = database.insert(DB_Config_SQLLite.MINING_TABLE, null, field_values);

        database.setTransactionSuccessful();
        database.endTransaction();

        close(database);

    }

类触发按钮点击:

Button b = (Button)findViewById(R.id.btnnext);
b.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) { Fields.setVariable_field1name(mchangingfield.getText().toString());
        Fields.setVariable_field2email(mfieldcount.getText().toString());

        MiningDataSource dataSource = new MiningDataSource(getBaseContext());
        dataSource.create(Fields);
    }
 });

0 个答案:

没有答案