将JSON数据放入List中

时间:2015-04-10 22:34:35

标签: java android json android-asynctask

我的JSON数据来自我的服务器,我只想把它放到下面的数组中,但我不确定JSON数据是否正确插入到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

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

        }
    }
}

2 个答案:

答案 0 :(得分:5)

在这行代码中:

ShopAdapter ca = new ShopAdapter(createList(3));

您正在调用createList(int size)方法,该方法返回一个ArrayList,其中包含三个虚拟 ShopInfo 对象作为元素的对象。

AsyncTask 中您正在填充 shopList ArrayList,但您实际上从未实际使用shopList。

解析 JSON 的更简单方法是使用Google的 Gson 库来解析 JSON

我猜这是你的 ShopInfo 类:

public class ShopInfo {
    String name;
    String address;

    public void setName(String n){
        name = n;
    }

    public void setAddress(String a){
        address = a;
    }

    public String getName(){
        return name;
    }

    public String getAddress(){
        return address;
    }
}

创建一个如下所示的新类:

import java.util.List;
public class ShopInfoList{
     List<ShopInfo> shops;
}

在AsyncTask的doInBackground方法中,编写以下代码:

try 
{
    HttpURLConnection connection =  (HttpURLConnection)new URL(YOUR_URL_WITH_JSON).openConnection();
    try 
    {
        InputStream instream =connection.getInputStream();
        BufferedReader breader = new BufferedReader(new InputStreamReader(instream));
        ShopInfoList shopList = new Gson().fromJson(breader, ShopInfoList.class);

        breader.close();
    }
    catch (IOException e) 
    {
        Log.e("Exception parsing JSON", e);
    }
    finally 
    {
        connection.disconnect();
    }
}
catch (Exception e) 
{
    Log.e("Exception parsing JSON", e);
}

但您仍需要更新 ShopAdapter 以在列表(RecycleView)上显示它们,您可以在 AsyncTask 的onPostExecute()方法中执行此操作。

您可以查看此网址,详细了解如何使用 GSON github URL

以下是一些快速指南:

  1. 您的适配器,AsyncTask,Acitvity 类应分为不同的包,例如:util.asynctasks;和util.adapters; somename.activities; 。它更易于维护和调试;
  2. 保持代码约定。由于您使用Java编程,请使用以下指南: https://google-styleguide.googlecode.com/svn/trunk/javaguide.html
  3. 当你扩展像Activity或AsyncTask这样没有构建它的类时,很高兴将该类命名为 WhateverExtendingClassName ,例如:YourAcitivity。所以你确切地知道它的目的是什么。
  4. 嗯,你不想使用GSON我个人认为这很难过:(。

    以下代码希望对您有用,有些事情要记住:

    1. 我复制了你的代码,我更改了一些变量名称,并添加了一些代码。
    2. 我评论了我在哪里进行了更改或添加了代码。
    3. 我在onPostExecute() AsyncTask 方法中使用 notifyDataSetChanged() adapter方法,你应该尝试使用notifyItemInserted(int) notifyItemRemoved(int)方法根据您从API中收到的内容添加和删除项目。
    4. 以下是您的Activity和AsyncTask的代码:

      public class OrderCoffee extends Activity {
      
      JSONParser jParser = new JSONParser();
      ArrayList<ShopInfo> shopInfoList; //I changed this
      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);
          RecyclerView recList = (RecyclerView) findViewById(R.id.cardList);
          recList.setHasFixedSize(true);
          LinearLayoutManager llm = new LinearLayoutManager(this);
          llm.setOrientation(LinearLayoutManager.VERTICAL);
          recList.setLayoutManager(llm);
          shopInfoList = new ArrayList<ShopInfo>();//I changed this
          ShopAdapter shopAdapter = new ShopAdapter(ShopInfoList);//I changed this
          recList.setAdapter(shopAdapter);//I changed this
      
          LoadAllProducts loadAllProducts = new LoadAllProducts(shopAdapter)//I added this
          loadAllProducts.execute();//I changed this
      }
      
      
      class LoadAllProducts extends AsyncTask<String, String, String> {
      
          ShopAdapter shopAdapter;//I added this
          ArrayList<ShopInfo> shopInfoList = new ArrayList<ShopInfo>();//I added this
      
          public LoadAllProducts(ShopAdapter shopAdapter)//I added this
          {
              this.shopAdapter = shopAdapter;//I added this
          }
      
          @Override
          protected String doInBackground(String... args) //I changed this{
              // 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);
                          ShopInfo shopInfo = new ShopInfo();//I changed this
                          shopInfo.setId(id);//I changed this
                          shopInfo.setName(name);//I changed this
      
                          shopInfoList.add(shopInfo);//I changed this
                      }
                  } else {
      
                  }
              } catch (JSONException e) {
                  e.printStackTrace();
              }
      
              return null;
          }
      
          @Override
         protected void onPostExecute(String result)//I added this{
            shopAdapter.setShopList(shopInfoList); //I added this
            shopAdapter.notifyDataSetChanged();   //I added this
         }
      }
      

      适配器代码:

      public class ShopAdapter extends RecyclerView.Adapter<ShopAdapter.ShopViewHolder> {
      
          private ArrayList<ShopInfo> shopList;//I added this
      
          public ShopAdapter(ArrayList<ShopInfo> shopList)//I added this {
              this.shopList = shopList;//I added this
          }
      
          public void setShopList(ArrayList<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);
      
              }
          }
      }
      

答案 1 :(得分:1)

您应该将onCreate更改为此

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

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