listview在android中显示数据库中的数据

Posted

技术标签:

【中文标题】listview在android中显示数据库中的数据【英文标题】:listview display the data from database in android 【发布时间】:2013-08-14 15:19:38 【问题描述】:

我是安卓新手。我想知道如何在列表视图中显示数据库中的数据。它不会向数据库添加数据。我只是显示我们存储在数据库中的任何内容。请帮助我实现这一点...提前致谢...

【问题讨论】:

查找 SimpleCursorAdapter。 看我的问答***.com/a/7568093/964741 【参考方案1】:

使用这些类可能会对您有所帮助

用于创建数据库

package com.example.grapes;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHandler extends SQLiteOpenHelper 

    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "dataManager";

    // Contacts table name
    private static final String TABLE_DATAS = "datas";

    // Contacts Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_ITEM = "item";
    private static final String KEY_COMMENT = "comment";
    private static final String KEY_DATE = "date";
    private static final String KEY_TIME = "time";

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

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) 
        String CREATE_DATAS_TABLE = "CREATE TABLE " + TABLE_DATAS + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_ITEM + " TEXT,"
                + KEY_COMMENT + " TEXT," + KEY_DATE + " TEXT," + KEY_TIME + " TEXT" + ")";
        db.execSQL(CREATE_DATAS_TABLE);
    

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_DATAS);

        // Create tables again
        onCreate(db);
    

    /**
     * All CRUD(Create, Read, Update, Delete) Operations
     */

    // Adding new contact
    void addData(Datas data) 
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_ITEM, data.getItem()); // Contact Name
        values.put(KEY_COMMENT, data.getComment()); // Contact Phone
        values.put(KEY_DATE, data.getDate()); // Contact Name
        values.put(KEY_TIME, data.getTime()); // Contact Phone

        // Inserting Row
        db.insert(TABLE_DATAS, null, values);
        db.close(); // Closing database connection
    

    // Getting single contact
    Datas getData(int id) 
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_DATAS, new String[]  KEY_ID,
                KEY_ITEM, KEY_COMMENT, KEY_DATE, KEY_TIME, KEY_ID + "=?",
                new String[]  String.valueOf(id) , null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        Datas data = new Datas(Integer.parseInt(cursor.getString(0)),
                cursor.getString(1), cursor.getString(2),cursor.getString(3), cursor.getString(4));
        // return contact
        return data;
    

 Datas getItemOnly(int id) 
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_DATAS, new String[]  KEY_ID,
                KEY_ITEM, KEY_COMMENT, KEY_DATE, KEY_TIME, KEY_ID + "=?",
                new String[]  String.valueOf(id) , null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        Datas data = new Datas(Integer.parseInt(cursor.getString(0)),
                cursor.getString(1), cursor.getString(2),cursor.getString(3), cursor.getString(4));
        // return contact
        return data;
    

    // Getting All Contacts
    public List<Datas> getAllDatas() 
        List<Datas> dataList = new ArrayList<Datas>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_DATAS;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) 
            do 
                Datas data = new Datas();
                data.setID(Integer.parseInt(cursor.getString(0)));
                data.setItem(cursor.getString(1));
                data.setComment(cursor.getString(2));
                data.setDate(cursor.getString(3));
                data.setTime(cursor.getString(4));
                // Adding contact to list
                dataList.add(data);
             while (cursor.moveToNext());
        

        // return contact list
        return dataList;
    

    // Updating single contact
    public void updateDatas(int position, String value) 
        SQLiteDatabase db = this.getWritableDatabase();

        String update = "UPDATE datas SET comment = '"+ value +"' WHERE ID = " + position;
        db.execSQL(update);

    

    // Deleting single contact
        public void deleteValues(int position) 
            SQLiteDatabase db = this.getWritableDatabase();
            position = position + 1;
            String id = String.valueOf(position);
            db.delete(TABLE_DATAS, KEY_ID + "="+id,null);
            //Updating table
            //Creating temporary table

            String CREATE_TABLE_COPY = "CREATE TABLE " + "COPIED_TABLE" + "("
                    + KEY_ID + " INTEGER PRIMARY KEY," + KEY_ITEM + " TEXT,"
                    + KEY_COMMENT + " TEXT," + KEY_DATE + " TEXT," + KEY_TIME + " TEXT" + ")";
            db.execSQL(CREATE_TABLE_COPY);
            // Copying necessary columns to new temporary table
            String db_insert_command;
            db_insert_command = "INSERT INTO COPIED_TABLE (" + KEY_ITEM +", " + KEY_COMMENT + ", " + KEY_DATE + ", " + KEY_TIME + ") SELECT " + KEY_ITEM +", " + KEY_COMMENT + ", " + KEY_DATE + ", " + KEY_TIME + " FROM "+ TABLE_DATAS;
            System.out.println(db_insert_command);
            db.execSQL(db_insert_command);
            //Dropping old table
            db.execSQL("DROP TABLE " + TABLE_DATAS);
            //Creating old table again
            String CREATE_TABLE = "CREATE TABLE " + TABLE_DATAS + "("
                    + KEY_ID + " INTEGER PRIMARY KEY," + KEY_ITEM + " TEXT,"
                    + KEY_COMMENT + " TEXT," + KEY_DATE + " TEXT," + KEY_TIME + " TEXT"  + ")";
            db.execSQL(CREATE_TABLE);
            //Copying all fields from temporary table to newly created old table
            db.execSQL("INSERT INTO " + TABLE_DATAS + " SELECT * FROM COPIED_TABLE");
            //Dropping temporary table
            db.execSQL("DROP TABLE COPIED_TABLE");
            db.close();
        


    // Getting contacts Count
    public int getDatasCount() 
        String countQuery = "SELECT  * FROM " + TABLE_DATAS;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        //cursor.close();

        // return count
        return cursor.getCount();
    


