Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/218.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android-将所有数据库条目读取到listView_Android_Database_Listview - Fatal编程技术网

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

Android-将所有数据库条目读取到listView,android,database,listview,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 =

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

这是描述数据库的类

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



}
最好的方法是什么?我试着寻找了很多,但似乎没有一个解决办法有效


谢谢:)

您可以使用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;
}
public ArrayList getAllItem(){
ArrayList allItem=新的ArrayList();
String selectQuery=“SELECT*FROM”+Item.TABLE;
SQLiteDatabase=this.getWritableDatabase();
Cursor=database.rawQuery(selectQuery,null);
if(cursor.moveToFirst()){
做{
字符串数据=”;
data+=cursor.getInt(0);
data+=cursor.getString(1);
data+=cursor.getInt(2);
allItem.add(数据);
}while(cursor.moveToNext());
}
返回allItem;
}
然后打电话给你的主要活动

DBHelper dbTools = new DBHelper(this);
ArrayList<String> itemList = dbTools.getAllItem();
DBHelper dbTools=新的DBHelper(这个);
ArrayList itemList=dbTools.getAllItem();

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

Cursor c = db.query(TABLE, null, null, null, null, null, null);
您应该研究游标查询的每个参数是什么,但基本上,如果您在执行SELECT*时没有WHERE,那么它将如上面所示

最好为数据库表创建一个模型。例如,有一个名为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;

}
公共函数getEntries(){
列表项=新的ArrayList();
if(c.moveToFirst()){
做{
添加(createEntryFromCursor(c));
}而(c.moveToNext());
}
返回条目;
}
公共条目createEntryFromCursor(光标c){
如果(c==null)
返回null;
条目项=新条目();
item.id=c.getString(c.getColumnIndex(KEY_id));
item.name=c.getString(c.getColumnIndex(KEY_name));
item.expiry=c.getString(c.getColumnIndex(KEY_expiry));
退货项目;
}
然后创建一个使用条目模型的ListAdapter,并在活动中填充该适配器

因此,请创建一个自定义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;
  }
}
公共类EntryListAdapter扩展了ArrayAdapter{
私人充气机;
私有上下文;
私有静态类视图持有者{
TextView id、名称、有效期;
}
公共EntryListAdapter(上下文、列表项){
super(上下文、R.id.row、条目);
this.inflater=layoutiner.from(上下文);
mContext=上下文;
}
@凌驾
公共视图getView(int位置、视图转换视图、视图组父视图){
视窗座;
if(convertView==null){
convertView=充气机。充气(R.layout.entries\u list\u row,null);
holder=新的ViewHolder();
holder.id=(TextView)convertView.findViewById(R.id.text\u id);
holder.name=(TextView)convertView.findViewById(R.id.text\u name);
holder.expiry=(TextView)convertView.findViewById(R.id.text\u expiry);
convertView.setTag(支架);
}否则{
holder=(ViewHolder)convertView.getTag();
}
条目=获取项目(位置);
holder.id.setText(entry.id);
holder.name.setText(entry.name);
holder.expiry.setText(entry.expiry);
}
返回视图;
}
}
然后在您的活动中:

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

    });
private ListView-mListView;
私有EntriesListAdapter-mAdapter;
mListView=(ListView)v.findViewById(R.id.list\u视图);
mAdapter=newentrylistapter(getActivity(),databaseHelper.getEntries());
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(新的AdapterView.OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView列表视图、视图视图、整数位置、长id){
条目=(条目)listView.getItemAtPosition(pos);
}
});

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

刚刚发布了一个答案,并提醒您在调用GetAllItem()函数之前,您必须通过创建另一个将行数据添加到表中的函数来使用数据填充表我不建议在UI线程中查询DB,正如您在回答中建议的那样。必须在查询结束时关闭光标。如果您只需要一个查询,为什么要调用
getWritableDatabase()
而不是
getReadableDatabase()
?您能告诉我为什么它不应该在主UI线程上,以及我应该使用什么处理程序/Aysnc任务吗?因为如果您的查询“繁重”或有大量数据要选择,您可能会得到一个ANR。使用加载器(本例中为游标加载器),它们是为此而设计的,请阅读我在回答中发布的教程。等等,让我来竞争教程,刚刚完成了第4节