我有以下方法连接到db并返回一个json数组。
private String getServerData(String returnString) {
InputStream is = null;
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year","1970"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(KEY_121);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
// JSONObject json_data = jArray.getJSONObject(i);
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getInt("id")+
", name: "+json_data.getString("name")+
", sex: "+json_data.getInt("sex")+
", birthyear: "+json_data.getInt("birthyear")
);
//Get an output to the screen
returnString += "\n\t" + jArray.getJSONObject(i);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
returnString += result.toString();
}
return returnString;
}
然后我想从外面调用这个方法但是对java很新。我不知道如何将它放入hm对象中,就像那个被注释掉的对象一样。请参阅以下代码
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView listView = (ListView)findViewById(R.id.list);
myBooks = new ArrayList<HashMap<String,Object>>();
HashMap<String, Object> hm;
hm = new HashMap<String, Object>();
List<String> list=new ArrayList<String>();
list.add(getServerData(KEY_121));
//With the help of HashMap add Key, Values of Book, like name,price and icon path
/* hm = new HashMap<String, Object>();
hm.put(BOOKKEY, "Android");
hm.put(PRICEKEY, "Price Rs: 500");
hm.put(IMGKEY, R.raw.android); //i have images in res/raw folder
myBooks.add(hm);
SimpleAdapter adapter = new SimpleAdapter(this, myBooks, R.layout.listbox,
new String[]{BOOKKEY,PRICEKEY,IMGKEY}, new int[]{R.id.text1, R.id.text2, R.id.img});
listView.setAdapter(adapter);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
我的目标是获取返回的字符串,并使用hm对象将其添加到myBooks对象,就像在评论代码中完成它一样。
由于
答案 0 :(得分:1)
由于getServerData()
需要一段时间才能执行(它包含一个http请求),因此无法直接从UI线程运行它。 (onCreate()
直接在UI线程上,并且永远不应暂停UI线程。
这意味着您必须创建 AsyncTask
并从getServerData()
的{{1}}致电doInBackground()
。您可以在AsyncTask
的{{1}}。
这意味着您希望将要显示结果的 SoftReference
传递给AsyncTask
。如果您在获取JSON时发生了某些事情,您希望将其设为onPostExecute()
(就像您离开活动一样)。
我建议您阅读 this Android blog article 并使用 the code from the article 创建自己的项目。启动并运行后,将该图像下载程序修改为JSON下载程序。该文章应该对您非常有帮助,因为它还使用适配器在列表视图中显示项目。
您的示例与文章中的示例有几点不同,但我认为它实际上更简单,所以如果您对本文中的代码感兴趣,那么您将能够在以后的代码中运行代码。
<强>参考文献:强>
的 AsyncTask 强>
的 SoftReferences 强>
的 Multithreading for Performance 强>
的 Working Code from the Article Above which implements something like you want but w images 强>
答案 1 :(得分:0)
这是我做的,它运作得很好
1-而不是返回字符串,我将结果返回给调用。
2之后我构建了一个字符串,然后我能够像这样解析它
returnedResult = this.getServerData(KEY_121);
try {
JSONArray jArray = new JSONArray(returnedResult);
for(int i=0;i<jArray.length();i++){
// JSONObject json_data = jArray.getJSONObject(i);
JSONObject json_data = jArray.getJSONObject(i);
hm = new HashMap<String, Object>();
hm.put(IDKEY, json_data.getInt("id"));
hm.put(NAMEKEY, json_data.getString("name"));
hm.put(IMGKEY, R.raw.android);
myBooks.add(hm);
}
希望这里有人帮忙 感谢