将 JSON 数据放入列表

Putting JSON data into a List(将 JSON 数据放入列表)
本文介绍了将 JSON 数据放入列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 JSON 数据正确地来自我的服务器,我只想将它放入以下数组,但我不确定 JSON 数据是否正确插入到 ArrayList 中.

I have my JSON data coming correctly from my server, I just want to put it into the following array but I'm not sure the JSON data is correctly being inserted into the ArrayList.

这是数组

private List<ShopInfo> createList(int size)  {
    List<ShopInfo> result = new ArrayList<ShopInfo>();
    for (int i = 1; i <= size; i++) {
        ShopInfo ci = new ShopInfo();
        ci.name =    TAG_NAME+i;
        ci.address = TAG_ADDRESS+i;
        result.add(ci);
    }
    return result;
}

我的 json

{"success":1,"shops":[{"name":"Test_Shop","address":"1 Big Road Dublin"}

文件

public class OrderCoffee extends Activity {

JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> shopList;
private static String url_all_products = "xxxxxxxxxx/ordercoffee.php";
// products JSONArray
JSONArray shops = null;


// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_SHOPS = "shops";
private static final String TAG_NAME = "name";
private static final String TAG_ADDRESS = "address";


//get a list of participating coffee shops in the locality that are using the app
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.order_coffee);
    new LoadAllProducts().execute();
    RecyclerView recList = (RecyclerView) findViewById(R.id.cardList);
    recList.setHasFixedSize(true);
    LinearLayoutManager llm = new LinearLayoutManager(this);
    llm.setOrientation(LinearLayoutManager.VERTICAL);
    recList.setLayoutManager(llm);
    shopList = new ArrayList<HashMap<String, String>>();
    ShopAdapter ca = new ShopAdapter(createList(3));
    recList.setAdapter(ca);

}


class LoadAllProducts extends AsyncTask<String, String, String> {


    @Override
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("All Products: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // products found
                // Getting Array
                shops = json.getJSONArray(TAG_SHOPS);

                // looping through All Products
                for (int i = 0; i < shops.length(); i++) {
                    JSONObject c = shops.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_ADDRESS);
                    String name = c.getString(TAG_NAME);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_ADDRESS, id);
                    map.put(TAG_NAME, name);

                    shopList.add(map);


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

        return null;
    }


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}


private List<ShopInfo> createList(int size)  {
    List<ShopInfo> result = new ArrayList<ShopInfo>();
    for (int i = 1; i <= size; i++) {
        ShopInfo ci = new ShopInfo();
        ci.name =    TAG_NAME+i;
        ci.address = TAG_ADDRESS+i;
        result.add(ci);
    }
    return result;
}
}

ShopAdapter

ShopAdapter

  package com.example.strobe.coffeetime;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;

/**
 * Created by root on 10/04/15.
 */
public class ShopAdapter extends RecyclerView.Adapter<ShopAdapter.ShopViewHolder> {

    private List<ShopInfo> shopList;

    public ShopAdapter(List<ShopInfo> shopList) {
        this.shopList = shopList;
    }


    @Override
    public int getItemCount() {
        return shopList.size();
    }

    @Override
    public void onBindViewHolder(ShopViewHolder shopViewHolder, int i) {
        ShopInfo ci = shopList.get(i);
        shopViewHolder.vName.setText(ci.name);
        shopViewHolder.vAddress.setText(ci.address);

    }

    @Override
    public ShopViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View itemView = LayoutInflater.
                from(viewGroup.getContext()).
                inflate(R.layout.card_layout, viewGroup, false);

        return new ShopViewHolder(itemView);
    }

    public static class ShopViewHolder extends RecyclerView.ViewHolder {

        protected TextView vName;
        protected TextView vAddress;


        public ShopViewHolder(View v) {
            super(v);
            vName =  (TextView) v.findViewById(R.id.name);
            vAddress = (TextView)  v.findViewById(R.id.address);

        }
    }
}

推荐答案

你应该把你的 onCreate 改成这个

You should change your onCreate to this

private RecyclerView recList;
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.order_coffee);
    recList = (RecyclerView) findViewById(R.id.cardList);
    recList.setHasFixedSize(true);
    recList.setLayoutManager(new LinearLayoutManager(this));
    shopList = new ArrayList<HashMap<String, String>>();
    new LoadAllProducts().execute();
}

然后在 onPostExecute

And then in onPostExecute

protected void onPostExecute(String result) {
    List<ShopInfo> list = new ArrayList<ShopInfo>();
    for (int i = 0; i < shopList.size(); i++) {
        ShopInfo ci = new ShopInfo();
        HashMap<String, String> map = shopList.get(i)
        ci.name =    map.get(TAG_NAME);
        ci.address = map.get(TAG_ADDRESS);
        list.add(ci);
    }

    ShopAdapter ca = new ShopAdapter(list);
    recList.setAdapter(ca);
}

如果您不将 shopList 用于其他任何用途,您可以将其删除并将用于创建您传递给适配器的列表的代码移动到 doInBackground

If you are not using shopList for anything else you can remove it and move the code for creating the list you pass to the adapter to doInBackground

这篇关于将 JSON 数据放入列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How to get large JSON Using REST template Spring MVC without memory issues in java(如何在Java中无内存问题地使用REST模板Spring MVC获取大型JSON)
Using RestTemplate to map JSON to object(使用RestTemplate将JSON映射到对象)
How to map dynamic JSON in JAX-RS(如何在JAX-RS中映射动态JSON)
Convert tuples to json using rdf4j(使用rdf4j将元组转换为json)
How can I store nested JSON data in Room Database? [Room](如何将嵌套的JSON数据存储在Room Database中?[房间])
Is there any way to flatten the nested JSON in spark streaming?(有什么办法可以扁平化电光流媒体中的嵌套JSON吗?)