[英]Putting JSON data into a List
我的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);
}
}
}
在這行代碼中:
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才能在List(RecycleView)上顯示它們,您可以在AsyncTask的onPostExecute()方法中進行操作 。
您可以檢查此URL,以獲取有關如何使用GSON github URL的更多詳細信息。
以下是一些快速指南:
好吧,您不想使用GSON,我個人認為這很可悲:(。
下面的代碼有望為您工作,請記住以下幾點:
下面是您的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);
}
}
}
您應該將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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.