如何在android上的listview中显示数据库的数据

时间:2014-05-03 17:57:24

标签: android sqlite listview

我想在listView中显示数据库的数据,但我的项目有问题。 在我的代码中的问题是什么? 这是我的代码:

public class Activity2 extends ListActivity {
        DBAdapter db = new DBAdapter(this); 


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            //setContentView(R.layout.activity_activity2);
            db.open();
            Cursor c = db.getAllContacts();
            if (c.moveToFirst())
            {
                do {          
                    DisplayContact(c);
                } while (c.moveToNext());
            }
            db.close();
        }

    public void DisplayContact(Cursor c)
    {

        ListView lstView = getListView();
        //lstView.setChoiceMode(0); //CHOICE_MODE_NONE
        //lstView.setChoiceMode(1); //CHOICE_MODE_SINGLE
        lstView.setChoiceMode(2);   //CHOICE_MODE_MULTIPLE
        lstView.setTextFilterEnabled(true);

       // presidents = getResources().getStringArray(R.array.presidents_array);

        setListAdapter(new ArrayAdapter<DBAdapter>(this,
                android.R.layout.activity_list_item));
    }
    }

**

这是我的数据库:

public class DBAdapter {
    public static final String KEY_ROWID = "_id";
    public static final String KEY_NAME = "name";
    public static final String KEY_PRICE = "price";
    private static final String TAG = "DBAdapter";

    private static final String DATABASE_NAME = "MyDB";
    private static final String DATABASE_TABLE = "contacts";
    private static final int DATABASE_VERSION = 2;

    private static final String DATABASE_CREATE =
        "create table contacts (_id integer primary key autoincrement, "
        + "name text not null, price text not null);";

    private final Context context;    

    private DatabaseHelper DBHelper;
    private SQLiteDatabase db;

    public DBAdapter(Context ctx) 
    {
        this.context = ctx;
        DBHelper = new DatabaseHelper(context);
    }

    private static class DatabaseHelper extends SQLiteOpenHelper 
    {
        DatabaseHelper(Context context) 
        {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) 
        {
            try {
                db.execSQL(DATABASE_CREATE);    
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
        {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS contacts");
            onCreate(db);
        }
    }    

    //---opens the database---
    public DBAdapter open() throws SQLException 
    {
        db = DBHelper.getWritableDatabase();
        return this;
    }

    //---closes the database---    
    public void close() 
    {
        DBHelper.close();
    }

    //---insert a contact into the database---
    public long insertContact(String name, String price) 
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_NAME, name);
        initialValues.put(KEY_PRICE, price);
        return db.insert(DATABASE_TABLE, null, initialValues);
    }

    //---deletes a particular contact---
    public boolean deleteContact(long rowId) 
    {
        return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    }

    //---retrieves all the contacts---
    public Cursor getAllContacts() 
    {
        return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME,
                KEY_PRICE}, null, null, null, null, null);
    }

    //---retrieves a particular contact---
    public Cursor getContact(long rowId) throws SQLException 
    {
        Cursor mCursor =
                db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
                KEY_NAME, KEY_PRICE}, KEY_ROWID + "=" + rowId, null,
                null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }

    //---updates a contact---
    public boolean updateContact(long rowId, String name, String price) 
    {
        ContentValues args = new ContentValues();
        args.put(KEY_NAME, name);
        args.put(KEY_PRICE, price);
        return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }
}

2 个答案:

答案 0 :(得分:0)

创建一个数组并将从数据库中检索到的值存储在该数组中。

String str[] = new String[cur.getCount()];
for(int i=0;i<str.length;str++){
      //Assign str[i] the value retrived from cursor
}

然后创建一个列表适配器并调用listview.setAdapter

ListAdapter adapter = new ListAdapter(this, R.layout.subcategory_list,
            str);
listView.setAdapter(adapter);

希望这有帮助

答案 1 :(得分:0)

  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_activity2);
        db.open();
        Cursor c = db.getAllContacts();
        if (c.moveToFirst())
        {

           DisplayContact(c);

        }
        db.close();
    }

public void DisplayContact(Cursor c)
{

    ListView lstView = getListView();
    //lstView.setChoiceMode(0); //CHOICE_MODE_NONE
    //lstView.setChoiceMode(1); //CHOICE_MODE_SINGLE
    lstView.setChoiceMode(2);   //CHOICE_MODE_MULTIPLE
    lstView.setTextFilterEnabled(true);

   // presidents = getResources().getStringArray(R.array.presidents_array);

    MyAdapter adapter= new MyAdapter(c);
   lstView.setAdapter(adapter);
}

和自定义适配器类如下。

 class MyAdapter extends BaseAdapter {
    Cursor mCurosr;
    MyAdapter (Cursor c) {
        mCursor=c;
    }



    public int getCount() {
        // TODO Auto-generated method stub
        return mCursor.getCount();
    }

    public Object getItem(int arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

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

        LayoutInflater inflater = getLayoutInflater();
        View row;
        row = inflater.inflate(R.layout.custom, parent, false);
        TextView title, detail;
        //set data to ur view
        mCursor.moveToPosition(position);
        //now get ur data from cursor for each row using mCursor using cursor methods.

        return (row);
    }
}