对于数据管理使用这个类

package com.example.grapes;

public class Datas 

    //private variables
    int _id;
    String _item;
    String _comment;
    String _date;
    String _time;

    // Empty constructor
    public Datas()

    
    // constructor
    public Datas(int id, String item, String comment, String date, String time)
        this._id = id;
        this._item = item;
        this._comment = comment;
        this._date = date;
        this._time = time;
    

    // constructor
    public Datas(String item, String comment, String date, String time)
        this._item = item;
        this._comment = comment;
        this._date = date;
        this._time = time;
    
    // getting ID
    public int getID()
        return this._id;
    

    // setting id
    public void setID(int id)
        this._id = id;
    

    // getting name
    public String getItem()
        return this._item;
    

    // setting name
    public void setItem(String item)
        this._item = item;
    

    // getting phone number
    public String getComment()
        return this._comment;
    

    // setting phone number
    public void setComment(String comment)
        this._comment = comment;
    

    // getting phone number
    public String getDate()
        return this._date;
    

    // setting phone number
    public void setDate(String date)
        this._date = date;
    

    // getting phone number
    public String getTime()
        return this._time;
    

    // setting phone number
    public void setTime(String time)
        this._time = time;
    

对于列表视图使用这个

package com.example.grapes;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class ListviewActivity extends ListActivity 

    AlertDialog.Builder alert;
    EditText input;
    private static final int TEXT_ID = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);


        input = new EditText(this);
        alert = new AlertDialog.Builder(this);

        final DatabaseHandler db = new DatabaseHandler(this);

        System.out.println("Entered ListViewActivity");

        ArrayList<HashMap<String, String>> Items = new ArrayList<HashMap<String, String>>();

        System.out.println("Arraylist hashmap declared");

        // Reading all values
        Log.d("Reading: ", "Reading all contacts..");
        List<Datas> data = db.getAllDatas();       

        for (Datas val : data) 

                // Writing values to map
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("comment",val.getComment());
            map.put("date", val.getDate());
            map.put("time", val.getTime());
            map.put("item", val.getItem());


            Items.add(map);        
        

     // Adding Items to ListView
        ListAdapter adapter = new SimpleAdapter(this, Items,
                R.layout.list_item,new String[]  "date", "time", "comment", "item" ,
                new int[] R.id.date, R.id.time, R.id.capacity, R.id.price );

            setListAdapter(adapter);

            // selecting single ListView item
             ListView lv = getListView();
            lv.setLongClickable(true);

            lv.setOnItemLongClickListener(new OnItemLongClickListener() 

                public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                        final int pos, long id) 
                    // TODO Auto-generated method stub

