2015-10-30 60 views
0

我有一个项目,我们必须解析一个嵌套的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" 
      } 
     ] 
    } 
] 
} 
+0

感谢您help.I的还真不少被困在这个长期说明谢谢.. – devendra

回答

0

更改条件的json响应到<

我打赌你有IndexOutOfBoundException在你的日志。在循环所有第一个项目的子项之后,系统因为它而退出循环。

他们应该是:

for(int i=0; i<jarray.length(); i++) 
for(int j=0; j<subcatarray.length() ;j++) 
+0

在每个孩子设置increament decreament柜台时我已经在适配器类的另一个问题item.i我试图在getchildview方法上添加onclick监听器,但是这两个方法都是为了增加和减少,但是在几个项目之后我会得到重复值,当我按下增量或减少值。@ rami – devendra

+0

请接受答案,如果您的OP问题仍然存在。如果你有另一个你应该问一个新的问题,这是* Stackoverflow *的工作原理。我不明白你的意思是什么*“我在几件物品后得到重复价值”*? – Rami

+0

请告诉我如何设置子项item.and如何获取每个子项的计数器文本的位置@ Rami – devendra