如何在数据库中添加和删除项目时动态更新列表视图?

时间:2013-06-05 00:37:07

标签: android listview

我知道在这里有很多建议来更新列表视图,我已经尝试过但没有任何效果。你能帮我么?我不知道我是否错过了什么。这是我的代码:

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();

当我勾选提交按钮时,我想在不离开页面的情况下自动更新lisview。当我单击列表视图时,将出现一个警告对话框,询问用户是否要删除所选项目,如果用户单击确定按钮,它已在我的数据库中删除但列表视图未更新。我仍然需要离开页面才能看到更新的listview。我试图将代码放在下面,但没有任何作用。 ()

simpleAdapterConsumerList.notifyDataSetChanged(); 

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

这里是我在数据库中添加新数据的代码

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{
          ....          
        }

在我的删除按钮上。这是我的代码

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;

}

4 个答案:

答案 0 :(得分:1)

这有两个部分:

<强> 1。支持适配器的Cursor不会自行更改。

支持适配器的Cursor指向查询的结果。当数据库中的数据发生更改时,Cursor仍指向相同的结果集。您需要再次查询以获取更新的数据。无论何时手动删除项目,都可以自己执行此操作。

如果您为数据库设置了合适的ContentProvider,则可以使用ContentObserver和/或CursorLoader(设置ContentObserver本身)并确保在您的ContentProvider的query(...)方法中执行此操作:

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

<强> 2。如果你得到一个新的Cursor,你需要替换旧的Cursor。

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

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

答案 1 :(得分:0)

处理游标适配器时,需要调用swapCursor()并传递更新的游标,然后调用notifyDataSetChanged

答案 2 :(得分:0)

在调用notifyDataSetChanged()之前,您应该更新引用适配器的 ConsumerList 。 从你的代码,我猜你使用了ListAdapter或他的子类,我没有测试其他API级别,但我相信API级别16(JELLY_BEAN)对ListAdapter.notifyDataSetChanged()不起作用,即使刷新List也是如此。所以,我建议你使用BaseAdapter。

答案 3 :(得分:0)

哥们,

  After calling "NotifyDatasetChanged" also your listview try to access your  "arraylistRegisteredConsumer" arralist. But in this ArrayList you didn't delete or insert the data. 

   That's why your listview again loading same data.

   Perform delete operation in "arraylistRegisteredConsumer" based on "Index" then call

   "NotifyDatasetChanged".