使用基本适配器和列表视图显示数据库中的数据

Posted

技术标签:

【中文标题】使用基本适配器和列表视图显示数据库中的数据【英文标题】:Display data from database using base adapter and listview 【发布时间】:2014-06-11 22:28:16 【问题描述】:

我想将 SQLite 数据库中的数据显示到我的自定义列表视图中

这是我的活动:

public class Main_activity extends Activity implements OnItemClickListener


public static final String[] titles = new String[]  "Strawberry",
    "Banana", "Orange" ;

public static final String[] descriptions = new String[] 
    "It is an aggregate accessory fruit",
    "It is the largest herbaceous flowering plant", "Citrus Fruit"
    ;


ListView listView;
List<RowItem> rowItems;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) 
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);


rowItems = new ArrayList<RowItem>();
for (int i = 0; i < titles.length; i++) 
    RowItem item = new RowItem(titles[i], descriptions[i]);
    rowItems.add(item);


listView = (ListView) findViewById(R.id.list);
CustomBaseAdapter adapter = new CustomBaseAdapter(this, rowItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);




@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
    long id) 
Toast toast = Toast.makeText(getApplicationContext(),
        "Item " + (position + 1) + ": " + rowItems.get(position),
        Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();

在这个活动中,listview 将显示来自字符串标题和描述的数据,现在我想用我的 sqlite 数据库中的数据替换这些字符串。 谁能告诉我该怎么做?

提供导致问题的教程链接也很有帮助

【问题讨论】:

使用游标访问您的 sqlite 数据库。迭代游标以获取所有数据并将这些数据添加到列表中。你想要多个数据,然后创建cutim列表。 【参考方案1】:

创建数据库

 public class DatabaseHandler extends SQLiteOpenHelper 

        //Database Version
        private static final int DATABASE_VERSION = 1;
        //Database Name
        private static final String DATABASE_NAME = "Test";
        //Table Name
        private static final String TABLE_TEST = "TestTable";
        //Column Name
        private static final String KEY_ID = "id";
        private static final String KEY_NAME = "name";
        private static final String KEY_AGE = "age";

        public DatabaseHandler(Context context) 
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        

        //Create Table
        @Override
        public void onCreate(SQLiteDatabase db) 
            String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_TEST + "("
                    + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
                    + KEY_AGE + " TEXT" + ")";
            db.execSQL(CREATE_CONTACTS_TABLE);
        

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_TEST);
            onCreate(db);
        

        //Insert Value
        public void adddata(Context context,String movieId,String songId) 
            SQLiteDatabase db = this.getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put(KEY_NAME, movieId);
            values.put(KEY_AGE, songId); 
            db.insert(TABLE_TEST, null, values);
            db.close(); 
        

        //Get Row Count
        public int getCount() 
            String countQuery = "SELECT  * FROM " + TABLE_TEST;
            int count = 0;
            SQLiteDatabase db = this.getReadableDatabase();
            Cursor cursor = db.rawQuery(countQuery, null);
            if(cursor != null && !cursor.isClosed())
                count = cursor.getCount();
                cursor.close();
               
            return count;
        

        //Delete Query
        public void removeFav(int id) 
            String countQuery = "DELETE FROM " + TABLE_TEST + " where " + KEY_ID + "= " + id ;
            SQLiteDatabase db = this.getReadableDatabase();
            db.execSQL(countQuery);
        

        //Get FavList
        public List<FavoriteList> getFavList()
            String selectQuery = "SELECT  * FROM " + TABLE_TEST;
            SQLiteDatabase db = this.getWritableDatabase();
            Cursor cursor = db.rawQuery(selectQuery, null);
            List<FavoriteList> FavList = new ArrayList<FavoriteList>();
            if (cursor.moveToFirst()) 
                do 
                    FavoriteList list = new FavoriteList();
                    list.setId(Integer.parseInt(cursor.getString(0)));
                    list.setName(cursor.getString(1));
                    list.setAge(cursor.getString(2));
                    FavList.add(list);
                 while (cursor.moveToNext());
            
            return FavList;
        

并使用下面的基本适配器创建自定义列表视图

public class ViewAdapter extends BaseAdapter 

        LayoutInflater mInflater;

        public ViewAdapter() 
            mInflater = LayoutInflater.from(context);
        

        @Override
        public int getCount() 
            return favoriteList.size();
        

        @Override
        public Object getItem(int position) 
            return null;
        

        @Override
        public long getItemId(int position) 
            return position;
        

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

            if (convertView == null) 
                convertView = mInflater.inflate(R.layout.listitem,null);
            

            final TextView nameText = (TextView) convertView.findViewById(R.id.nameText);
            nameText.setText("Name : "+favoriteList.get(position).getName());
            final TextView ageText = (TextView) convertView.findViewById(R.id.ageText);
            ageText.setText("Age : "+favoriteList.get(position).getAge());

            final Button edit = (Button) convertView.findViewById(R.id.edit);
            edit.setOnClickListener(new OnClickListener() 
                @Override
                public void onClick(View v) 
                    final Dialog dialog = new Dialog(context);
                    dialog.setContentView(R.layout.row);
                    dialog.setTitle("Add Data to Database");
                    final EditText name = (EditText) dialog.findViewById(R.id.name);
                    final EditText age = (EditText) dialog.findViewById(R.id.age);
                    Button Add = (Button) dialog.findViewById(R.id.Add);
                    Add.setText("Add");
                    Add.setOnClickListener(new OnClickListener() 
                        @Override
                        public void onClick(View v) 
                            if(name.getText().toString() != null && name.getText().toString().length() >0 )
                                if(age.getText().toString() != null && age.getText().toString().length() >0 )
                                    db.updateRow(favoriteList.get(position).getId(), name.getText().toString(), age.getText().toString());
                                    favoriteList = db.getFavList();
                                    listView.setAdapter(new ViewAdapter());
                                    dialog.dismiss();
                                else
                                    Toast.makeText(getApplicationContext(), "Please Enter the Age", Toast.LENGTH_LONG).show();  
                                
                            else
                                Toast.makeText(getApplicationContext(), "Please Enter the Name", Toast.LENGTH_LONG).show(); 
                            
                        
                    );
                    dialog.show();  
                
            );
            final Button delete = (Button) convertView.findViewById(R.id.delete);
            delete.setOnClickListener(new OnClickListener() 
                @Override
                public void onClick(View v) 
                    db.removeFav(favoriteList.get(position).getId());
                    notifyDataSetChanged();
                    favoriteList = db.getFavList();
                    listView.setAdapter(new ViewAdapter());
                
            );
            return convertView;
        
    

从数据库中获取数据:

favoriteList = db.getFavList();

最后添加适配器

listView.setAdapter(new ViewAdapter());

如果您需要更多帮助,请查看以下网址

http://mylearnandroid.blogspot.in/2014/04/android-sqlite-with-custom-listview.html

【讨论】:

我有一个小问题:它是什么 R.id.name ......因为没有这样的 id 是用 xml 写入的,并且类似地 Add 没有写入????。请指定,因为我也是 android 的新手。还有什么是 dialog.setContentView(R.layout.row);?????????

以上是关于使用基本适配器和列表视图显示数据库中的数据的主要内容,如果未能解决你的问题,请参考以下文章

使用基本适配器和列表视图显示来自 SQLite 的变量数据

1.2列表显示的三元素:数据视图适配器

RecyclerView 适配器 - 列表正在更新,但视图没有

列表视图适配器实现

尝试通过列表视图显示数据时应用程序崩溃

使用数组适配器对列表视图进行排序