使用sql数据库项填充列表视图

时间:2013-06-27 12:08:50

标签: android database android-listview sqldataadapter

我的应用程序基于当用户输入“添加类别”按钮时显示一个对话框。然后,它应该将数据保存到SQL数据库中,并使用用户添加的每个项目填充列表视图。我选择了SQL数据库,因为我希望在用户结束应用程序时保存数据。如何使用这些项目实际填充列表视图?以下是我到目前为止的情况:

public class CategoryDatabase {

public static final String KEY_ROWID = "_id";
public static final String KEY_CATEGORY = "category";

private static final String DATABASE_NAME = "DBCategory";
private static final String DATABASE_TABLE = "categoryTable";
private static final int DATABASE_VERSION = 1;

private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;

public CategoryDatabase(Context c){
    ourContext = c;
}

public CategoryDatabase open() throws SQLException{
    ourHelper = new DbHelper(ourContext);
    ourDatabase = ourHelper.getWritableDatabase();
    return this;
}

public void close(){
    ourHelper.close();
}

private static class DbHelper extends SQLiteOpenHelper{

    public DbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
                KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                KEY_CATEGORY + " TEXT NOT NULL);"
        );
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
        onCreate(db);
    }

}

public long createEntry(String category) {
    ContentValues cv = new ContentValues();
    cv.put(KEY_CATEGORY, category);
    return ourDatabase.insert(DATABASE_TABLE, null, cv);
}


}

和主要活动:

public class MainActivity extends Activity {

final Context context = this;
ArrayAdapter<String> arrayAdapter;
ArrayList<String> listItems = new ArrayList<String>();
ListView lv;

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

    lv = (ListView)findViewById(R.id.listView1);
    arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, listItems);
    lv.setAdapter(arrayAdapter);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch(item.getItemId()){
    case R.id.menu_add_cat:

        LayoutInflater li = LayoutInflater.from(context);
        View promptAdd = li.inflate(R.layout.prompt_add, null);

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);

        //set prompts.xml to alertDialogBuilder
        alertDialogBuilder.setView(promptAdd);

        final EditText etAddCat = (EditText)promptAdd.findViewById(R.id.etDialogInput);

        //set a dialog message
        alertDialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
            /*
             *    add a cat here 
             *    if(null != input && input.length() > 0){
                    listItems.add(input);
                    arrayAdapter.notifyDataSetChanged();
                }else{
                    Toast.makeText(getApplicationContext(), "Please enter a new category", Toast.LENGTH_LONG).show();

                }
             */
                boolean didItWork = true;
                try{
                    String category = etAddCat.getText().toString();
                    CategoryDatabase entry = new CategoryDatabase(MainActivity.this);
                    entry.open();
                    entry.createEntry(category);

                    entry.close();
                }catch(Exception e){
                    didItWork = false;
                    String error = e.toString();
                    Dialog d = new Dialog(MainActivity.this);
                    d.setTitle("Dang it ! ");
                    TextView tv = new TextView(MainActivity.this);
                    tv.setText(error);
                    d.setContentView(tv);
                    d.show();
                }finally{
                    if(didItWork){
                        Dialog d = new Dialog(MainActivity.this);
                        d.setTitle("Heck yea ! ");
                        TextView tv = new TextView(MainActivity.this);
                        tv.setText("Success");
                        d.setContentView(tv);
                        d.show();
                    }
                }


            }
        })
        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();

        // show it
        alertDialog.show();
        break;
    }
    //return super.onOptionsItemSelected(item);
    return true;
}



}// end of MainActivity

1 个答案:

答案 0 :(得分:2)

getAllCategory()类中创建一个函数CategoryDatabase

public List<String> getAllCategory() {
    List<String> List = new ArrayList<String>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + DATABASE_TABLE;
    Cursor cursor = ourDatabase.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            List.add(cursor.getString(1));
        } while (cursor.moveToNext());
    }
    return List;
   }  

将项目填充到listview。

MainActivity说按钮上点击。

CategoryDatabase entry = new CategoryDatabase(MainActivity.this);
            entry.open();
            List<String> all = entry.getAllCategory();
            lv = (ListView)findViewById(R.id.listView1);
            arrayAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1, all);
            lv.setAdapter(arrayAdapter);

编辑:

onCreate

    CategoryDatabase entry = new CategoryDatabase(MainActivity.this);
            entry.open();
            List<String> all = entry.getAllCategory();
                if(all.size()>0) // check if list contains items.
                {    
            lv = (ListView)findViewById(R.id.listView1);
            arrayAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1, all);
            lv.setAdapter(arrayAdapter);
                }  
                else
                {
                   Toast.makeText(MainActivity.this,"No items to display",1000).show();
                }