【问题标题】:Listview to get all data in list in JSON formatListview 以 JSON 格式获取列表中的所有数据
【发布时间】:2018-04-09 20:57:16
【问题描述】:

我使用 listview 来显示来自 API 的响应,这是一个 JSON 对象。在列表视图下方,将有一个按钮。单击该按钮时,我需要从列表视图中以 JSON 格式获取所有数据。

活动类

package com.aryvart.myaromasupply;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ListView;
import com.aryvart.myaromasupply.Adapter.CartListAdapterKV;
import com.aryvart.myaromasupply.Bean.CommonBean;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * Created by android01 on 28/8/17.
 */

public class CartPageKV extends Activity implements MyInterface {
    String json = null;
    List<CommonBean> movieList = new ArrayList<>();
    RecyclerView recyclerView;
    CartListAdapterKV mAdapter;
    Context context;
    CoordinatorLayout coordinatorLayout;
    Button btn_submit;
    HashMap<String, JSONObject> hsFilterGmap;
    String value;
    JSONArray jsonArray;
    ListView llView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cart_page_kv);
        context = this;
        recyclerView = (RecyclerView) findViewById(R.id.my_recyclerView);
        btn_submit = (Button) findViewById(R.id.btn_submit);
        coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinator_layout);
        llView = (ListView) findViewById(R.id.ll_view);
        loadJSONFromAsset();

        //Response API
        try {
            JSONObject obj = new JSONObject(json);
            Log.e("NN", "json-->" + obj.toString());

            JSONArray respArray = obj.getJSONArray("results");
            Log.e("NN", "respArray-->" + respArray.toString());
            for (int i = 0; i < respArray.length(); i++) {
                JSONObject jsonObj = respArray.getJSONObject(i);
                CommonBean drawerBean = new CommonBean();
                drawerBean.setStr_cart_id(jsonObj.getString("id"));
                drawerBean.setStr_cart_title(jsonObj.getString("name"));
                drawerBean.setStr_quan(jsonObj.getString("quantity"));
                drawerBean.setStr_tot_quant(jsonObj.getString("total_quantity"));
                movieList.add(drawerBean);
            }

            // Getting adapter by passing xml data ArrayList
            mAdapter = new CartListAdapterKV(movieList, context, (MyInterface) context);
            llView.setAdapter(mAdapter);


        } catch (JSONException e) {
            e.printStackTrace();
        }

        //Button Click Event

        btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.e("NN:fc", String.valueOf(hsFilterGmap));
                Iterator myVeryOwnIterator = hsFilterGmap.keySet().iterator();
                JSONArray jsonArray = new JSONArray();
                while (myVeryOwnIterator.hasNext()) {
                    String key = (String) myVeryOwnIterator.next();
                    JSONObject value1 = hsFilterGmap.get(key);
                    Log.e("NN:value", value1.toString());
                    jsonArray.put(value1);

                }

                Log.e("NN:fcAr", jsonArray.toString().replaceAll("\\\\", ""));
                System.out.println("the JSON ARRAY is" + jsonArray.toString());

            }
        });
    }

    public String loadJSONFromAsset() {

        try {

            InputStream is = getAssets().open("data.json");
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            json = new String(buffer, "UTF-8");


        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;

    }


    // Interface to get Checked value from listview(Hashmap for not allowing duplicates)
    @Override
    public HashMap<String, JSONObject> getUnCheckedVal(HashMap<String, JSONObject> strVal, String str_removed_id) {

        hsFilterGmap = strVal;
        Log.e("NN:fc", String.valueOf(hsFilterGmap));
        return hsFilterGmap;
    }
}

适配器类

 package com.aryvart.myaromasupply.Adapter;

import android.content.Context;
import android.support.v7.widget.CardView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import com.aryvart.myaromasupply.Bean.CommonBean;
import com.aryvart.myaromasupply.MyInterface;
import com.aryvart.myaromasupply.R;
import com.like.LikeButton;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.List;

/**
 * Created by android01 on 28/8/17.
 */

public class CartListAdapterKV extends BaseAdapter {
    private List<CommonBean> commonBeanList;
    Context c;
    MyInterface my_interface;
    private static LayoutInflater inflater = null;
    HashMap<String, JSONObject> hsMap = new HashMap<String, JSONObject>();

