这是我的示例代码解析JSON数据并将其填充到列表视图,但它给我一个运行时错误?我怎样才能设置联系人名称和密钥到列表视图,我想隐藏的关键,并只查看联系人名称列表,但是当我点击列表视图我想获得与该名称相关的关键。Android的运行时异常,而从网站和填充JSON数据填充ListView
package com.example.myjsonsample;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.util.Log;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
private ProgressDialog pDialog;
private static String url = "http://192.168.1.2/webandroid/datamanip.php?cat=1";
private static final String TAG_KEY = "key";
private static final String TAG_NAME = "name";
private static final String TAG_LGTIME = "lgtime";
JSONArray contacts = null;
String[] contactList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new String[]{};
ListView lv = (ListView) findViewById(R.id.list);
new GetContacts(lv).execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
ListView lv ;
GetContacts(ListView vl){
lv =vl;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONArray arrJsonArray = new JSONArray(jsonStr);
for(int i=0;i<arrJsonArray.length();i++){
JSONObject object = arrJsonArray.getJSONObject(i);
Log.d("JSON PARSE",object.getString("key"));
Log.d("JSON PARSE",object.getString("name"));
Log.d("JSON PARSE",object.getString("lgtime"));
contactList[i] =object.getString("name")+"~"+object.getString("key");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
//this is the question : how to add my key into list view ? i want to start another activity with that key
ListAdapter adapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.list_item,contactList);
lv.setAdapter(adapter);
}
}
}
有没有这条线的需要 ListView lv;获取联系人(ListView v1){ lv = vl; –
那么如何通过listview对象来填充? – Elshan