朋友们,我只想在列表视图中显示数据我使用异步任务,然后我完成了json中的数据并通过id和title过滤它现在我在listview中显示id和title你能否提前感谢
public class runActivity extends Activity implements OnClickListener {
String returnString="";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
}
@Override
public void onClick(View arg0) {
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(false);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
@Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://192.168.1.156/recess/document/document.json");
HttpClient client = new DefaultHttpClient();
HttpResponse response=null;
try{
response = client.execute(httpGet);}
catch(Exception e){}
System.out.println(response.getStatusLine());
String text = null;
try {
response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
String var =text;
try{
JSONObject jObj = new JSONObject(var);
JSONArray jArray = jObj.getJSONArray("document");
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getString("id")+
", title: "+json_data.getString("title")
);
returnString += "\n" +"id:"+ json_data.getString("id")+" "+"Title:"+ json_data.getString("title");
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return returnString;
}
protected void onPostExecute(String results) {
if (results!=null) {
ListView listView = (ListView) findViewById(R.id.mylist);
listView.setFilterText(results);
}
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(true);
}
}
}
答案 0 :(得分:1)
您需要构建一个与ListAdapter一起使用的数组。
以下是Google的指南:http://developer.android.com/resources/tutorials/views/hello-listview.html
答案 1 :(得分:0)
我认为最好的解决方案是在您的活动中创建一个Handler。然后,您可以向处理程序发送消息并获取数据并将其放入ListView。
答案 2 :(得分:0)
在doInBackground中“for”循环只需创建数据数组或将数据放入对象的Array列表中(然后需要编写自定义适配器)
有 1-选项 http://www.java-samples.com/showtutorial.php?tutorialid=1516 http://www.ezzylearning.com/tutorial.aspx?tid=1659127&q=binding-android-listview-with-string-array-using-arrayadapter
有关 2-选项