简体   繁体   English

来自sqlite的Android Listview

[英]Android Listview from sqlite

I have been struggling for now days What have I done wrong so that I did not get my data on my listview 我现在一直在苦苦挣扎我做错了什么,所以我没有在listview上获取我的数据

// This is the function inside database class

public ArrayList<HashMap<String, String>> getMessage(){
        ArrayList<HashMap<String, String>> message = new ArrayList<HashMap<String, String>>();
        String selectQuery = "SELECT  * FROM " + TABLE_MESSAGE;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        // Move to first row
        if (cursor.moveToFirst()) {
            do {
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("message_sno", cursor.getString(0));
            map.put("message_sender", cursor.getString(1));
            map.put("message_subject", cursor.getString(2));
            map.put("message_date", cursor.getString(3));
            map.put("message_read_flag", cursor.getString(4));
            } while (cursor.moveToNext());
        }
        // return contact list
        return message;
    }

ANd the following is in my activity that extends ListActivity 以下是我的活动中扩展ListActivity

ArrayList<HashMap<String, String>> emaillist = db.getMessage();
        if(emaillist.size()!=0) {
            Toast.makeText(getApplicationContext(), "this" + emaillist.get(1), Toast.LENGTH_SHORT).show();
            ListView lv = getListView();

            /*<!-- android:id="@+id/inboxlist" -->*/
            ListAdapter adapter = new SimpleAdapter( InboxActivity.this, emaillist,
                    R.layout.inbox_list_item,
                    new String[] {"message_sender","message_subject","message_date","message_read_flag"}, new int[] {
                     R.id.from,R.id.subject,R.id.date,R.id.unread});
            setListAdapter(adapter);
        }

For me I use always this method and it work fine :) 对我来说,我总是使用这种方法,它工作得很好:)

- Frist : -> I declare my variables : - 首先: - >我宣布我的变量:

private ListView lv; //My listview that will contain the informations
DBHelper helper = new DBHelper(this); //DBHelper is the class that contain my database on SQLite
private SQLiteDatabase db; //An instance of SQLiteDatabase that will contain my Database 
private Cursor cursor; //A cursor for the query 
public SimpleCursorAdapter adapter ; //The adapter of my ListView   

- Second : -> I create my ViewBinder : - 第二: - >我创建了我的ViewBinder:

public static ViewBinder viewBinder = new ViewBinder() {

    @Override
    public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
        return false;
    }
};

- Thirdly : -> I declare two tables (The first table contain names of column that I want to display, and the seconde TextView or ImageView... That will contain that informations) : - 第三: - >我声明了两个表(第一个表包含我要显示的列的名称,以及seconde TextView或ImageView ......它将包含该信息):

static final String[] FROM = { "name", "image" };
static final int[] TO = { R.id.txt_name, R.id.img };

- fourthly : -> I declare my listview on the onCreate() method : - 第四: - >我在onCreate()方法上声明我的listview:

lv = (ListView) findViewById(R.id.list);

- fifthly : -> I create my class ViewHolder that contain the object that will contain the information : - 第五: - >我创建了包含将包含信息的对象的ViewHolder类:

static class ViewHolder {

    private TextView txtName;
    private ImageView img;

    public ViewHolder(View vue) {

        txtName = (TextView) vue.findViewById(R.id.txt_name);
        img =(ImageView) vue.findViewById(R.id.img);
    }
}

- sixthly : -> I create my class of arrayAdapter : - 第六: - >我创建了我的arrayAdapter类:

class CustomAdapter extends SimpleCursorAdapter {

    Activity context;
    Cursor c;

    @SuppressWarnings("deprecation")
    public CustomAdapter(Activity context, int layout, Cursor c,
            String[] from, int[] to) {
        super(context, layout, c, from, to);
        this.context = context;
        this.c = c;
        Log.i("custom", "" + c.getCount());
    }
    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        LayoutInflater inflater = getLayoutInflater();
        View row = inflater.inflate(R.layout.informations, null);
        //layout.informations is the layout that contain the textview and image view that will contain my informations
        ViewHolder wrapper = new ViewHolder(row);
        row.setTag(wrapper);

        return (row);
    }
    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        ViewHolder wrapper = (ViewHolder) view.getTag();

        int n_name = c.getColumnIndex("name");

        //Example how i fill my image from informations of SQLite
        if (c.getString(n_name).equals("Suite royale")) {
            wrapper.imge.setImageResource(R.drawable.suite_royale);
        }
        if (c.getString(n_name).equals("Suite familiale")) {
            wrapper.img.setImageResource(R.drawable.suite_familiale);
        }
        wrapper.txtName.setText(c.getString(n_name));
    }
}

- Finally : -> In my onResume() method : - 最后: - >在我的onResume()方法中:

db = helper.getReadableDatabase();
cursor = db.query("Name_of_table", null, null, null, null, null,"_id DESC");
//it's like the SQL query : SELECT * FROM Name_of_table
startManagingCursor(cursor);
adapter = new SimpleCursorAdapter(getApplicationContext(), R.layout.informations, cursor, FROM, TO);
adapter.setViewBinder(viewBinder);
lv.setAdapter(adapter);
SimpleCursorAdapter chambres = new CustomAdapter(this, R.layout.informations,cursor, FROM, TO);
lv.setAdapter(chambres);

//Just doing this you can see your informations in your ListView and if you want a clickListener on your line of the listView just add the code below :

lv.setOnItemClickListener(new OnItemClickListener(){

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                long id) {
            Cursor c = db.query("Name_of_table", null, "_id="+(lv.getCount()-position), null, null, null,null);
//== SELECT * FROM Name_of_table WHERE _id = Id_Selected, so you need an id called (_id) on your table his type is INT AUTO_INCREMANTE for example
            c.moveToFirst();
            Log.i("position", ""+position);
            Log.i("taille","Cursor :"+c.getCount());
            String name= c.getString(c.getColumnIndex("name"));
            Toast.makeText(getBaseContext(), "Name selected is : " + name, Toast.LENGTH_SHORT).show();
            }
        }

    });

I hope this will help you, good luck :) 我希望这会对你有所帮助,祝你好运:)

In your getMessage() method, you instantiate the ArrayList 'message' but then never add to it. 在您的getMessage()方法中,您实例化ArrayList'消息',但从不添加它。 You are therefore always returning an empty dataset for your adapter to use. 因此,您始终返回要使用的适配器的空数据集。

Within each iteration over your cursor rows, add the HashMap you have created to your ArrayList as below: 在光标行的每次迭代中,将您创建的HashMap添加到ArrayList,如下所示:

do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("message_sno", cursor.getString(0));
map.put("message_sender", cursor.getString(1));
map.put("message_subject", cursor.getString(2));
map.put("message_date", cursor.getString(3));
map.put("message_read_flag", cursor.getString(4));
message.add(map);    //Add the map to the message ArrayList
} while (cursor.moveToNext());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM