如何动态更新列表视图当您添加和删除数据库中的项目吗? [英] How to dynamically update the listview when you add and delete item in the database?

查看:112
本文介绍了如何动态更新列表视图当您添加和删除数据库中的项目吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有很多的建议在这里,因此及时更新列表视图,我尝试过,但没有任何工程。你能帮我么?我不知道如果我错过了什么。这是我的code:

  simpleAdapterConsumerList =新ConsumerList(RegistrationActivity.this,arraylistRegisteredConsumer,R.layout.registeredconsumerlistattributecell,Constants.REGISTERED_ATTRIBUTE_KEYS,Constants.REGISTERED_ATTRIBUTES_VIEWS,假);
        lv_ConsumersList.setAdapter(simpleAdapterConsumerList);
        registeredConsumerCount = lv_ConsumersList.getCount();
 

当我打勾的提交按钮,我想在不离开页面自动更新lisview。而当我点击列表视图将出现一个警告对话框,询问用户是否要删除所选的项目,如果用户点击确定按钮,它已经被删除了我的数据库,但列表视图不更新。我还需要离开页面,以查看更新listview.I试图把codeS低于但没有任何工程。 ()

  simpleAdapterConsumerList.notifyDataSetChanged();
 

 ((BaseAdapter)lv_ConsumersList.getAdapter())notifyDataSetChanged()。
 

