如何将用户输入添加到数据库并在ListFragment中显示?

时间:2017-07-07 19:33:50

标签: java android sqlite listview android-fragments

我使用SQLite数据库和游标适配器在我的片段中创建listview。我有一个帮助类来创建初始表:

TaskDatabase(Context context){
    super(context, DB_NAME, null, DB_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db){
    updateDB(db,0, DB_VERSION);
}

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

private void updateDB(SQLiteDatabase db, int oldVersion, int newVersion){
    if(oldVersion < 2 ){
        db.execSQL("CREATE TABLE TASK("
                +"_id INTEGER PRIMARY KEY AUTOINCREMENT, "
                +"NAME TEXT, "
                +"DESCRIPTION TEXT);");
        insertTask(db, "get milk");
        insertTask(db, "walk dog");
    }
}

然后在我的片段中,我创建了SQLitedb对象,游标,并设置了适配器。但是,出于某种原因,当我运行应用程序时,数据库中的初始项目不会出现在我的列表视图中。

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    try{
        SQLiteOpenHelper taskDbHelper = new TaskDatabase(getActivity());
        db = taskDbHelper.getReadableDatabase();
        cursor = db.query("TASK",
                new String[]{"_id", "NAME"},
                null,null,null,null,null);
        CursorAdapter listAdapter = new SimpleCursorAdapter(getActivity(),
                android.R.layout.simple_list_item_1,
                cursor,
                new String[]{"NAME"},
                new int[]{android.R.id.text1},
                0);
        setListAdapter(listAdapter);
    } catch (SQLiteException e){
        Toast toast = Toast.makeText(getActivity(),"Database unavailable", Toast.LENGTH_SHORT);
        toast.show();
    }
}

最后一个是我的quicAdd方法,它是一个从edittext框中检索用户输入的按钮。我想将其提供给数据库并在listfragment中显示它。

public void onQuickAdd(View v){
    EditText button = (EditText) findViewById(R.id.quick_add);
    String task = button.getText().toString();
    if(task.length() < 1){
        Toast toast = Toast.makeText(this,"Please enter a task", Toast.LENGTH_SHORT);
        toast.show();
        return;
    }


    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(button.getWindowToken(), 0);
    button.setText(new char[] {}, 0, 0);

0 个答案:

没有答案