//                    Log.v("long clicked","pos"+" "+pos);
                    alert.setTitle("Confirm Delete");
                    // set dialog message
                    alert
                        .setMessage("Do you want to DELETE this entry?")
                        .setCancelable(false)
                        .setPositiveButton("Do it!",new DialogInterface.OnClickListener() 
                            public void onClick(DialogInterface dialog,int id) 
                                // if this button is clicked, close
                                // current activity
                                db.deleteValues(pos);
                                Intent i = new Intent(getApplicationContext(), ListviewActivity.class);
                                startActivity(i);

                            
                          )
                        .setNegativeButton("I need this",new DialogInterface.OnClickListener() 
                            public void onClick(DialogInterface dialog,int id) 
                                // if this button is clicked, just close
                                // the dialog box and do nothing
                                dialog.cancel();
                            
                        );

                        // create alert dialog
                        AlertDialog alertDialog = alert.create();

                        // show it
                        alertDialog.show();

                    return true;
                
            );

            lv.setOnItemClickListener(new OnItemClickListener() 
                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                        final int pos, long id) 
                    // TODO Auto-generated method stub

                    input.setId(TEXT_ID);

                    alert.setView(input);

//                    Log.v("long clicked","pos"+" "+pos);
                    alert.setTitle("Edit the Comment?");

                     String dat = ((TextView) arg1.findViewById(R.id.date)).getText().toString();
                     String tim = ((TextView) arg1.findViewById(R.id.time)).getText().toString();
                     String itm = ((TextView) arg1.findViewById(R.id.price)).getText().toString();

                    // set dialog message
                    alert
                        .setMessage("Edit Comment of " + itm + " on " + dat + " " + tim + " ?")
                        .setCancelable(false)
                        .setPositiveButton("Do it!",new DialogInterface.OnClickListener() 
                            public void onClick(DialogInterface dialog,int id) 
                                // if this button is clicked, close
                                // current activity

                                String value = input.getText().toString();
                                Log.d("User name: ",value);
                                //return;
                               // db.execSQL(TABLE_DATAS, KEY_COMMENT, KEY_ID + " = " + string, null);
                                db.updateDatas(pos+1, value);
                                Intent j = new Intent(getApplicationContext(), ListviewActivity.class);
                                startActivity(j);

                            
                          )
                        .setNegativeButton("I need this",new DialogInterface.OnClickListener() 
                            public void onClick(DialogInterface dialog,int id) 
                                // if this button is clicked, just close
                                // the dialog box and do nothing
                                dialog.cancel();
                            
                        );

                        // create alert dialog
                        AlertDialog alertDialog = alert.create();

                        // show it
                        alertDialog.show();

                
                );
            

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
        return true;
    

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    
        switch (item.getItemId())
        
            case R.id.home:
                ListviewActivity.this.finish();
                return true;
            case R.id.about:
                 Toast.makeText(getApplicationContext(), "This is collection and is created by amdel corporation",
                         Toast.LENGTH_LONG).show();
                return true;
            case R.id.exit:
                finish();
                System.exit(0);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        
    

插入操作使用this

 db.addData(new Datas(item, comment, date, time));

阅读所有项目

for (Datas d : datas) 
    String log = "Id: "+d.getID()+" ,Item: " + d.getItem() + " ,Comment: " + d.getComment() + " ,Date: " + d.getDate() + ",Comment: " + d.getTime();
               // Writing Contacts to log
    Log.d("Item: ", log);

从列表视图中删除

                public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                        final int pos, long id) 
                    // TODO Auto-generated method stub

