【问题标题】:Android ArrayAdapter and JSONArrayAndroid ArrayAdapter 和 JSONArray
【发布时间】:2013-12-09 09:14:31
【问题描述】:

我是 Android 开发新手。

我纯粹喜欢在我的简单应用程序中使用 JSON 对象和数组,考虑到 JSON 载体与 XML 相比更轻巧。

我在使用 ArrayAdapter 填充 ListView 时遇到了挑战。

这就是我克服的方法,需要你的建议。

Extend the Adaptor class.

然后将 JSONArray 传递给构造函数。
这里构造函数调用 super 并使用 dummy 字符串数组设置 JSONArray 的长度。
将构造函数参数存储在类中以供进一步使用。

public myAdaptor(Context context, int resource, JSONArray array)
{
    super(context, resource, new String[array.length()]);
    // Store in the local varialbles to the adapter class.
    this.context = context;
    this.resource = resource;
    this.profiles = objects;
}

getView() 将完成从 JSONArray 中获取 JSONObjects 以构建视图的工作。

public View getView(int position, View convertView, ViewGroup parent)
{
    View view;
    if (convertView == null)
    {
        LayoutInflater inflater = (LayoutInflater) 
            context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(resource, parent, false);
    }
    else
    {
        view = convertView;
    }

    // Here 
    JSONObject item = (JSONObject) profiles.getJSONObject(position);

    // READY WITH JSONObject from the JSONArray
    // YOUR CODE TO BUILD VIEW OR ACCESS THE 
}

现在有任何改进/建议/深思熟虑的问题吗??

【问题讨论】:

  • 这似乎没问题。您可以尝试的另一件事是将json数组转换为对象数组/数组列表,然后开始处理。
  • imo,而不是提供 JSONArray,您应该传递传递的结果,并避免在每次向上/向下滚动列表时解析信息
  • 不要在getView 中做很多工作,而是使用ArrayList、HashMap 等数据结构在myAdaptor 类中传递解析值。

标签: android listview arrays jsonobject


【解决方案1】:

我建议您使用 google GSON 而不是 JSON。它是一个库,可让您从 JSON 请求创建对象,您无需再解析 JSON。只需创建一个包含 JSON 请求中的所有字段并命名相同的对象,然后随心所欲地使用它 - 例如:

Your JSON request
{
    [
        {
            "id": "2663",
            "title":"qwe"

        },
        {
            "id": "1234",
            "title":"asd"
        },
        {
            "id": "5678",
            "title":"zxc"
        }

    ]
}

您的班级 - JSON-Array 项

 public class MyArrayAdapterItem{
     int id;
     String title;
 }

在您下载数据的代码中的某个位置。我不知道你是怎么做的,所以我会发布我的代码:

mGparser = new JsonParser();
Gson mGson = new Gson();

Url url = "http://your_api.com"
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Connection", "close");
conn.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

JsonArray request = (JsonArray) mGparser.parse(in.readLine());
in.close();
ArrayList<MyArrayAdapterItem> items = mGson.fromJson(request, new TypeToken<ArrayList<MyArrayAdapterItem>>() {}.getType());

就是这样,现在只需在适配器的构造函数中放入“items”而不是 JSON-array

【讨论】:

  • 感谢您的建议,这似乎很有趣。它的新知识。
  • 在未来的项目中,使用 gson 代替 json 您将获得“巨大的利润”,这将节省您大量的时间。因此,要从请求中获取数据,您需要在代码中添加几行代码,而不是烦人、无聊且不广泛的 JSON 解析。
【解决方案2】:

您可以将 null 传递给 super 而不是创建字符串数组并实现 getCount 方法:

public myAdaptor(Context context, int resource, JSONArray array)
{
    super(context, resource, null);
    // Store in the local varialbles to the adapter class.
    this.context = context;
    this.resource = resource;
    this.profiles = array;
}

public int getCount(){
   return profiles.length();
}

【讨论】:

  • 这是一个棘手的问题.. 很好.. 建议。无法将 null 传递给超级构造函数。而是只传递前 2 个参数。就可以了。
【解决方案3】:

创建一个文本视图并使用 item.getString("key") 分配并将该字符串添加到本地字符串数组并返回该视图

【讨论】:

    【解决方案4】:

    这是列表视图适配器类。

    public class Adapter extends BaseAdapter {
        Context context = null;
        ArrayList<OffersAvailable> offers = null;
    
    
        public Adapter(Context context, ArrayList<OffersAvailable> offer) {
            this.context = context;
            this.offers = offer;
    
        }
    
        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return offers.size();
        }
    
        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return offers.get(position).getTitle();
        }
    
        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return 0;
        }
    
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
    
            View v;
            final TextView tvpoints;
            final TextView tv,tv_quantity;
            if (convertView == null) {
                LayoutInflater li = ((Activity) context).getLayoutInflater();
                v = li.inflate(R.layout.design_userlist, null);
    
            } else {
                v = convertView;
            }
            tvpoints = (TextView) v.findViewById(R.id.tvpointlist);
            tv_quantity= (TextView) v.findViewById(R.id.tv_quantity);
            tv = (TextView) v.findViewById(R.id.tvdatalist);
            ((Activity) context).runOnUiThread(new Runnable() {
    
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    tv.setText(offers.get(position).getTitle().toUpperCase());
                    tv_quantity.setText(offers.get(position).getQuatity().toUpperCase());
                    tvpoints.setText(offers.get(position).getPoint() + "");
                }
            });
    
            return v;
        }
    
    }
    

    对象类

    public class OffersAvailable {
        String title, point, quatity, description,nid;
    
        public String getNid() {
            return nid;
        }
    
        public void setNid(String nid) {
            this.nid = nid;
        }
    
        public String getTitle() {
            return title;
        }
    
        public void setTitle(String title) {
            this.title = title;
        }
    
        public String getPoint() {
            return point;
        }
    
        public void setPoint(String point) {
            this.point = point;
        }
    
        public String getQuatity() {
            return quatity;
        }
    
        public void setQuatity(String quatity) {
            this.quatity = quatity;
        }
    
        public String getDescription() {
            return description;
        }
    
        public void setDescription(String description) {
            this.description = description;
        }
    
    }
    

    使用主类中的json并将其存储在OffersAvailable类型的Arraylist中。

    并将其传递给 listviews 适配器。 如果您从互联网上获得响应,请使用 asynchttpclient 方法。并解析 json。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-24
      • 2012-04-20
      • 2013-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多