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

Posted

技术标签:

【中文标题】使用 sql 数据库项填充列表视图【英文标题】:populating a list view with sql database items 【发布时间】:2013-06-27 12:08:49 【问题描述】:

我的应用程序基于在用户输入“添加类别”按钮时显示一个对话框。然后它应该将数据保存到 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

【问题讨论】:

我已经用按钮而不是菜单项单击尝试了您的代码。如果您添加以下内容,它会起作用。如果您需要进一步的帮助,请告诉我 Populating a list view from SQLite Database的可能重复 【参考方案1】:

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

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;
     

将项目填充到列表视图。

在您的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();
                 

【讨论】:

只有当我点击添加猫按钮时才有效,最初当我启动应用程序时,它是空白的,当我点击按钮时,所有类别都会出现 @Frugo 您可以将代码的第二部分移至onCreate。我将编辑我的答案 @Frugo 欢迎您。如果有帮助,你能投票给答案吗?

以上是关于使用 sql 数据库项填充列表视图的主要内容,如果未能解决你的问题,请参考以下文章

SQL 如何查询指定架构中所有表(或视图)的名称

Android:使用数组项填充列表视图

可视化工具-视图-事物-以及存储过程

推动视图表的自定义 sql

通过 JSON 将背景图像填充到列表视图项中的问题

从视图表中获取数据时出现 Laravel 错误