在Android上使用ListView显示数据库中的数据

时间:2011-11-15 23:46:50

标签: android database listview

我是初学者,我正在大学学习机器人。

目前,我正在使用DBAdapter,我正在尝试使用ListView从数据库中显示布局数据(如果有更好的方法,建议我)。

当我运行应用程序时,将调用makeText函数,并显示数据信息。

我希望在ListView上显示一些值,例如名称和数量,而不是显示通知。

我怎样才能得到它?哪个ListView我必须与数据库一起使用? 我想知道ListView的处理数据库。 请指教。

下面的代码:

FridgeDbAdapter.java

public class FridgeDbAdapter
{
public static final String KEY_ROWID = "_id";
public static final String KEY_CATEGORY = "category";
public static final String KEY_NAME = "name";
public static final String KEY_EXPIRED_DATE = "expired_date";
private static final String DATABASE_TABLE = "fridge_table";
private Context ctxt;
private SQLiteDatabase db;
private FridgeDatabaseHelper dbhelper;


public FridgeDbAdapter(Context ctxt)
{
    this.ctxt = ctxt;
}

//DB databaseHelper
public class FridgeDatabaseHelper extends SQLiteOpenHelper
{
    private static final String DATABASE_NAME = "fridge_db";
    private static final int DATABASE_VERSION = 1;
    private static final String DATBASE_CREATE = 
            "create table fridge_table (_id integer primary key autoincrement, "
 + "category text not null, name text not null, expired_date text not null);";

    public FridgeDatabaseHelper(Context ctxt)
    {
        super(ctxt, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {
        db.execSQL(DATBASE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVer, int newVer)
    {
        Log.w(FridgeDatabaseHelper.class.getName(), 
                    "Upgrading database from version " + oldVer + " to "
        + newVer + ", which will delete the old data.");
        db.execSQL("DROP TABLE IF EXISTS fridge_table");
        //Method is called during creation of new database
        onCreate(db);
    }
}

//Open database
public FridgeDbAdapter open() throws SQLException
{
    dbhelper = new FridgeDatabaseHelper(ctxt);
    db = dbhelper.getWritableDatabase();
    return this;
}

//Close database
public void close(){
    dbhelper.close();
}

//Create a new item
public long insertItem(String category, String name, String expired_date)
{
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_CATEGORY, category);
    initialValues.put(KEY_NAME, name);
    initialValues.put(KEY_EXPIRED_DATE, expired_date);
    return db.insert(DATABASE_TABLE, null, initialValues);
}

//update a item
public boolean updateItem(long rowId, String category, 
    String name, String expired_date)
{
    ContentValues updateValues = new ContentValues();
    updateValues.put(KEY_CATEGORY, category);
    updateValues.put(KEY_NAME, name);
    updateValues.put(KEY_EXPIRED_DATE, expired_date);
    return db.update(DATABASE_TABLE, updateValues, KEY_ROWID + "=" + rowId,
            null) > 0;      
}

//delete a item
public boolean deleteItem(long rowId){
    return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}

//return cursor over the list of all items in the database
public Cursor fetchAllItems(){
    return db.query(DATABASE_TABLE, new String[]{KEY_ROWID, KEY_CATEGORY, 
                            KEY_NAME, KEY_EXPIRED_DATE}, 
                   null, null, null, null, null);
}

//return a cursor positioned at the defined item
public Cursor fetchItem(long rowId) throws SQLException{
    Cursor mCursor = db.query(true, DATABASE_TABLE, 
            new String[]{KEY_ROWID, KEY_CATEGORY, KEY_NAME,
    KEY_EXPIRED_DATE}, KEY_ROWID + "=" + rowId, null, null, null, null, null);
    if(mCursor != null){
        mCursor.moveToFirst();
    }
    return mCursor;
}
}

Fridge.java

public class Fridge extends Activity{
//Button goBack;
Button button1;
TextView text;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fridge);

    FridgeDbAdapter db = new FridgeDbAdapter(this);

  //Open database
    db.open();
   //Get all items
   Cursor c = db.fetchAllItems();
    if(c.moveToFirst())
    {
        do
        {
            //Call displayItem method in below
            DisplayItem(c);
        } while (c.moveToNext());
    }
    else
    {
        Toast.makeText(this, "No item found", Toast.LENGTH_SHORT).show();
    }
    db.close();
 }  

public void DisplayItem(Cursor c){
    Toast.makeText(this, "id: " + c.getString(0) + "\n" + 
                    "category: " + c.getString(1) + "\n" +
                    "name: " + c.getString(2) + "\n" + 
                    "expired date: " + c.getString(3), 
                                            Toast.LENGTH_SHORT).show();
}


}

fridge.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Fridger page" />

 <LinearLayout
    android:id="@+id/fridge_List_View"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
 </LinearLayout>

 <Button
    android:id="@+id/add_Btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Add item" />


 </LinearLayout>

5 个答案:

答案 0 :(得分:3)

您可能想要使用它的公式是Loader API,它很棒,因为它可以帮助您有效地处理光标和查询。

  

加载程序可以轻松地在活动中异步加载数据或   分段。

     
      
  • 每个活动和片段都可以使用它们。
  •   
  • 他们提供异步数据加载。
  •   
  • 他们会监控数据来源,并在内容发生变化时提供新结果。
  •   
  • 在配置更改后重新创建时,它们会自动重新连接到上一个加载程序的游标。因此,他们不需要   重新查询他们的数据。
  •   