    // constructor
    public CartListAdapterKV(List<CommonBean> movieList, Context context, MyInterface inter) {
        this.commonBeanList = movieList;
        Log.e("NN", "size-->" + this.commonBeanList);
        this.c = context;
        this.my_interface = inter;
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public int getCount() {
        return commonBeanList.size();
    }

    public Object getItem(int position) {
        return commonBeanList.get(position);
    }

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

    public View getView(final int position, View convertView, ViewGroup parent) {
        View view = convertView;
        if (convertView == null)
            view = inflater.inflate(R.layout.cart_items_kv, parent, false);
        TextView txt_cartTitle;
        final CheckBox cb_box;
        txt_cartTitle = (TextView) view.findViewById(R.id.textView2);
        cb_box = (CheckBox) view.findViewById(R.id.checkBoxKV);
        final CommonBean recyclerBean = commonBeanList.get(position);
        cb_box.setChecked(true);
        txt_cartTitle.setText(recyclerBean.getStr_cart_title());

        //check if checkbox is checked. if yes the add value to hashmap(by default all checkboxes will be checked in listview

        if (cb_box.isChecked()) {
            Toast.makeText(c, "--" + recyclerBean.getStr_cart_title(), Toast.LENGTH_SHORT).show();
            //JSONArray req = new JSONArray();
            JSONObject jsoBj = new JSONObject();
            try {

                jsoBj.put("id", recyclerBean.getStr_cart_id());
                jsoBj.put("value", recyclerBean.getStr_cart_title());
                jsoBj.put("checked", "true");

            } catch (JSONException e) {
                e.printStackTrace();
            }
            hsMap.put(recyclerBean.getStr_cart_id(), jsoBj);
            my_interface.getUnCheckedVal(hsMap, recyclerBean.getStr_cart_id());
            Log.e("NN", "AdpaMap--" + hsMap.toString());

        } else {

            JSONObject jsoBj = new JSONObject();
            try {
                jsoBj.put("id", recyclerBean.getStr_cart_id());
                jsoBj.put("value", recyclerBean.getStr_cart_title());
                jsoBj.put("checked", "false");

            } catch (JSONException e) {
                e.printStackTrace();
            }

            //adding the json object in hashmap to remove duplicates
            hsMap.put(recyclerBean.getStr_cart_id(), jsoBj);
            my_interface.getUnCheckedVal(hsMap, recyclerBean.getStr_cart_id());
            Toast.makeText(c, "-*-" + recyclerBean.getStr_cart_title(), Toast.LENGTH_SHORT).show();
        }
        cb_box.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                final CommonBean recyclerBean = commonBeanList.get(position);
                if (cb_box.isChecked()) {
                    Toast.makeText(c, "--" + recyclerBean.getStr_cart_title(), Toast.LENGTH_SHORT).show();
                    JSONObject jsoBj = new JSONObject();
                    try {

                        jsoBj.put("id", recyclerBean.getStr_cart_id());
                        jsoBj.put("value", recyclerBean.getStr_cart_title());
                        jsoBj.put("checked", "true");

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    hsMap.put(recyclerBean.getStr_cart_id(), jsoBj);
                    my_interface.getUnCheckedVal(hsMap, recyclerBean.getStr_cart_id());
                    Log.e("NN", "AdpaMap--" + hsMap.toString());

                } else {

                    JSONObject jsoBj = new JSONObject();
                    try {
                        jsoBj.put("id", recyclerBean.getStr_cart_id());
                        jsoBj.put("value", recyclerBean.getStr_cart_title());
                        jsoBj.put("checked", "false");

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    hsMap.put(recyclerBean.getStr_cart_id(), jsoBj);
                    my_interface.getUnCheckedVal(hsMap, recyclerBean.getStr_cart_id());
                    Toast.makeText(c, "-*-" + recyclerBean.getStr_cart_title(), Toast.LENGTH_SHORT).show();
                }
            }
        });
        return view;
    }
}

在最初单击按钮时,我将获取位于前台(用户可见)的数据,一旦我滚动剩余的数据正在获取。

谁能帮助我如何在单击按钮时获取列表视图中的所有值?

【问题讨论】:

  • 如果您从 JSON 填充 listView,然后尝试在单击时检索相同的 JSON,那么为什么您不能在填充 listView 后保留 JSON 然后引用它?

标签: android json listview android-recyclerview hashmap


【解决方案1】:

打开这个 cart_items_kv xml 并放置按钮。 转到适配器 并在那里进行事件。您可以通过适配器中的位置获取项目的数据。

另一种解决方案

找到视图后添加点击

public ViewHolder(View itemLayoutView) {
// here `enter code here`
itemLayoutView.setOnClickListener(this);
}

【讨论】:

  • 当我选中和取消选中复选框时,我从适配器获取值。但是我需要在单击单个按钮时将整个 listview 数据作为 JSON 对象。显示在列表视图下方。
猜你喜欢
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 2017-04-30
  • 1970-01-01
  • 2021-09-05
  • 1970-01-01
  • 1970-01-01
  • 2018-01-25
相关资源
最近更新 更多