Android使用BaseAdapter将JsonArray转换为Listview中的Array

时间:2016-09-11 06:38:57

标签: 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);

本地主机/使用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。

2 个答案:

答案 0 :(得分:1)

试试这个

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

    });
}

答案 1 :(得分:1)

理想的做法是实际创建一个Model类,或者说一下POJO类,其成员变量如sku,name,price,quantity,id。代码可能看起来像

public class Item {
    private int id;
    private String sku;
    private String name;
    private String price;
    private String quantity;
}

让json解析后,创建一个像

这样的Item列表
public void parseJson(String data) {
    ArrayList<Item> items = new ArrayList<Item>();

    //Parsing logic goes here
}

完成创建项目列表后,可以使用ArrayAdapter或BaseAdapter接受该项目,然后迭代列表并设置适当的值。对我来说,这似乎是正确的方法,而不是创建单独的数组,然后将其传递给BaseAdapter。

希望这可以帮助你。