我有一個項目,我們必須解析一個嵌套的JSON數組,並顯示它在一個可擴展的列表視圖與2級,現在我只得到第一項 組和他們的chield item.I新來的android開發請幫我做到這一點。我的代碼如下..可擴展的列表視圖與嵌套的JSON解析
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.Toast;
public class MainActivity extends Activity {
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
JSONObject obj,subObj;
JSONArray subcatarray,jarray;
private ProgressDialog pDialog;
String cat_id="2";
int j;
JsonParser jsonParser=new JsonParser();
private static final String LOGIN_URL = "http://sion.in/kandly/services/serviceList.php?service=subcategory";
private static final String TAG_SUCCESS = "status";
private static final String TAG_MESSAGE = "message";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the listview
expListView = (ExpandableListView) findViewById(R.id.lvExp);
// preparing list data
prepareListData();
// Listview Group expanded listener
expListView.setOnGroupExpandListener(new OnGroupExpandListener() {
@Override
public void onGroupExpand(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Expanded",
Toast.LENGTH_SHORT).show();
}
});
// Listview Group collasped listener
expListView.setOnGroupCollapseListener(new OnGroupCollapseListener() {
@Override
public void onGroupCollapse(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Collapsed",
Toast.LENGTH_SHORT).show();
}
});
// Listview on child click listener
expListView.setOnChildClickListener(new OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// TODO Auto-generated method stub
Toast.makeText(
getApplicationContext(),
listDataHeader.get(groupPosition)
+ " : "
+ listDataChild.get(
listDataHeader.get(groupPosition)).get(
childPosition), Toast.LENGTH_SHORT)
.show();
return false;
}
});
}
/*
* Preparing the list data
*/
private void prepareListData() {
new Subcatagory().execute();
}
private class Subcatagory extends AsyncTask<String, String, String> {
boolean failure = false;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please Wait..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
Boolean success;
try {
// Building Parameters
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("cat_id", cat_id));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
System.out.println("devjsondata"+json);
jarray=json.getJSONArray("data");
for(int i=0;i<=jarray.length();i++){
listDataHeader = new ArrayList<String>();
obj=jarray.getJSONObject(i);
listDataHeader.add(obj.getString("cat_name"));
subcatarray=obj.getJSONArray("product_details");
List<String> pSubItemArrayList = new ArrayList<String>();
for(j=0;j<=subcatarray.length();j++){
subObj=subcatarray.getJSONObject(j);
pSubItemArrayList.add(subObj.optString("product_name"));
listDataChild.put(listDataHeader.get(i), pSubItemArrayList);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
listAdapter = new ExpandableListAdapter(MainActivity.this, listDataHeader, listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
// Listview Group click listener
expListView.setOnGroupClickListener(new OnGroupClickListener() {
@Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
// Toast.makeText(getApplicationContext(),
// "Group Clicked " + listDataHeader.get(groupPosition),
// Toast.LENGTH_SHORT).show();
return false;
}
});
}
}
}
和我的適配器類是 -
public static class BasexpandableListAdapter extends BaseExpandableListAdapter{
Context context;
ArrayList<Product>ListTerbaru;
ArrayList<ArrayList<SubCategory>> ListChildTerbaru;
ArrayList<String>counterlist;
//private int[] itemcounter=new int[ListChildTerbaru.size()];
//final int count[] = {1};
//String subcount;
//SubCategory subcat;
Boolean showText=false;
public BasexpandableListAdapter (Context context, ArrayList<Product>ListTerbaru,ArrayList<ArrayList<SubCategory>> listChildXX){
this.context=context;
this.ListTerbaru=ListTerbaru;
this.ListChildTerbaru=listChildXX;
// this.count=ListTerbaru.size();
// this.count=ListChildTerbaru.size();
}
@Override
public boolean areAllItemsEnabled()
{
return true;
}
@Override
public SubCategory getChild(int groupPosition, int childPosition) {
return ListChildTerbaru.get(groupPosition).get(childPosition);
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild,View convertView, ViewGroup parent) {
final SubCategory childTerbaru = getChild(groupPosition, childPosition);
final ViewHolder holder;
View view = null;
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.row_second, parent,false);
//counter=0;
totalValueOfCounter+=totalValueOfCounter;
holder= new ViewHolder();
holder.begdate1=(TextView)convertView.findViewById(R.id.textViewTitle);
holder.countertext=(TextView)convertView.findViewById(R.id.countettext);
holder.increament=(Button)convertView.findViewById(R.id.increment);
holder.decrement=(Button)convertView.findViewById(R.id.decrement);
holder.increament.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
//int position = (Integer) v.getTag();
try{
counter = Integer.parseInt(holder.countertext.getText().toString().trim());
}catch(NumberFormatException e){
}
counter++;
SubCategory element = (SubCategory)holder.increament.getTag();
element.setScore(Integer.toString(counter));
holder.countertext.setText(childTerbaru.getScore().trim());
//totalValueOfCounter=childTerbaru.getScore();
totaleamount.setText(totalValueOfCounter);
try{
totaleamount.setText(Double.toString(Double.parseDouble(childTerbaru.getItemPrice())*Double.parseDouble(childTerbaru.getScore())));
totalValueOfCounter=Double.toString(Double.parseDouble(childTerbaru.getItemPrice())*Double.parseDouble(childTerbaru.getScore()));
}catch(NumberFormatException e){
}
notifyDataSetChanged();
}
});
holder.decrement.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
counter = Integer.parseInt(holder.countertext.getText().toString().trim());
}catch(NumberFormatException e){
}
if(counter>0){
counter--;
}
SubCategory element = (SubCategory) holder.decrement.getTag();
element.setScore(Integer.toString(counter));
holder.countertext.setText(childTerbaru.getScore().trim());
//totalValueOfCounter=Integer.toString(counter);
//totalValueOfCounter
totaleamount.setText(totalValueOfCounter);
try{
totaleamount.setText(Double.toString(Double.parseDouble(childTerbaru.getItemPrice())*Double.parseDouble(childTerbaru.getScore())));
totalValueOfCounter=Double.toString(Double.parseDouble(childTerbaru.getItemPrice())*Double.parseDouble(childTerbaru.getScore()));
}catch(NumberFormatException e){
}
notifyDataSetChanged();
}
});
holder.increament.setTag(childTerbaru);
holder.decrement.setTag(childTerbaru);
holder.countertext.setTag(childTerbaru);
holder.begdate1.setTag(childTerbaru);
convertView.setTag(holder);
//holder.begdate1.setText(childTerbaru.getpSubCatName());
//holder.countertext.setText(childTerbaru.getScore());
}
else{
view = convertView;
((ViewHolder) view.getTag()).countertext.setTag(childTerbaru);
((ViewHolder) view.getTag()).increament.setTag(childTerbaru);
((ViewHolder) view.getTag()).decrement.setTag(childTerbaru);
((ViewHolder) view.getTag()).begdate1.setTag(childTerbaru);
holder=(ViewHolder)view.getTag();
holder.begdate1.setText(childTerbaru.getpSubCatName());
holder.countertext.setText(childTerbaru.getScore());
return view;
}
holder.begdate1.setText(childTerbaru.getpSubCatName());
holder.countertext.setText(childTerbaru.getScore());
// holder.countertext.setText(Integer.toString(counter));
// holder.countertext.setText(ListChildTerbaru.get(groupPosition).get(childPosition).getScore());
return convertView;
}
@Override
public int getChildrenCount(int groupPosition) {
return ListChildTerbaru.get(groupPosition).size();
}
@Override
public Product getGroup(int groupPosition) {
return ListTerbaru.get(groupPosition);
}
@Override
public int getGroupCount() {
return ListTerbaru.size();
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
Product terbaruModel = (Product) getGroup(groupPosition);
ViewHolder holder= null;
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.row_first, parent,false);
holder=new ViewHolder();
holder.nama=(TextView)convertView.findViewById(R.id.textViewName);
// holder.alamat=(TextView)convertView.findViewById(R.id.address);
convertView.setTag(holder);
}
else{
holder=(ViewHolder)convertView.getTag();
}
holder.nama.setText(terbaruModel.getpName());
//holder.alamat.setText(terbaruModel.getAlamat());
return convertView;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public boolean isChildSelectable(int arg0, int arg1) {
return true;
}
class ViewHolder{
TextView begdate1,nama,countertext;
Button increament,decrement;
}
}
在你的兩個for循環從<=
是 -
{
"data": [
{
"status": "true",
"message": "found",
"cat_id": "24",
"cat_name": "MEN",
"product_details": [
{
"message": "found",
"product_id": "17",
"product_name": "irt",
"price": "77.000000"
},
{
"message": "found",
"product_id": "22",
"product_name": "sers",
"price": null
}
]
},
{
"status": "true",
"message": "fnd",
"cat_id": "5",
"cat_name": "WOMEN",
"product_details": [
{
"message": "fod",
"product_id": "17",
"product_name": "irt",
"price": "700"
},
{
"message": "foud",
"product_id": "7",
"product_name": "Shrt",
"price": "00"
}
]
}
]
}
感謝您help.I的還真不少被困在這個長期說明謝謝.. – devendra