【问题标题】:Android - Reading all database entries to a listViewAndroid - 将所有数据库条目读取到 listView
【发布时间】:2015-07-22 22:22:59
【问题描述】:

我正在尝试读取我尝试在列表视图中显示的所有数据库条目。我比较新,所以我不知道我搞砸了哪一部分。

这是描述数据库的类。

public class Item {

    public static final String TABLE = "ITEM";

    // Labels Table Columns names
    public static final String KEY_ID = "id";
    public static final String KEY_NAME = "name";
    public static final String KEY_EXPIRY = "expiry";

    // property help us to keep data
    public int item_ID;
    public String name;
    public int expiry;

}

这是带有 DatabaseHelper 的类

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {
    //version number to upgrade database version
    //each time if you Add, Edit table, you need to change the
    //version number.
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "crud.db";

    public DBHelper(Context context ) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //All necessary tables you like to create will create here

        String CREATE_TABLE_ITEM = "CREATE TABLE " + Item.TABLE  + "("
                + Item.KEY_ID  + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
                + Item.KEY_NAME + " TEXT, "
                + Item.KEY_EXPIRY + " INTEGER )";

        db.execSQL(CREATE_TABLE_ITEM);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed, all data will be gone!!!
        db.execSQL("DROP TABLE IF EXISTS " + Item.TABLE);

        // Create tables again
        onCreate(db);

    }

}

现在我想读取所有数据库条目并在活动中使用 onCreate() 填充列表视图 - 这样当我调用该活动时,就会显示列表。

public class ItemShow extends ListActivity {

TextView item_Id;

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



}

最好的方法是什么?我尝试了很多搜索,但似乎没有一个解决方案有效。

谢谢你:)

【问题讨论】:

  • 刚刚发布了一个答案,并在调用 GetAllItem() 函数之前提醒您,您必须通过创建另一个将行数据添加到表中的函数来用数据填充表

标签: android database listview


【解决方案1】:

首先使用光标查询您的数据库:

Cursor c = db.query(TABLE, null, null, null, null, null, null);

你应该研究一下游标查询的每个参数是什么,但基本上如果你正在做一个没有 WHERE 的 SELECT * 那么它会像上面那样。

最好为您的数据库表创建一个模型。因此,有一个模型类,例如,Entry。

public class Entry {
  public String id;
  public String name;
  public String expiry;
}

然后像 L-X 的回答一样,遍历光标,然后将结果映射到您的模型。

在数据库助手中:

public function getEntries() {
    List<Entry> entries = new ArrayList<Entry>();
       if(c.moveToFirst()){
        do{
            entries.add(createEntryFromCursor(c));

        }while(c.moveToNext());
    }
    return entries;
}


public Entry createEntryFromCursor(Cursor c) {
    if (c == null)
        return null;

    Entry item = new Entry();

    item.id = c.getString(c.getColumnIndex(KEY_ID));
    item.name = c.getString(c.getColumnIndex(KEY_NAME));
    item.expiry = c.getString(c.getColumnIndex(KEY_EXPIRY));

    return item;

}

然后您创建一个使用您的 Entry 模型的 ListAdaptor 并在您的活动中填充该适配器。

所以创建一个自定义的 EntryListAdapter:

public class EntryListAdapter extends ArrayAdapter<Entry> {
private LayoutInflater inflater;
private Context mContext;

private static class ViewHolder {
    TextView id, name, expiry;
}

public EntryListAdapter(Context context, List<Entry> entries){
    super(context, R.id.row, entries);
    this.inflater = LayoutInflater.from(context);
    mContext = context;
}

@Override
public View getView(int position, View convertView, ViewGroup parent){
    ViewHolder holder;

    if(convertView == null){

        convertView = inflater.inflate(R.layout.entries_list_row, null);

        holder = new ViewHolder();

        holder.id = (TextView)convertView.findViewById(R.id.text_id);
        holder.name = (TextView)convertView.findViewById(R.id.text_name);
        holder.expiry = (TextView)convertView.findViewById(R.id.text_expiry);

        convertView.setTag(holder);

    } else {
        holder = (ViewHolder)convertView.getTag();
    }

        Entry entry = getItem(position);
        holder.id.setText(entry.id);
        holder.name.setText(entry.name);
        holder.expiry.setText(entry.expiry);
    }

    return convertView;
  }
}

然后在你的活动中:

    private ListView mListView;
    private EntriesListAdapter mAdapter;

    mListView = (ListView)v.findViewById(R.id.list_view);

    mAdapter = new EntryListAdapter(getActivity(),  databaseHelper.getEntries());
    mListView.setAdapter(mAdapter);

    mListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){

        @Override
        public void onItemClick(AdapterView<?> listView, View view, int pos, long id) {
            Entry entry = (Entry)listView.getItemAtPosition(pos);
        }

    });

未来注意事项:您可能希望根据数据库的大小和视图的响应能力考虑在其自己的线程上查询数据库。

【讨论】:

    【解决方案2】:

    您可以拥有扩展自定义类的 ArrayList,也可以将每个数据存储到不同的变量中。在您的 DBHelper 中定义它

    public ArrayList<String> getAllItem(){
        ArrayList<String> allItem = new ArrayList<>();
    
        String selectQuery = "SELECT * FROM "+Item.TABLE;
        SQLiteDatabase database = this.getWritableDatabase();
    
        Cursor cursor=database.rawQuery(selectQuery,null);
    
        if(cursor.moveToFirst()){
            do{
                String data="";
                data += cursor.getInt(0);
                data += cursor.getString(1);
                data += cursor.getInt(2);
    
                allItem.add(data);
    
            }while(cursor.moveToNext());
        }
        return allItem;
    }
    

    然后调用你的 MainActivity

    DBHelper dbTools = new DBHelper(this);
    ArrayList<String> itemList = dbTools.getAllItem();
    

    【讨论】:

    • 我不建议在 UI 线程中查询数据库,因为您建议您的答案。游标必须在查询结束时关闭。如果您只需要查询,为什么要调用getWritableDatabase() 而不是getReadableDatabase()
    • 你能告诉我为什么它不应该在主 UI 线程上,我应该使用什么 Handler /Aysnc Task 吗?
    • 因为如果您的查询“繁重”或者您有大量数据可供选择,您可能会收到 ANR。使用加载器(在这种情况下为 CursorLoader),它们是为此而设计的,并阅读我在答案中发布的教程。
    • 等一下,让我完成教程,刚刚完成了它的第 4 部分
    猜你喜欢
    • 2023-03-13
    • 1970-01-01
    • 2017-10-25
    • 1970-01-01
    • 1970-01-01
    • 2012-07-26
    • 1970-01-01
    • 2016-12-24
    • 1970-01-01
    相关资源
    最近更新 更多