在ListView或ListFragment中实现LoaderCallbacks,然后覆盖onCreateLoader,onFinishedLoader,onRestartLoader上的方法。使用LoaderManager,getLoaderManager()。initLoader初始化您的加载器,并享受。

我看到它的唯一缺点是,如果你有一个ContentProvider是有用的,但即使你没有,你可以在SO中尝试一些解决方案,如Loader without ContentProvider,一般来说,我已经了解到使用游标,ContentProvider让您的生活变得更加轻松!

答案 1 :(得分:1)

公共类ShowNotificationAdapter扩展了SimpleCursorAdapter {

Cursor dataCursor;
LayoutInflater mInflater;
Context context;
int layoutType;
DatabaseHelper db_helper;

public CustomAdapter(Context context,int layout,Cursor dataCursor,String [] from,                     int [] to){             super(context,layout,dataCursor,from,to);

        this.context=context;
        this.dataCursor = dataCursor;
        mInflater = LayoutInflater.from(context);

        db_helper=new DatabaseHelper(context);
        db_helper.open();           
}

@覆盖     public View getView(final int position,View convertView,ViewGroup parent){

        final ViewHolder holder;

        if(convertView==null)
        {
                 convertView = mInflater.inflate(R.layout.custom_listitem, null);
                 holder = new ViewHolder();

                 holder.name=(TextView)convertView.findViewById(R.id.name);
                 holder.quantity=(TextView)convertView.findViewById(R.id.quantity);
                 holder.otherInfo=(TextView)convertView.findViewById(R.id.otherInfo);                    
        }
        else
        {   
            holder=(ViewHolder)convertView.getTag();
        }

        dataCursor.moveToPosition(position);                

        String nameString=Integer.toString(dataCursor.getString(dataCursor.getColumnIndexOrThrow("name")));//column name of "name"
        holder.name.setText(nameString);

        String quantityString=dataCursor.getString(dataCursor.getColumnIndexOrThrow("quantity")); //column name of "quantity" 
        holder.quantity.setText(quantityString);      

        String otherInfoString=dataCursor.getString(dataCursor.getColumnIndexOrThrow("field_name"));  
        holder.otherInfo.setText(quantityString); 

        return convertView;
}    

static class ViewHolder
{
        TextView name;
        TextView quantity;
        TextView otherInfo;
}
@Override
public Object getItem(int position) {

        return position;
}

}

答案 2 :(得分:0)

您想使用ListActivity。

您需要创建一个游标并在fillData方法中查询数据。

这是一个关于如何做到这一点的体面教程:

http://www.vogella.de/articles/AndroidSQLite/article.html

答案 3 :(得分:0)

答案 4 :(得分:0)

您可以使用SimpleCadorAdapter使用custom_adapter来获取数据库信息。显示在列表视图上。

<强> CustomAdpater.class:

public class CustomAdpater extends SimpleCursorAdapter{

    Cursor dataCursor;
    LayoutInflater mInflater;
    Context context;
    int layoutType;
    DatabaseHelper db_helper;

   public CustomAdapter(Context context, int layout, Cursor dataCursor, String[] from,
                    int[] to) {
            super(context, layout, dataCursor, from, to);

            this.context=context;
            this.dataCursor = dataCursor;
            mInflater = LayoutInflater.from(context);

            db_helper=new DatabaseHelper(context);
            db_helper.open();           
    }

 @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

            final ViewHolder holder;

            if(convertView==null)
            {
                     convertView = mInflater.inflate(R.layout.custom_listitem, null);
                     holder = new ViewHolder();

                     holder.name=(TextView)convertView.findViewById(R.id.name);
                     holder.quantity=(TextView)convertView.findViewById(R.id.quantity);
                     holder.otherInfo=(TextView)convertView.findViewById(R.id.otherInfo);                    
            }
            else
            {   
                holder=(ViewHolder)convertView.getTag();
            }

            dataCursor.moveToPosition(position);                

            String nameString=Integer.toString(dataCursor.getString(dataCursor.getColumnIndexOrThrow("name")));//column name of "name"
            holder.name.setText(nameString);

            String quantityString=dataCursor.getString(dataCursor.getColumnIndexOrThrow("quantity")); //column name of "quantity" 
            holder.quantity.setText(quantityString);      

            String otherInfoString=dataCursor.getString(dataCursor.getColumnIndexOrThrow("field_name"));  
            holder.otherInfo.setText(quantityString); 

            return convertView;
    }    

    static class ViewHolder
    {
            TextView name;
            TextView quantity;
            TextView otherInfo;
    }
    @Override
    public Object getItem(int position) {

            return position;
    }
}

<强> custom_listitem.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent"  
    android:orientation="vertical">
        <TextView android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:padding="5dp"
                  android:id="@+id/name"
                  />
        <TextView android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:padding="5dp"
                  android:id="@+id/quantity"
                  />
        <TextView android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:padding="5dp"
                  android:id="@+id/otherInfo"
                  />
</LinearLayout>

<强> MainActivity.class:

...
ListView listview=(ListView)findViewById(R.id.listview);

Cursor cursor=<get data to be passed to custom adapter>;
String[] from={"name","quantity"};//field names of 'name' and 'quantity'
int[] to={R.id.name,R.id.quantity};      

CustomAdapter ca=new CustomAdapter(context,R.layout.custom_listitem,cursor,from,to);
listview.setAdapter(ca);
ca.notifyDataSetChanged();
...