使用后台线程和sqlite在按钮单击上存储数据

时间:2014-08-14 15:18:28

标签: android multithreading sqlite android-asynctask

[解决] 我重新设计了整个事情:摆脱单例模式,创建插入值的方法并使doInBackground()调用它。

我有一个包含2个表单和一个按钮的活动。因此,当单击按钮时,信息将存储在sqlite数据库中,一旦完成,按钮组将被禁用。我正在使用SQLiteOpenHelper和AsyncTask来完成它。 我的问题:我应该在哪里实例化我的数据库?我错过了什么,有没有更好的方法来做所有这些?

DatabaseHelper:

public class DatabaseHelper extends SQLiteOpenHelper  {

private static DatabaseHelper singleton=null;

synchronized static DatabaseHelper getInstance(Context context) {
    if (singleton == null) {
        singleton = new DatabaseHelper(context);
    }
    return singleton;
}

private DatabaseHelper(Context context) {
    super(context, DBContract.DATABASE_NAME, null, DBContract.SCHEMA_VER);
}

@Override
public void onCreate(SQLiteDatabase db) {
    try {
        db.beginTransaction();
        db.execSQL(DBContract.WordTable.CREATE_TABLE);
        db.setTransactionSuccessful();
    }
    finally {
        db.endTransaction();
    }
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}

public void saveWord(String theWord, String translatedWord) {
    ContentValues newValues = new ContentValues();

    newValues.put(DBContract.WordTable.THEWORD_COLUMN, theWord);
    newValues.put(DBContract.WordTable.TRANSLATED_COLUMN, translatedWord);

    SQLiteDatabase db = getWritableDatabase();
    db.insert(DBContract.DATABASE_NAME, null, newValues);
    }
}

MainActivity:

public class MainActivity extends ActionBarActivity {

private DatabaseHelper dbhelper;
private EditText wordField, translatedField;
private Button addButton;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    DatabaseHelper.getInstance(getApplicationContext());

    wordField = (EditText) findViewById(R.id.word_title);
    translatedField = (EditText) findViewById(R.id.translated_title);
    addButton = (Button) findViewById(R.id.addword_button);

    addButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            new WordSaveTask().execute(wordField.getText().toString(),translatedField.getText().toString());
        }
    });

}

private class WordSaveTask extends AsyncTask<String, Void, Void> {

    @Override
    protected Void doInBackground(String... params) {
        dbhelper.saveWord(params[0], params[1]);

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        addButton.setEnabled(false);
    }
}

}

0 个答案:

没有答案