Android - 将所有数据库条目读取到listView

时间:2015-07-22 22:22:59

标签: android database listview

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

这是描述数据库的类。

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);



}

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

谢谢:)

2 个答案:

答案 0 :(得分:1)

首先使用Cursor查询数据库:

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

你应该研究每个参数对于游标查询的作用,但基本上如果你正在做一个没有WHERE的SELECT *,那么它将如上所示。

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

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

然后就像L-X的回答一样,循环光标,然后将结果映射到你的模型。

在DatabaseHelper中:

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;

}

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

所以创建一个自定义的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);
        }

    });

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

答案 1 :(得分:0)

您可以使用ArrayList扩展CustomClass,将每个数据存储到不同的变量中。在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();