我的项目是从服务器获取json数据并在列表视图中显示,当运行代码时,我的代码无效:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, this.datadrinks()));
}
public ArrayList<String> datadrinks()
{
ArrayList<String> listItems = new ArrayList<String>();
try {
URL twitter = new URL("http://10.0.2.2:50667/expression%20web4/GetAllDrinkItems.ashx");
URLConnection tc = twitter.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
JSONObject ja = new JSONObject(line);
JSONArray jobj=ja.getJSONArray("lstDrinkItems");
for (int i = 0; i < jobj.length(); i++) {
JSONObject jo = jobj.getJSONObject(i);
listItems.add(jo.getString("Name"));
}
}
}catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listItems;
}
}
答案 0 :(得分:0)
我在代码中找不到明显的错误。
但是你在设计上遇到了很大的问题。您正在UI线程上发出服务器请求。你永远不应该这样做。在较新版本的Android上,您甚至不允许这样做。
您应该使用像AsyncTask这样的专门类:
doInBackground
:发出请求并解析回复onPostExecute
:填充listView 希望这有助于您未来的项目!