Android 使用 BaseAdapter 将 JsonArray 转换为 ListView 中的数组

标签 android listview

我已经设置了一个带有 BaseAdapter 的 Listview,目前它与 setOnItemClickListener 一起工作正常。但这是硬编码。

enter image description here

Main2Activity.java

String sku[]={"1","2","3","4"};
String name[]={"Bad Food","Very Bad Food","Extremly Bad Food","Super Bad Food"};
String price[]={"99","999","9999","99999"};
String quantity[]={"123","456","789","101112"};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);

    ListView listView = (ListView) findViewById(R.id.listView);
    listView.setAdapter(new my_adapter(Main2Activity.this,sku,name,price,quantity));

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Toast.makeText(Main2Activity.this, "Sku->"+sku[i]
                    +" Name->"+name[i]
                    +" Price->"+price[i]
                    +" Quantity->"+quantity[i]
                    ,Toast.LENGTH_SHORT).show();
        }
    });

}

my_adapter.java

public class my_adapter extends BaseAdapter {

Context ctx;
LayoutInflater inflater=null;

String sku[];
String name[];
String price[];
String quantity[];

public my_adapter(Context ctx, String sku[], String name[], String price[],String quantity[]){
    this.ctx=ctx;
    this.sku=sku;
    this.name=name;
    this.price=price;
    this.quantity=quantity;
}

@Override
public int getCount() {
    return sku.length;
}

@Override
public Object getItem(int i) {
    return null;
}

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

@Override
public View getView(int i, View view, ViewGroup viewGroup) {
    View row=view;

    if(row==null){
        inflater=(LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row=inflater.inflate(R.layout.rows,null);
    }

    TextView product_sku=(TextView)row.findViewById(R.id.sku);
    TextView product_name=(TextView)row.findViewById(R.id.name);
    TextView product_price=(TextView)row.findViewById(R.id.price);
    TextView product_quantity=(TextView)row.findViewById(R.id.quantity);

    product_sku.setText(sku[i]);
    product_name.setText(name[i]);
    product_price.setText(price[i]);
    product_quantity.setText(quantity[i]);

    return row;
}
}

接下来,我需要做一些类似的事情,即将 JsonArray 转换为 Array,然后在 setOnItemClickListener 中使用它。 也就是说,我需要将 json 中的所有数据存储到 4 个数组中,然后使用稍后单击该项目时的任何元素。就像我的硬编码示例一样。

我看过一些使用 HashMap 的示例以及一些 JsonArray 到数组模板的编码,但不确定如何将它们与我的 ListView 和 baseAdapter 结合使用。

获取json数据

JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

    @Override
    public void onResponse(JSONObject response) {
        // working with HashMap or Arraylist?????
    }
}, new Response.ErrorListener() {

    @Override
    public void onErrorResponse(VolleyError error) {
        // TODO Auto-generated method stub
    }
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsObjRequest);

localhost/web_service/ohno.php

{
"482":["1","Chicken Rice","1","1"],  //Unique ID, sku,name,price,quantity
"483":["1","French Fries","1","1"],
"484":["1","apple","1","1"],
"492":["1","western+italian","1","1"],
"493":["1","no_cat","1","1"]
}

我在 Listview 中设置的格式与上面的 Json 格式(4 列)完全相同,除了 Json 格式有一个额外的元素,即唯一产品 ID。

最佳答案

试试这个

  public void getJson() { 
    AsyncHttpClient client = new AsyncHttpClient();
    client.get(localhost/web_service/ohno.php, new JsonHttpResponseHandler()   {

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            ArrayList<String> listData = new ArrayList<>();
            JSONArray jsonArray482=response.optJSONArray("482");
            if (jsonArray482 != null) {
                for (int i=0;i<jsonArray482.length();i++){
                    try {
                        listData.add(jsonArray482.get(i).toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    });
}

关于Android 使用 BaseAdapter 将 JsonArray 转换为 ListView 中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39433503/

相关文章:

flutter - 如何在不设置Flutter中的容器高度的情况下在容器内显示ListView?

java - 安卓政策 : External application files

java - 按下后退按钮时保存

java - 我的应用程序在 android studio 中崩溃了,在查看日志时我无法弄清楚出了什么问题

excel - EXCEL VBA : Listview object feature not found when exporting XLAM file to another machine

android - 我可以在另一个 Activity 中更新一个 Activity 中的 ListView 吗?

Android奇怪的绘图 Canvas 错误?

android - 资源 'attr/font' 的重复值与配置“

android - 如何处理 Android Activity 中的通知