【问题标题】:how to Listview Refresh after Delete an item on Button Click event in android?在android中删除按钮单击事件上的项目后如何刷新Listview?
【发布时间】:2014-11-26 11:52:28
【问题描述】:

我想从 Listview 中删除一个项目,并在删除一个项目后一次刷新 Listview。怎么可能?

我正在使用 JSON 解析从数据库中获取所有项目,并在单击按钮时删除选定的项目。从数据库中成功删除,但 Listview 一次不刷新。怎么办?

我正在使用 Json 解析。不是本地数据库。

在这种情况下,如何在删除项目时刷新Listview? 请指导我。 提前致谢。

我的代码是, Detail.java 文件

public class Detail extends Activity {
    ListView lstDetail = null;
    /** String */
    String urlGetDetailData = null;

    /** Declare another variable for Listview */
    Adapter1 adapter1 = null;
    ArrayList<Detail> myList = new ArrayList<Detail>();
    /** Hashmap for ListView */
    ArrayList<HashMap<String, String>> dataList = null;

    /** JSON Node names */
    public static final String TAG_MEMBER_ID = "mem_id";
    public static final String TAG_ID = "id";
    public static final String TAG_USER_ID = "userid";
    public static final String TAG_STATUS = "Status";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        onCreateActivity(R.layout.detail);

        initializeWidgets();
    }

    private void initializeWidgets() {
        /** ListView */
        lstDetail = (ListView) findViewById(R.id.lstDetail);

        urlGetDetailData = "http://example.com/getdata.php?id="
                + strId;

        new GetDetailData().execute();
        myList.remove(position);
        Adapter1.this.notifyDataSetChanged();

    }

    /**
     * Async task class to get json by making HTTP call
     * */
    private class GetDetailData extends AsyncTask<Void, Void, Void> {
        JSONObject jsonobject;
        JSONArray jsonarray;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            dataList = new ArrayList<HashMap<String, String>>();
            // Retrieve JSON Objects from the given URL address
            jsonobject = JSONFunctions.getJSONfromURL(urlGetDetailData);

            try {
                // Locate the array name in JSON
                jsonarray = jsonobject.getJSONArray("data");

                for (int i = 0; i < jsonarray.length(); i++) {

                    HashMap<String, String> map = new HashMap<String, String>();
                    jsonobject = jsonarray.getJSONObject(i);
                    // Retrive JSON Objects

                    map.put("mem_id", String.valueOf(jsonobject
                            .getString(TAG_MEMBER_ID)));
                    map.put("id",
                            jsonobject.getString(TAG_ID));

                    map.put("userid", jsonobject.getString(TAG_USER_ID));
                    map.put("Status", jsonobject.getString(TAG_STATUS));

                    dataList.add(map);
                }
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            if (dataList.size() != 0) {
                lstDetail.setVisibility(View.VISIBLE);
                Adapter1 = new Adapter1(Detail.this,
                        dataList);
                lstDetail.setAdapter(Adapter1);
            } else {
                lstDetail.setVisibility(View.GONE);
            }
        }
    }
}

适配器类是, Adapter1.java 文件

public class Adapter1 extends BaseAdapter {
    public ArrayList<HashMap<String, String>> arrData = null;
    Context context = null;
    LayoutInflater layoutInflater = null;
    HashMap<String, String> getDetailData = new HashMap<String, String>();

    /** String */
    String strMemberId = null, urlDelete = null;

    /** Constructor */
    public Adapter1(Context context,
            ArrayList<HashMap<String, String>> arrData) {
        layoutInflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.context = context;
        this.arrData  = arrData;
    }

    @Override
    public int getCount() {
        return arrData.size();
    }

