gpt4 book ai didi

java - 将 JSON 数据放入列表

转载 作者:太空狗 更新时间:2023-10-29 16:15:26 27 4
gpt4 key购买 nike

我的 JSON 数据正确地来 self 的服务器,我只想将它放入以下数组中,但我不确定 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;
}
}

商店适配器

  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

这里有一些快速指南:

  1. 您的Adapter、AsyncTask、Acitvity 类应该分成不同的包,例如:util.asynctasks;和 util.adapters;某个名字.activities; .更易于维护和调试;
  2. 保持代码约定。由于您使用 Java 进行编程,因此请使用此指南: https://google-styleguide.googlecode.com/svn/trunk/javaguide.html
  3. 当您扩展一个不是您构建的类(如 Activity 或 AsyncTask)时,最好将该类命名为 WhateverExtendingClassName,例如:YourAcitivity。所以您确切地知道它的目的是什么。

好吧,你不想使用 GSON 我个人认为这很可悲 :(。

希望下面的代码对您有用,但要记住一些事项:

  1. 我复制了您的代码,更改了一些变量名称并添加了一些代码。
  2. 我已对我所做的更改或添加的代码进行了评论。
  3. 我在 onPostExecute() AsyncTask 方法中使用了 notifyDataSetChanged() 适配器方法,您应该尝试使用 notifyItemInserted(int)notifyItemRemoved(int) 方法根据您从 API 收到的内容添加和删除项目。

以下是您的 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);

}
}
}

关于java - 将 JSON 数据放入列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29571680/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com