下面的id我的code,在数据库中添加新的数据。

  btn_Register.setOnClickListener(新OnClickListener()
    {
        @覆盖
        公共无效的onClick(视图v)
        {
            EMP = txt_Emp.getText()的toString()。
            姓氏= txt_Lname.getText()的toString()。
            名字= txt_Fname.getText()的toString()。
            Middlename = txt_Mname.getText()的toString()。
            。CP = txt_Cp.getText()的toString();
            。电子邮件= txt_Email.getText()的toString();
            全名=姓氏++名字++ Middlename;
            careFriend =共享preferences.getString(Constants.SHARED_ preFERENCES_CAREFRIEND,);
            的companyName =共享preferences.getString(Constants.SHARED_ preFERENCES_COMPANY_CARE_FRIEND,);
            consumercompany code =共享preferences.getString(Constants.SHARED_ preFERENCES_COMPANY code_CARE_FRIEND,);
            SimpleDateFormat的SDF =新的SimpleDateFormat(MM / DD / YYYY HH:MM);
            emailmark =不发送;
            consumerId =共享preferences.getInt(Constants.SHARED_ preFERENCES_CONSUMER_ID,1);
            consumerId = consumerId + 1;
            如果(!Lastname.equals())
            {
                ....
{
                            字符串currentDateandTime = sdf.format(新日期());
                            databaseAdapter.SaveConsumerDetails(新构造函数(EMP,姓氏,名字,Middlename,CP,电子邮件,全名,careFriend,公司名称,emailmark,currentDateandTime,consumerId,consumercompany code));
                            共享preferencesEditor.putInt(Constants.SHARED_ preFERENCES_CONSUMER_ID,consumerId);
                            共享preferencesEditor.commit();
                            simpleAdapterConsumerList.notifyDataSetChanged();
                            //((BaseAdapter)lv_ConsumersList.getAdapter())notifyDataSetChanged()。
                            // registeredConsumerCount = lv_ConsumersList.getCount();
                            Toast.makeText(RegistrationActivity.this,注册成功。+ currentDateandTime,Toast.LENGTH_LONG).show(); simpleAdapterConsumerList.notifyDataSetChanged();
                            明确();

                        }其他{
          ....
        }
 

这是我的删除按钮。这里是我的code

 公共无效的onClick(DialogInterface对话框,INT ID)
                {
                    databaseAdapter.deleteSelectedItem(ID);
                    Toast.makeText(RegistrationActivity.this,删除+ ID,Toast.LENGTH_LONG).show();
                    simpleAdapterConsumerList.notifyDataSetChanged();
                }

....
最终光标cursorRegisteredConsumer = databaseAdapter.getCursorRegisteredConsumer();

   ....
//我databaseAdapter这里是我的code

公共光标getCursorRegisteredConsumer(){
    光标C = dbSqlite.query(Constants.DATABASE_TABLE_CONSUMER,新的String [] {Constants.DATABASE_COLUMN_ID,Constants.CONSUMER_EMPNO,Constants.CONSUMER_FIRSTNAME,Constants.CONSUMER_LASTNAME,Constants.CONSUMER_MIDDLEINITIAL,Constants.CONSUMER_CELLPHONENO,Constants.CONSUMER_EMAIL,Constants.CONSUMER_FULLNAME,常量。 CONSUMER_CAREFRIEND,Constants.CONSUMER_COMPANY,Constants.CONSUMER_REGISTRATIONDATE,Constants.CONSUMER_EMAILMARK,Constants.CONSUMER_ID,Constants.CONSUMER_COMPANY code},NULL,NULL,NULL,NULL,Constants.DATABASE_COLUMN_ID +ASC);
    。//c.setNotificationUri(getContext()getContentResolver(),URI);
    如果(C!= NULL){
        c.moveToFirst();
    }
    返回℃;

}
 

解决方案

有两部分内容:

1。用于备份您的适配器光标本身不改变。

这是备份您的适配器点从查询的结果集光标。当在数据库中的数据发生变化时,光标仍然指向相同的结果集。您需要再次查询来获取更新的数据。你可以自己做,只要你手动删除的项目。

如果您已经设置了正确的的ContentProvider 为您的数据库,你也可以使用一个 ContentObserver 和/或 CursorLoader (它设置了一个 ContentObserver 本身),只是确保你的ContentProvider的查询(...)方法,你这样做:

 光标光标= ...; //查询
cursor.setNotificationUri(的getContext()getContentResolver(),URI);
返回游标;
 

 

2。如果你得到一个新的光标,你需要替换旧的。

您可能有一个新的光标,但你的适配器仍然使用旧的,所以你需要更换。添加此方法适配器,并调用它时,你得到的查询结果。

 公共无效swapCursor(光标newCursor){
    如果(光标=空&安培;!&安培; oldCursor.isOpen()){
        cursor.close();
    }
    光标= newCursor;
    notifyDataSetChanged();
}
 

I know there's a lot of suggestion here in SO to update the listview, I've tried them but nothing works. Can you please help me? I don't know if I missed something. Here is my code:

simpleAdapterConsumerList= new ConsumerList(RegistrationActivity.this, arraylistRegisteredConsumer, R.layout.registeredconsumerlistattributecell, Constants.REGISTERED_ATTRIBUTE_KEYS, Constants.REGISTERED_ATTRIBUTES_VIEWS, false);
        lv_ConsumersList.setAdapter(simpleAdapterConsumerList);
        registeredConsumerCount = lv_ConsumersList.getCount();

When I tick the submit button i want to automatically update the lisview without leaving the page. And when I clicked listview an alert dialog will appear asking if the user wants to delete the selected item, if the user clicked the OK button it was already deleted in my database but the listview is not updated. I still need to leave the page to see the updated listview.I tried to put codes below but nothing works. ()

simpleAdapterConsumerList.notifyDataSetChanged(); 

and

((BaseAdapter) lv_ConsumersList.getAdapter()).notifyDataSetChanged();

here id my code that add new data in the database

btn_Register.setOnClickListener(new OnClickListener() 
    {
        @Override
        public void onClick(View v) 
        {
            Emp = txt_Emp.getText().toString();
            Lastname = txt_Lname.getText().toString();
            Firstname = txt_Fname.getText().toString();
            Middlename = txt_Mname.getText().toString();
            Cp = txt_Cp.getText().toString();
            Email = txt_Email.getText().toString();
            fullName = Lastname +" "+ Firstname +" "+Middlename;
            careFriend = sharedPreferences.getString(Constants.SHARED_PREFERENCES_CAREFRIEND, "");  
            companyName = sharedPreferences.getString(Constants.SHARED_PREFERENCES_COMPANY_CARE_FRIEND, "");
            consumercompanycode =  sharedPreferences.getString(Constants.SHARED_PREFERENCES_COMPANYCODE_CARE_FRIEND, "");
            SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm");
            emailmark = "Not send";
            consumerId = sharedPreferences.getInt(Constants.SHARED_PREFERENCES_CONSUMER_ID, 1);
            consumerId = consumerId + 1;
            if (!Lastname.equals(""))
            {
                ....
{
                            String currentDateandTime = sdf.format(new Date());
                            databaseAdapter.SaveConsumerDetails(new Constructor(Emp, Lastname, Firstname, Middlename, Cp, Email, fullName, careFriend, companyName, emailmark, currentDateandTime, consumerId, consumercompanycode));
                            sharedPreferencesEditor.putInt(Constants.SHARED_PREFERENCES_CONSUMER_ID, consumerId);
                            sharedPreferencesEditor.commit();
                            simpleAdapterConsumerList.notifyDataSetChanged();
                            //((BaseAdapter) lv_ConsumersList.getAdapter()).notifyDataSetChanged(); 
                            //registeredConsumerCount = lv_ConsumersList.getCount();
                            Toast.makeText(RegistrationActivity.this, "Registered successfully. " + currentDateandTime, Toast.LENGTH_LONG).show();                                                                          simpleAdapterConsumerList.notifyDataSetChanged();
                            Clear();

                        }else{
          ....          
        }

on my delete button. here is my code

public void onClick(DialogInterface dialog, int id) 
                {
                    databaseAdapter.deleteSelectedItem(ID);
                    Toast.makeText(RegistrationActivity.this, "Delete " + ID, Toast.LENGTH_LONG).show();                                                                            
                    simpleAdapterConsumerList.notifyDataSetChanged();
                }

....
final Cursor cursorRegisteredConsumer = databaseAdapter.getCursorRegisteredConsumer();

   ....
//on my databaseAdapter here is my code

public Cursor getCursorRegisteredConsumer(){
    Cursor c = dbSqlite.query(Constants.DATABASE_TABLE_CONSUMER, new String[] { Constants.DATABASE_COLUMN_ID, Constants.CONSUMER_EMPNO, Constants.CONSUMER_FIRSTNAME, Constants.CONSUMER_LASTNAME, Constants.CONSUMER_MIDDLEINITIAL, Constants.CONSUMER_CELLPHONENO, Constants.CONSUMER_EMAIL, Constants.CONSUMER_FULLNAME, Constants.CONSUMER_CAREFRIEND, Constants.CONSUMER_COMPANY, Constants.CONSUMER_REGISTRATIONDATE, Constants.CONSUMER_EMAILMARK,Constants.CONSUMER_ID,Constants.CONSUMER_COMPANYCODE}, null , null, null, null, Constants.DATABASE_COLUMN_ID + " ASC");
    //c.setNotificationUri(getContext().getContentResolver(), uri);
    if (c != null) {
        c.moveToFirst();
    }
    return c;

}

解决方案

There are two parts to this:

1. The Cursor that backs your adapter doesn't change by itself.

The Cursor that backs your adapter points to a set results from a query. When the data in the database changes, the Cursor still points to the same result set. You need to query again to get updated data. You can do this yourself whenever you manually delete an item.

If you've set up a proper ContentProvider for your database, you could instead use a ContentObserver and/or a CursorLoader (which sets up a ContentObserver itself) and just make sure that in your ContentProvider's query(...) method you do this:

Cursor cursor = ...; // query
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;

 

2. If you get a new Cursor, you need to replace the old one.

You may have a new cursor, but your adapter still uses the old one, so you need to replace them. Add this method to your adapter and call it whenever you get the result of a query.

public void swapCursor(Cursor newCursor) {
    if (cursor != null && oldCursor.isOpen()) {
        cursor.close();
    }
    cursor = newCursor;
    notifyDataSetChanged();
}

这篇关于如何动态更新列表视图当您添加和删除数据库中的项目吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