//                    Log.v("long clicked","pos"+" "+pos);
                    alert.setTitle("Confirm Delete");
                    // set dialog message
                    alert
                        .setMessage("Do you want to DELETE this entry?")
                        .setCancelable(false)
                        .setPositiveButton("Do it!",new DialogInterface.OnClickListener() 
                            public void onClick(DialogInterface dialog,int id) 
                                // if this button is clicked, close
                                // current activity
                                db.deleteValues(pos);
                                Intent i = new Intent(getApplicationContext(), ListviewActivity.class);
                                startActivity(i);

                            
                          )
                        .setNegativeButton("I need this",new DialogInterface.OnClickListener() 
                            public void onClick(DialogInterface dialog,int id) 
                                // if this button is clicked, just close
                                // the dialog box and do nothing
                                dialog.cancel();
                            
                        );

                        // create alert dialog
                        AlertDialog alertDialog = alert.create();

                        // show it
                        alertDialog.show();

                    return true;
                

【讨论】:

【参考方案2】:

你可以在这里找到完美的数据库示例here

(或)

在你的课堂上试试这个,它肯定会奏效。但是你需要看一下链接

filteredCouponsList = new ArrayList<CouponsResponse>();
    ViewCouponsDataBase db1 = new ViewCouponsDataBase(context);
    filteredCouponsList = db1.getByDuration(which);
    setAdapter();

要从数据库中检索数据,请尝试此代码

public ArrayList<CouponsResponse> getByDuration(int msgbyduration) 

    ArrayList<CouponsResponse> byDuration = new ArrayList<CouponsResponse>();
    String selectQuery = null;
    if (msgbyduration == 0) 
        selectQuery = "SELECT  * FROM " + COUPONS_TABLE + " WHERE "
                + VALIDTILL + " <=  DATE('now','1 day') " + " AND "
                + VALIDTILL + " >=  DATE('now') " + " order by "
                + VALIDTILL;
    
    if (msgbyduration == 1) 
        selectQuery = "SELECT  * FROM " + COUPONS_TABLE + " WHERE "
                + VALIDTILL + " <=  DATE('now','7 day') " + " AND "
                + VALIDTILL + " >=  DATE('now') " + " order by "
                + VALIDTILL;
    
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    if (cursor.moveToFirst()) 
        do 
            CouponsResponse rec = new CouponsResponse();
            rec.setId(cursor.getInt(0));
            rec.setMerchantName(cursor.getString(1));
            rec.setIssuedBranchAddress(cursor.getString(2));
            rec.setBranchEmail(cursor.getString(3));
            rec.setBranchContactno(cursor.getString(4));
            rec.setBranchWebsite(cursor.getString(5));
            rec.setCouponIssuedOn(cursor.getString(6));
            rec.setValidFrom(cursor.getString(7));
            byDuration.add(rec);
         while (cursor.moveToNext());
    
    db.close();

    return byDuration;

【讨论】:

【参考方案3】:

您可以像下面这样使用 CursorAdapter:

public class MyCursorAdapter extends CursorAdapter 

    private LayoutInflater mInflater;

    public MyCursorAdapter(Context context, Cursor c, boolean autoRequery) 
        super(context, c, autoRequery);
        mInflater = LayoutInflater.from(context);
    

    @Override
    public void bindView(View convertView, Context context, Cursor cursor) 
        ViewHolder holder = (ViewHolder) convertView.getTag();
        holder.text.setText(cursor.getString(0));
    

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) 
        View item = mInflater.inflate(R.layout.listitem, parent, false);
        ViewHolder holder = new ViewHolder();
        holder.text = (TextView) item.findViewById(R.id.text);
        item.setTag(holder);
        return item;
    

    private static class ViewHolder 
        TextView text;
    

【讨论】:

以上是关于listview在android中显示数据库中的数据的主要内容,如果未能解决你的问题,请参考以下文章

android中怎么将SQLite中的数据显示在Listview中(用Cursor)

android listView,list中有多个值,页面显示两个listView,如何让list中的值在页面中循环显示,谢谢大神…

android开发之路08(ListView&Adapter)

如何将片段中的 ListView 对象的数据传递给 Activity?

如何在Android中的ListView中突出显示行?

android中如何获得listview中的checkbox的值?