    @Override
    public Object getItem(int position) {
        return arrData.get(position);
    }

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

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder = null;
        if (convertView == null) {
            convertView = layoutInflater.inflate(
                    R.layout.list_item, null);

            viewHolder = new ViewHolder();
            getData = arrData.get(position);

            /** Initialize Widgets */

            viewHolder.imgCancel = (ImageView) convertView
                    .findViewById(R.id.imgCancel);

            viewHolder.imgCancel
                    .setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            strMemberId = arrData.get(
                                    position).get(
                                    Detail.TAG_MEMBER_ID);
                            urlDelete = "http://example.com/delete.php?mem_id="
                                    + strMemberId;
                            new DeleteComments().execute();
                        }
                    });

            /** TextView */
            viewHolder.txtMemberId = (TextView) convertView
                    .findViewById(R.id.txtMemberId);
            viewHolder.txtId = (TextView) convertView
                    .findViewById(R.id.txtId);

            viewHolder.txtDesc = (TextView) convertView
                    .findViewById(R.id.txtDesc);

            /** Set Value */


            viewHolder.txtMemberId.setText(getDetailData 
                    .get(Detail.TAG_MEMBER_ID));
            viewHolder.txtId.setText(getDetailData
                    .get(Detail.TAG_ID));

            viewHolder.txtDesc.setText(getDetailData
                    .get(Detail.TAG_STATUS));

            convertView.setTag(viewHolder);

        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        return convertView;
    }

    /** ViewHolder Class */
    @SuppressLint("NewApi")
    public static class ViewHolder {
        ImageView imgCancel = null;
        TextView txtMemberId = null, txtId = null,txtDesc = null;
    }

    public class DeleteComments extends AsyncTask<Void, Void, Void> {
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            ServiceHandler sh = new ServiceHandler();
            String jsonStr = sh.makeServiceCall(urlDelete,
                    ServiceHandler.GET);
            Log.d("Response : delete join comments", ">" + jsonStr);

            return null;
        }

        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

        };
    }
}

detail.xml 文件是,

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/re/android"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content" >

    <ListView
        android:id="@+id/lstDetail"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
    </ListView>
</RelativeLayout>

list_item.xml 文件是,

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/re/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <LinearLayout
        android:id="@+id/contentLayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/txtId"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="111" />

        <TextView
            android:id="@+id/txtDesc"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <ImageView
        android:id="@+id/imgCancel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:src="@drawable/cancel" />

    <TextView
        android:id="@+id/txtMemberId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/txtUserEventId"
        android:layout_alignBottom="@+id/txtUserEventId"
        android:layout_alignParentLeft="true"
        android:text="222" />
</RelativeLayout>

【问题讨论】:

  • 使用 adapter.notifyDataSetChanged();
  • 在您的自定义适配器中调用 this.notifyDataSetChanged();您正在执行删除功能并从设置为该适配器的 arrayList 中删除该元素
  • @Shrinivas 请在我的代码中更新,因为此代码在剩余的 Listview Refresh 中成功运行...我的代码在哪里更新。
  • 你用过adapter.notifyDataSetChanged();吗?
  • @Reena 只需在postexecute 中添加notifyDataSetChanged()

标签: android listview refresh


【解决方案1】:

在您的自定义适配器调用 this.notifyDataSetChanged(); 中,您正在执行删除功能并从设置为该适配器的 arrayList 中删除该元素

【讨论】:

  • 您正在执行删除功能并从设置为该适配器的 arrayList 中删除该元素
  • 直接从表中删除记录(使用 JSON 解析)。不从 arrayList 中删除记录。
  • @Reena 我同意,但是如果你知道它是哪条记录,你也必须从 ArrayList 中删除你设置给适配器的记录,你可以使用 ArrayList.remove(index);然后使用 notifyDataSetChanged(); :)
  • 谢谢,我得到了解决方案。谢谢你帮助我。
  • 我成功地使用了从数据库中删除项目然后使用 Like this arrayListDetailData.remove(position); DetailAdapter.this.notifyDataSetCha‌​nged(‌​);从列表视图中删除项目,然后从列表视图中删除最后一项未选择的项目。表示从列表视图中的最后一个删除。请帮助我。如何从列表视图项目中删除所选项目?请参阅我的更新问题。
