【发布时间】: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