Android 将数据从JSON检索到列表视图中
我希望许多开发人员已经使用了此功能,其中一些人也进行了更改,因此我们开始: 我正在尝试使用JSON创建多层列表视图,并使用本教程进行客户端编码: 我可以使用此JSON获取相册列表:Android 将数据从JSON检索到列表视图中,android,json,listview,Android,Json,Listview,我希望许多开发人员已经使用了此功能,其中一些人也进行了更改,因此我们开始: 我正在尝试使用JSON创建多层列表视图,并使用本教程进行客户端编码: 我可以使用此JSON获取相册列表: [ { "id":1, "name":"127 Hours", "songs_count":14 }, { "id":2, "name":"Adele 21", "songs_count":11 } ] 但是,没有得到该专辑下的歌曲列表 为了获得歌曲列表,我尝试了两种JSON 首先: { "id":1, "alb
[
{
"id":1,
"name":"127 Hours",
"songs_count":14
},
{
"id":2,
"name":"Adele 21",
"songs_count":11
}
]
但是,没有得到该专辑下的歌曲列表
为了获得歌曲列表,我尝试了两种JSON
首先:
{
"id":1,
"album":"127 Hours",
"songs":
[
{
"id":1,
"name":"Never Hear Surf Music Again",
"duration":"5:52"
},
{
"id":2,
"name":"The Canyon",
"duration":"3:01"
}
],
"id":2,
"album":"Adele 21",
"songs":
[
{
"id":1,
"name":"Rolling In The Deep",
"duration":"03:48"
}
]
}
第二点:
[
{
"id":1,
"album":"127 Hours",
"songs":[
{
"id":1,
"name":"Never Hear Surf Music Again",
"duration":"5:52"
}
]
}, {
"id":2,
"album":"Adele 21",
"songs":[
{
"id":1,
"name":"Rolling In The Deep",
"duration":"03:48"
}
]
}
]
注意:我想使用相同的代码制作相同类型的多级ListView,但只使用JSON,而不使用PHP类,或者是否可以只使用单一JSON来显示相册和歌曲列表,如果可能,请为我编写JSON。尝试以下方法:
JSON解析器类:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if (method == "POST") {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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 JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
公共类JSONParser{
静态InputStream为空;
静态JSONObject jObj=null;
静态字符串json=“”;
//建造师
公共JSONParser(){
}
//函数从url获取json
//通过使用HTTP POST或GET方法
公共JSONObject makeHttpRequest(字符串url、字符串方法、,
列表参数){
//发出HTTP请求
试一试{
//检查请求方法
如果(方法==“POST”){
//请求方法为POST
//defaultHttpClient
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(url);
setEntity(新的UrlEncodedFormEntity(参数));
HttpResponse HttpResponse=httpClient.execute(httpPost);
HttpEntity HttpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}else if(方法==“GET”){
//请求方法是GET
DefaultHttpClient httpClient=新的DefaultHttpClient();
String paramString=URLEncodedUtils.format(params,“utf-8”);
url+=“?”+参数字符串;
HttpGet HttpGet=新的HttpGet(url);
HttpResponse HttpResponse=httpClient.execute(httpGet);
HttpEntity HttpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}
}捕获(不支持的编码异常e){
e、 printStackTrace();
}捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
试一试{
BufferedReader reader=新的BufferedReader(新的InputStreamReader(
is,“iso-8859-1”),8);
StringBuilder sb=新的StringBuilder();
字符串行=null;
而((line=reader.readLine())!=null){
sb.追加(第+行“\n”);
}
is.close();
json=sb.toString();
}捕获(例外e){
Log.e(“缓冲区错误”,“错误转换结果”+e.toString());
}
//尝试将字符串解析为JSON对象
试一试{
jObj=新的JSONObject(json);
}捕获(JSONException e){
Log.e(“JSON解析器”,“错误解析数据”+e.toString());
}
//返回JSON字符串
返回jObj;
}
}
显示Listview的片段类:
public static class EventFragment extends ListFragment {
ArrayList<HashMap<String, String>> eventsList;
private String url_all_events = //url goes here;
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
// JSON Node names
private static final String CONNECTION_STATUS = "success";
private static final String TABLE_EVENT = "Event";
private static final String pid = "pid";
private static final String COL_GROUP = "Group";
private static final String COL_NAME = "Event_Name";
private static final String COL_DESC = "Event_Desc";
private static final String COL_DATE = "Event_Date";
private static final String COL_TIME = "Event_Time";
JSONArray Events = null;
public static final String ARG_SECTION_NUMBER = "section_number";
public EventFragment() {
}
public void onStart() {
super.onStart();
eventsList = new ArrayList<HashMap<String, String>>();
new LoadAllEvents().execute();
// selecting single ListView item
ListView lv = getListView();
// Lauching the Event details screen on selecting a single event
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String ID = ((TextView) view.findViewById(R.id.pid))
.getText().toString();
Intent intent = new Intent(view.getContext(),
EventDetails.class);
intent.putExtra(pid, ID);
view.getContext().startActivity(intent);
}
});
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_events,
container, false);
return rootView;
}
class LoadAllEvents extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Just a moment...");
pDialog.setIndeterminate(true);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_events,
"GET", params);
try {
// Checking for SUCCESS TAG
int success = json.getInt(CONNECTION_STATUS);
if (success == 1) {
// products found
// Getting Array of Products
Events = json.getJSONArray(TABLE_EVENT);
// looping through All Contacts
for (int i = 0; i < Events.length(); i++) {
JSONObject evt = Events.getJSONObject(i);
// Storing each json item in variable
id = evt.getString(pid);
group = evt.getString(COL_GROUP);
name = evt.getString(COL_NAME);
desc = evt.getString(COL_DESC);
date = evt.getString(COL_DATE);
time = evt.getString(COL_TIME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(pid, id);
map.put(COL_GROUP, group);
map.put(COL_NAME, name);
map.put(COL_DESC, desc);
map.put(COL_DATE, date);
map.put(COL_TIME, time);
// adding HashList to ArrayList
eventsList.add(map);
}
} else {
// Options are not available or server is down.
// Dismiss the loading dialog and display an alert
// onPostExecute
pDialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(getActivity(),
eventsList, R.layout.list_item, new String[] {
pid, COL_GROUP, COL_NAME, COL_DATE, COL_TIME },
new int[] { R.id.pid, R.id.group, R.id.name, R.id.header,
R.id.title2 });
setListAdapter(adapter);
}
});
}
}
}
公共静态类EventFragment扩展了ListFragment{
ArrayList事件列表;
私有字符串url\u all\u events=//url位于此处;
私人对话;
JSONParser jParser=新的JSONParser();
//JSON节点名称
私有静态最终字符串连接\u STATUS=“success”;
私有静态最终字符串表\u EVENT=“EVENT”;
私有静态最终字符串pid=“pid”;
私有静态最终字符串COL_GROUP=“GROUP”;
私有静态最终字符串COL_NAME=“Event_NAME”;
私有静态最终字符串COL_DESC=“Event_DESC”;
私有静态最终字符串COL_DATE=“Event_DATE”;
私有静态最终字符串COL_TIME=“Event_TIME”;
JSONArray事件=null;
公共静态最终字符串ARG\u SECTION\u NUMBER=“SECTION\u NUMBER”;
公共事件片段(){
}
public void onStart(){
super.onStart();
eventsList=新的ArrayList();
新建LoadAllEvents().execute();
//选择单个ListView项
ListView lv=getListView();
//在选择单个事件时启动事件详细信息屏幕
lv.setOnItemClickListener(新的OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父级、视图、,
内部位置,长id){
//从选定的ListItem获取值
字符串ID=((TextView)view.findViewById(R.ID.pid))
.getText().toString();
Intent Intent=新的Intent(view.getContext(),
EventDetails.class);
intent.putExtra(pid,ID);
view.getContext().startActivity(intent);
}
});
}
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
视图根视图=充气机。充气(R.layout.fragment_事件,
货柜(虚假);;
返回rootView;
}
类LoadAllEvents扩展异步任务{
/**
*在启动后台线程显示进度对话框之前
* */
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
pDialog=newprogressdialog(getActivity());
setMessage(“稍等…”);
pDialog.setUndeterminate(真);
pDialog.setCancelable(真);
public class EventDetails extends Activity {
String pid;
TextView EvtName, EvtDesc, EvtDate, EvtTime, Header;
ImageView logo;
private String url_event_details = "http://centrubook.eu.pn/eventDetails.php";
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
// JSON Node names
private static final String CONNECTION_STATUS = "success";
private static final String TABLE_EVENT = "Event";
private static final String COL_PID = "pid";
private static final String COL_NAME = "Event_Name";
private static final String COL_DESC = "Event_Desc";
private static final String COL_DATE = "Event_Date";
private static final String COL_TIME = "Event_Time";
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.eventdetails);
// ActionBar actionBar = getActionBar();
// actionBar.setDisplayHomeAsUpEnabled(true);
EvtName = (TextView) findViewById(R.id.BombaName);
EvtDesc = (TextView) findViewById(R.id.BombaDesc);
EvtDate = (TextView) findViewById(R.id.BombaDate);
EvtTime = (TextView) findViewById(R.id.BombaTime);
logo = (ImageView) findViewById(R.id.BombaLogo);
Intent i = getIntent();
pid = i.getStringExtra(COL_PID);
new getEventDetails().execute();
}
class getEventDetails extends AsyncTask<String, String, String> {
String name, desc, date, time;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EventDetails.this);
pDialog.setMessage("Just a moment...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... args) {
// Check for success tag
int success;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", pid));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jParser.makeHttpRequest(url_event_details,
"GET", params);
// json success tag
success = json.getInt(CONNECTION_STATUS);
if (success == 1) {
// successfully received product details
JSONArray eventsObj = json.getJSONArray(TABLE_EVENT);
// get first product object from JSON Array
JSONObject details = eventsObj.getJSONObject(0);
name = details.getString(COL_NAME);
desc = details.getString(COL_DESC);
date = details.getString(COL_DATE);
time = details.getString(COL_TIME);
} else {
// product with pid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(final String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
EvtName.setText(name);
EvtDesc.setText(desc);
EvtDate.setText(date);
EvtTime.setText(time);
logo.setImageResource(R.drawable.events);
}
});
}
}
}