
我是Android开发的新手.
考虑到JsON CarrIEr与XML相比的轻巧性,我纯粹喜欢使用JsON Objects和Arrays作为我的简单应用程序.
我对ArrayAdapter提出了挑战,要求填充ListVIEw.
这就是我如何克服并需要你的建议.
Extend the Adaptor class.然后将JsONArray传递给构造函数.
这里构造函数使用设置JsONArray长度的虚拟String数组调用super.
将构造函数参数存储在类中以供进一步使用.
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 }现在任何改进/建议/尽管问题?
解决方法:
我建议你使用谷歌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; }您下载数据的代码中的Somwhere.我不知道你是怎么做的所以我会发布我的代码例如:
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数组
总结以上是内存溢出为你收集整理的Android ArrayAdapter和JSONArray全部内容,希望文章能够帮你解决Android ArrayAdapter和JSONArray所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)