【解决方案2】:

您正在编写删除操作,在该函数中只调用 adapter.notifyDataSetChanged 再次。所以它 refr 在删除操作上再次获取数据,然后再次调用 adapter.notifyDataSetChanged 它将起作用

【讨论】:

  • 但我正在适配器类中编写删除操作,所以我无法编写 adapter.notifyDataSetChanged。我的代码在哪里更改?
  • 好的,我已经合并了类活动和适配器。然后在我将 adapter.notifyDataSetChanged() 放入 DeleteComments 的 postExecute 但没有任何更改之后。
  • @Reena 您不必合并您的类,在自定义适配器中的删除操作中只需编写 notifyDataSetChanged();就是这样
【解决方案3】:

首先把你的适配器代码放到Details.java类中

然后改变这个,

public class DeleteComments extends AsyncTask<Void, Void, Void> {
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            ServiceHandler sh = new ServiceHandler();
            String jsonStr = sh.makeServiceCall(urlDelete,
                    ServiceHandler.GET);
            Log.d("Response : delete join comments", ">" + jsonStr);

            return null;
        }

        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            Adapter1.remove(Adapter1.getItem(position));
        };
    }

希望对你有帮助

【讨论】:

  • 我成功地使用了从数据库中删除项目然后使用 Like this arrayListDetailData.remove(position); DetailAdapter.this.notifyDataSetCha‌​nged();从列表视图中删除项目,然后从列表视图中删除最后一项未选择的项目。表示从列表视图中的最后一个删除。请帮助我。如何从列表视图项目中删除所选项目?查看我的更新问题
【解决方案4】:
     @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = null;
            if (convertView == null) {
                convertView = layoutInflater.inflate(
                        R.layout.list_item, null);

                viewHolder = new ViewHolder();
                getData = arrData.get(position);

                /** Initialize Widgets */

                viewHolder.imgCancel = (ImageView) convertView
                        .findViewById(R.id.imgCancel);

                viewHolder.imgCancel
                        .setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                strMemberId = arrData.get(
                                        position).get(
                                        Detail.TAG_MEMBER_ID);
                                urlDelete = "http://example.com/delete.php?mem_id="
                                        + strMemberId;
                                new DeleteComments().execute();
                            }
                        });

                /** TextView */
                viewHolder.txtMemberId = (TextView) convertView
                        .findViewById(R.id.txtMemberId);
                viewHolder.txtId = (TextView) convertView
                        .findViewById(R.id.txtId);

                viewHolder.txtDesc = (TextView) convertView
                        .findViewById(R.id.txtDesc);

                /** Set Value */


                viewHolder.txtMemberId.setText(getDetailData 
                        .get(Detail.TAG_MEMBER_ID));
                viewHolder.txtId.setText(getDetailData
                        .get(Detail.TAG_ID));

                viewHolder.txtDesc.setText(getDetailData
                        .get(Detail.TAG_STATUS));

                convertView.setTag(viewHolder);

            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
bDelete.setOnClickListener(new OnClickListener(){
@Override
            public void onClick(View view)
            {
                arrData.remove(position);
                notifyDataSetChanged():
            }

});


            return convertView;
        }

【讨论】:

  • 我在 viewHolder.imgCancel 按钮上执行删除操作。我把 viewHolder.imgCancel 按钮代码设为 Last 并设置了 arrData.remove(position); notifyDataSetChanged();但再次删除最后一条记录。 Coreect的位置是get。但删除最后一条记录
  • 请添加行 Log.i("position", ""+ position) 并告诉我您在 logcat 中获得的位置是您要删除的相同位置
【解决方案5】:

为什么要这么复杂?

只需在您的自定义适配器Adapter1OnClickListener 中调用remove(Obj);。并且notifyDataSetChanged也会在removed方法中被调用。

【讨论】:

    猜你喜欢
    • 2013-10-09
    • 2019-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多