Android 将JSON输出解析为ListView
我从android设备连接到服务器,查询数据库并在屏幕上显示结果。但是,我希望在ListView中显示结果。如何让代码显示在ListView中?目前,它只是解析数据并将其显示在屏幕上。如何为ContactName的每个值指定一个参考值?下面是我的代码:Android 将JSON输出解析为ListView,android,json,android-listview,Android,Json,Android Listview,我从android设备连接到服务器,查询数据库并在屏幕上显示结果。但是,我希望在ListView中显示结果。如何让代码显示在ListView中?目前,它只是解析数据并将其显示在屏幕上。如何为ContactName的每个值指定一个参考值?下面是我的代码: public class DbConnectActivity extends Activity { /** Called when the activity is first created. */ TextView txt; @O
public class DbConnectActivity extends Activity {
/** Called when the activity is first created. */
TextView txt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create a crude view - this should really be set via the layout resources
// but since its an example saves declaring them in the XML.
LinearLayout rootLayout = new LinearLayout(getApplicationContext());
txt = new TextView(getApplicationContext());
rootLayout.addView(txt);
setContentView(rootLayout);
// Set the text and call the connect function.
txt.setText("Connecting...");
//call the method to run the data retreival
txt.setText(getServerData(KEY_121));
}
public static final String KEY_121 = "http://10.0.2.2/dbconnect.php"; //i use my real ip here
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("EngID","1"));
//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);
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
//return result;
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","Name: "+json_data.getString("ContactName")
);
//Get an output to the screen
returnString += "\n\t" + jArray.getJSONObject(i);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return returnString;
}
}
公共类DbConnectActivity扩展活动{
/**在首次创建活动时调用*/
文本视图;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//创建一个粗略的视图-这应该通过布局资源进行设置
//但是,因为这是一个示例,所以不需要在XML中声明它们。
LinearLayout rootLayout=新的LinearLayout(getApplicationContext());
txt=新文本视图(getApplicationContext());
rootLayout.addView(txt);
setContentView(rootLayout);
//设置文本并调用connect函数。
txt.setText(“连接…”);
//调用该方法以运行数据检索
setText(getServerData(KEY_121));
}
公共静态最终字符串键_121=”http://10.0.2.2/dbconnect.php“;//我在这里使用我的真实ip
私有字符串getServerData(字符串返回字符串){
InputStream=null;
字符串结果=”;
//要发送的年度数据
//ArrayList nameValuePairs=新的ArrayList();
//添加(新的BasicNameValuePair(“EngID”,“1”));
//http post
试一试{
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(键号121);
//setEntity(新的UrlEncodedFormEntity(nameValuePairs));
HttpResponse response=httpclient.execute(httppost);
HttpEntity=response.getEntity();
is=entity.getContent();
}捕获(例外e){
e(“Log_标记”,“http连接错误”+e.toString());
}
//将响应转换为字符串
试一试{
BufferedReader reader=新的BufferedReader(新的InputStreamReader(is,“iso-8859-1”),8;
StringBuffer sb=新的StringBuffer();
字符串行=”;
而((line=reader.readLine())!=null){
sb.追加(第+行“\n”);
}
is.close();
结果=sb.toString();
//返回结果;
}捕获(例外e){
Log.e(“Log_标记”,“错误转换结果”+e.toString());
}
//解析json数据
试一试{
JSONArray jArray=新JSONArray(结果);
对于(int i=0;i我要做的最简单的事情是将JSONArray放在某个ArrayList中,并在arrayadapter中使用它,我要做的最简单的事情是将JSONArray放在某个ArrayList中,并在arrayadapter中使用它,您可以将所有json对象添加到一个列表中,然后从那里加载列表,但正如您已经准备好了一个返回sing的方法一样le字符串。您可以使用以下命令:
使用
您可以将所有json对象添加到一个列表中,然后从此处加载列表,但正如您已经准备好一个返回单个字符串的方法一样。您可以使用以下方法:
使用
公共类JsonExampleActivity扩展了ListActivity{
/**在首次创建活动时调用*/
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
setListAdapter(新的ArrayAdapter(this,android.R.layout.simple_list_item_1,this.fetchTwitterPublicTimeline());
}
公共ArrayList fetchTwitterPublicTimeline()
{
ArrayList listItems=新的ArrayList();
试一试{
URL twitter=新URL(“此处为您的URL”);
URLConnection tc=twitter.openConnection();
BufferedReader in=新的BufferedReader(新的InputStreamReader(
tc.getInputStream());
弦线;
而((line=in.readLine())!=null){
JSONObject ja=新的JSONObject(行);
/*
//对于(int i=0;i
公共类JsonExampleActivity扩展了ListActivity{
/**在首次创建活动时调用*/
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
setListAdapter(新的ArrayAdapter(this,android.R.layout.simple_list_item_1,this.fetchTwitterPublicTimeline());
}
公共ArrayList fetchTwitterPublicTimeline()
{
ArrayList listItems=新的ArrayList();
试一试{
URL twitter=新URL(“此处为您的URL”);
URLConnection tc=twitter.openConnection();
BufferedReader in=新的BufferedReader(新的InputStreamReader(
tc.getInputStream());
弦线;
而((line=in.readLine())!=null){
JSONObject ja=新的JSONObject(行);
/*
//对于(int i=0;iString[] tokens=returnString.split("\n\r");
ArrayAdapter adapter=new ArrayAdapter(this, android.R.layout.simple_list_item_1, tokens);
listView.setAdapter(adapter);
public class JsonExampleActivity extends ListActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, this.fetchTwitterPublicTimeline()));
}
public ArrayList<String> fetchTwitterPublicTimeline()
{
ArrayList<String> listItems = new ArrayList<String>();
try {
URL twitter = new URL("your url here");
URLConnection tc = twitter.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
JSONObject ja = new JSONObject(line);
/*
//for (int i = 0; i < ja.length(); i++) {
JSONObject jo = ja.getJSONObject("_api_error");
listItems.add(jo.getString("name"));*/
JSONArray jobj=ja.getJSONArray("artists");
//JSONArray ja = new JSONArray(line);
for (int i = 0; i < jobj.length(); i++) {
JSONObject jo = jobj.getJSONObject(i);
listItems.add(jo.getString("artist_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;
}
}