从此链接填充 JSON 到 android Listview
Posted
技术标签:
【中文标题】从此链接填充 JSON 到 android Listview【英文标题】:Populating JSON from this link to android Listview 【发布时间】:2013-08-02 00:31:23 【问题描述】:我正在尝试从 JSON::
显示列表视图中的元素JsonURL-https://dl.dropboxusercontent.com/s/rhk01nqlyj5gixl/jsonparsing.txt?token_hash=AAHpfauVxJaC9Rkx_5abNtJnPFG04os7TZky1AhOuC5jEw
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_
android:layout_ >
<ListView
android:id="@+id/listViewID"
android:layout_
android:layout_
android:layout_gravity="center">
</ListView>
</LinearLayout>
JSONParser.java
package com.example.testjson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser
static InputStream is = null;
static JSONArray jObj = null;
static String json = "";
// constructor
public JSONParser()
public JSONArray getJSONFromUrl(String url)
// Making HTTP request
try
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
catch (UnsupportedEncodingException e)
e.printStackTrace();
catch (ClientProtocolException e)
e.printStackTrace();
catch (IOException e)
e.printStackTrace();
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();
json = sb.toString();
catch (Exception e)
Log.e("Buffer Error", "Error converting result " + e.toString());
// try parse the string to a JSON object
try
jObj = new JSONArray(json);
catch (JSONException e)
Log.e("JSON Parser", "Error parsing data " + e.toString());
// return JSON String
return jObj;
row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relativelay"
android:layout_
android:layout_
android:orientation="vertical" >
<TextView
android:id="@+id/tvname"
android:layout_
android:layout_
android:layout_alignParentTop="true"
android:layout_marginLeft="5dip"
android:maxLines="1"
android:text="Name"
android:textColor="@android:color/black"
android:textSize="14dp"
android:textStyle="bold" >
</TextView>
<TextView
android:id="@+id/tvcity"
android:layout_
android:layout_
android:layout_alignParentLeft="true"
android:layout_below="@+id/tvname"
android:layout_marginLeft="5dip"
android:layout_marginTop="3dip"
android:maxLines="1"
android:text="City"
android:textColor="@android:color/black"
android:textSize="14dp" >
</TextView>
<TextView
android:id="@+id/tvbdate"
android:layout_
android:layout_
android:layout_alignParentLeft="true"
android:layout_below="@+id/tvcity"
android:layout_marginLeft="5dip"
android:layout_marginTop="3dip"
android:maxLines="1"
android:text="Birthdate"
android:textColor="@android:color/black"
android:textSize="14dp" >
</TextView>
<TextView
android:id="@+id/tvgender"
android:layout_
android:layout_
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="15dip"
android:maxLines="1"
android:text="Gender"
android:textColor="@android:color/black"
android:textSize="14dp"
android:textStyle="bold" >
</TextView>
<TextView
android:id="@+id/tvage"
android:layout_
android:layout_
android:layout_alignParentRight="true"
android:layout_below="@+id/tvgender"
android:layout_marginRight="15dip"
android:layout_marginTop="3dip"
android:maxLines="1"
android:text="Age"
android:textColor="@android:color/black"
android:textSize="14dp" >
</TextView>
</RelativeLayout>
MainActivity.java
package com.example.testjson;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.text.StaticLayout;
import android.view.Menu;
public class MainActivity extends Activity
private static String url="https://www.dropbox.com/s/rhk01nqlyj5gixl/jsonparsing.txt?dl=1";
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Create a JSON parser Instance ----- Used JSON parser from Android
JSONParser jParser=new JSONParser();
//Getting JSON string from URL ------ Used JSON Array from Android
JSONArray json=jParser.getJSONFromUrl(url);
try
for(int i=0;i<json.length();i++)
JSONObject c=json.getJSONObject(i);// Used JSON Object from Android
//Storing each Json in a string variable
int AGE=c.getInt("age");
String NAME=c.getString("name");
String CITY=c.getString("city");
String GENDER=c.getString("Gender");
String BIRTHDATE=c.getString("birthdate");
catch (JSONException e)
// TODO Auto-generated catch block
e.printStackTrace();
我正在尝试将数据从 JSON 填充到 listView,一些
填写不明确MainActivity.java
该功能使用什么集合?
任何想法,这看起来很简单,但对于像我这样的初学者来说
努力学习
谢谢,
【问题讨论】:
好问题! ....即使我正在寻找这样的东西......以及对问题的良好解释!......将等待答案! 【参考方案1】:继续上课:
public class MainActivity extends Activity
private static String url="https://www.dropbox.com/s/rhk01nqlyj5gixl/jsonparsing.txt?dl=1";
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Create a JSON parser Instance ----- Used JSON parser from Android
JSONParser jParser=new JSONParser();
//Getting JSON string from URL ------ Used JSON Array from Android
JSONArray json=jParser.getJSONFromUrl(url);
List<WhateverObject> yourData = new ArrayList<WhateverObject>();
try
for(int i=0;i<json.length();i++)
JSONObject c=json.getJSONObject(i);// Used JSON Object from Android
//Storing each Json in a string variable
int AGE=c.getInt("age");
String NAME=c.getString("name");
String CITY=c.getString("city");
String GENDER=c.getString("Gender");
String BIRTHDATE=c.getString("birthdate");
yourData.add(new WhateverObject(NAME, CITY, GENDER, BIRTHDATE));
catch (JSONException e)
// TODO Auto-generated catch block
e.printStackTrace();
ListView yourListView = (ListView) findViewById(R.id.itemListView);
ListAdapter customAdapter = new ListAdapter(this, R.layout.itemlistrow, yourData);
yourListView.setAdapter(customAdapter);
适配器:
public class ListAdapter extends ArrayAdapter<Item>
public ListAdapter(Context context, int textViewResourceId)
super(context, textViewResourceId);
// TODO Auto-generated constructor stub
private List<Item> items;
public ListAdapter(Context context, int resource, List<Item> items)
super(context, resource, items);
this.items = items;
@Override
public View getView(int position, View convertView, ViewGroup parent)
View v = convertView;
TextView tt = null;
TextView tt1 = null;
TextView tt2 = null;
TextView tt3 = null;
TextView tt4 = null;
if (v == null)
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.itemlistrow, null);
tt = (TextView) v.findViewById(R.id.age);
tt1 = (TextView) v.findViewById(R.id.name);
tt2 = (TextView) v.findViewById(R.id.city);
tt3 = (TextView) v.findViewById(R.id.gender);
tt4 = (TextView) v.findViewById(R.id.birthdate);
Item p = items.get(position);
if (p != null)
if (tt != null)
tt.setText(""+p.getAge());
if (tt1 != null)
tt1.setText(""+p.getName());
if (tt2 != null)
tt2.setText(""+p.getCity());
if (tt3 != null)
tt3.setText(""+p.getGender());
if (tt4 != null)
tt4.setText(""+p.getBirthdate());
return v;
对象持有数据:
public class WhateverObject
private int age;
private String name;
private String city;
private String gender;
private String birthdate;
public WhateverObject(int age, String name, String city, String gender, String birthdate)
this.age = age;
this.name = name;
this.city = city;
this.gender = gender;
this.birthdate = birthdate;
public int getAge()
return this.age;
public String getName()
return this.name;
public String getCity()
return this.city;
public String getGender()
return this.gender;
public String getBirthdate()
return this.birthdate;
列表视图项的xml(保存在itemlistrow
名称下):
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_ android:orientation="vertical"
android:layout_>
<TableRow android:layout_
android:id="@+id/TableRow01"
android:layout_>
<TextView
android:id="@+id/age"
android:layout_
android:layout_
android:text="age" android:textStyle="bold"
android:gravity="left"
android:layout_weight="1"
android:typeface="monospace"
android:/>
</TableRow>
<TableRow android:layout_
android:layout_>
<TextView
android:id="@+id/name"
android:layout_
android:layout_
android:text="name"
android:layout_weight="1"
android:/>
</TableRow>
<TableRow android:layout_
android:layout_>
<TextView
android:id="@+id/city"
android:layout_
android:layout_
android:text="city"
android:layout_weight="1"
android:/>
</TableRow>
<TableRow android:layout_
android:layout_>
<TextView
android:id="@+id/gender"
android:layout_
android:layout_
android:text="city"
android:layout_weight="1"
android:/>
</TableRow>
<TableRow android:layout_
android:layout_>
<TextView
android:id="@+id/birthdate"
android:layout_
android:layout_
android:text="city"
android:layout_weight="1"
android:/>
</TableRow>
</TableLayout>
重用来自https://***.com/a/8166802/1276374的元素
更简单的例子:
public class MainActivity extends Activity
private static String url="https://www.dropbox.com/s/rhk01nqlyj5gixl/jsonparsing.txt?dl=1";
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Create a JSON parser Instance ----- Used JSON parser from Android
JSONParser jParser=new JSONParser();
//Getting JSON string from URL ------ Used JSON Array from Android
JSONArray json=jParser.getJSONFromUrl(url);
List<Map<String, String>> personList = new ArrayList<Map<String,String>>();
try
for(int i=0;i<json.length();i++)
JSONObject c=json.getJSONObject(i);// Used JSON Object from Android
//Storing each Json in a string variable
int AGE=c.getInt("age");
String NAME=c.getString("name");
String CITY=c.getString("city");
String GENDER=c.getString("Gender");
String BIRTHDATE=c.getString("birthdate");
personList.add(createPerson(AGE, NAME, CITY, GENDER, BIRTHDATE));
catch (JSONException e)
// TODO Auto-generated catch block
e.printStackTrace();
ListView yourListView = (ListView) findViewById(R.id.itemListView);
simpleAdpt = new SimpleAdapter(this, personList, android.R.layout.simple_list_item_1, new String[] "person", new int[] android.R.id.text1);
yourListView.setAdapter(simpleAdpt);
private HashMap<String, String> createPerson(int age, String name, String city, String gender, String birthdate)
HashMap<String, String> person = new HashMap<String, String>();
person.put("person", name+" | "+age + " | "+city + " | "+gender + " | "+birthdate);
return person;
感谢http://www.javacodegeeks.com/2013/06/android-listview-tutorial-and-basic-example.html
【讨论】:
Mocialov Boris .....我用你的第一个解决方案尝试了你的解决方案......我在我的 LogCat 中收到如下错误...... ......................... 08-01 14:38:15.625:E/Buffer 错误(710):错误转换结果 java.lang .NullPointerException 08-01 14:38:15.634: E/JSON Parser(710): 解析数据时出错 org.json.JSONException: 在 08-01 14:38:15.644 的字符 0 处输入结束:D/AndroidRuntime(710) : 关闭 VM ......................还有一些错误! @Sky 似乎是 JSON 解析器的一个例外 ListAdapter customAdapter = new ListAdapter(this, R.layout.itemlistrow, yourData); .....我解决了JSON解析器的异常但是............在这一行有问题......错误::constructor适配器未定义 @Sky 将我的回答Item
中的一些内容更改为 WhateverObject
,同样操作
@Sky 在ListAdapter
中将ArrayList
更改为List
- 已编辑答案【参考方案2】:
创建一个类,比如 Student,以包含一条记录,从 JSON 创建一个 Student 数组,然后将其与 ArrayAdapter 一起使用来填充您的 ListView。
【讨论】:
【参考方案3】:使用ArrayList会更适合你。见下面sn-p,
在顶部声明以下内容,
public static ArrayList<String> FriendName = new ArrayList<String>();
在获取Name
之后,try 块中的以下内容
FriendName .add(Name);
您可以通过如下索引值轻松地从数组列表中获取值,
String data=FriendName.get(0);
【讨论】:
【参考方案4】:为了简单起见,我会使用 GSON 库。在这种情况下,您将拥有以下内容:
一个用于数据映射的 POJO 学生类
public class Student
private int id;
private String name;
private String city;
private String Gender;
private int age;
private String birthdate;
//getters and setters
只需解析数据即可
Student[] students;
Type token = new TypeToken<Student[]>() .getType();
Gson gson = new Gson();
students = gson.fromJson(jsonString, token);
从这里您只需将数据添加到适配器,就是这样。
【讨论】:
以上是关于从此链接填充 JSON 到 android Listview的主要内容,如果未能解决你的问题,请参考以下文章