2013-11-16 2 views
0

Привет, Я пытаюсь получить данные из своей базы данных и показать их на ExpandableListView. Приложение продолжает сбой, когда я начал использовать JSON, но до этого он работал нормально.Расширяемый просмотр списка с JSON

мой адаптер класса

public class ExpandableListAdapterA extends BaseExpandableListAdapter 
{ 

private Activity context; 
private Map<String, List<String>> laptopCollections; 
private List<String> laptops; 

public ExpandableListAdapterA(Activity context, List<String> laptops, 
     Map<String, List<String>> laptopCollections) { 
    this.context = context; 
    this.laptopCollections = laptopCollections; 
    this.laptops = laptops; 
} 

public Object getChild(int groupPosition, int childPosition) { 
    return laptopCollections.get(laptops.get(groupPosition)).get(childPosition); 
} 

public long getChildId(int groupPosition, int childPosition) { 
    return childPosition; 
} 

public View getChildView(final int groupPosition, final int childPosition, 
     boolean isLastChild, View convertView, ViewGroup parent) { 
    final String laptop = (String) getChild(groupPosition, childPosition); 
    LayoutInflater inflater = context.getLayoutInflater(); 

    if (convertView == null) { 
     convertView = inflater.inflate(R.layout.child_view, null); 
    } 

    TextView item = (TextView) convertView.findViewById(R.id.laptop); 

    ImageView delete = (ImageView) convertView.findViewById(R.id.delete); 
    delete.setOnClickListener(new OnClickListener() { 

     public void onClick(View v) { 
      AlertDialog.Builder builder = new AlertDialog.Builder(context); 
      builder.setMessage("Do you want to remove?"); 
      builder.setCancelable(false); 
      builder.setPositiveButton("Yes", 
        new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int id) { 
          List<String> child = 
           laptopCollections.get(laptops.get(groupPosition)); 
          child.remove(childPosition); 
          notifyDataSetChanged(); 
         } 
        }); 
      builder.setNegativeButton("No", 
        new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int id) { 
          dialog.cancel(); 
         } 
        }); 
      AlertDialog alertDialog = builder.create(); 
      alertDialog.show(); 
     } 
    }); 

    item.setText(laptop); 
    return convertView; 
} 

public int getChildrenCount(int groupPosition) { 
    return laptopCollections.get(laptops.get(groupPosition)).size(); 
} 

public Object getGroup(int groupPosition) { 
    return laptops.get(groupPosition); 
} 

public int getGroupCount() { 
    return laptops.size(); 
} 

public long getGroupId(int groupPosition) { 
    return groupPosition; 
} 

public View getGroupView(int groupPosition, boolean isExpanded, 
     View convertView, ViewGroup parent) { 
    String laptopName = (String) getGroup(groupPosition); 
    if (convertView == null) { 
     LayoutInflater infalInflater = (LayoutInflater) context 
       .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     convertView = infalInflater.inflate(R.layout.parent_view, 
       null); 
    } 
    TextView item = (TextView) convertView.findViewById(R.id.head); 
    item.setTypeface(null, Typeface.BOLD); 
    item.setText(laptopName); 
    return convertView; 
} 

public boolean hasStableIds() { 
    return true; 
} 

public boolean isChildSelectable(int groupPosition, int childPosition) { 
    return true; 
} 
} 

мой другой класс

public class Product extends Activity { 

List<String> groupList; 
List<String> childList; 
Map<String, List<String>> laptopCollection; 
ExpandableListView expListView; 
private static String url = "http://10.0.2.2/Monoprix/DB_Connect.php"; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.products); 

    new createGroupList().execute(); 



    expListView = (ExpandableListView) findViewById(R.id.products); 
    final ExpandableListAdapter expListAdapter = new ExpandableListAdapterA(this, groupList, laptopCollection); 
    expListView.setAdapter(expListAdapter); 

    //setGroupIndicatorToRight(); 

    expListView.setOnChildClickListener(new OnChildClickListener() { 

     public boolean onChildClick(ExpandableListView parent, View v, 
       int groupPosition, int childPosition, long id) { 
      final String selected = (String) expListAdapter.getChild(
        groupPosition, childPosition); 
      Toast.makeText(getBaseContext(), selected, Toast.LENGTH_LONG) 
        .show(); 

      return true; 
     } 
    }); 
} 



class createGroupList extends AsyncTask<String,String,String> { 
    protected String doInBackground(String... args) { 
    groupList = new ArrayList<String>(); 
    String[] hpModels = { "HP Pavilion G6-2014TX", "ProBook HP 4540", 
    "HP Envy 4-1025TX" }; 

    //String[] lenovoModels = { "IdeaPad Z Series", "Essential G Series","ThinkPad X Series", "Ideapad Z Series" }; 
    String[] dellModels = { "Inspiron", "Vostro", "XPS" }; 
    try{ 
     JSONParser jsonParser = new JSONParser(); 
     JSONObject json = jsonParser.getJSONFromUrl(url); 
     Log.d("Create Response", json.toString()); 
     JSONArray title = json.getJSONArray("product"); 
     for (int i=0;i<title.length();i++) 
     { 
      JSONObject c = title.getJSONObject(i); 
      String categ = c.getString("product_category"); 
      groupList.add(categ); 
     } 
     childList = new ArrayList<String>(); 
     laptopCollection = new LinkedHashMap<String, List<String>>(); 
     for (String laptop : groupList) { 
      if (laptop.equals("HP")) { 
       for (String model : hpModels) 
        childList.add(model); 
      } else if (laptop.equals("Dell")) 
       for (String model : dellModels) 
        childList.add(model); 

      laptopCollection.put(laptop, childList); 
     } 

}catch (JSONException e) 
{ 
    e.printStackTrace(); 
} 
    return null; 
    } 
} 


public int getDipsFromPixel(float pixels) { 
    // Get the screen's density scale 
    final float scale = getResources().getDisplayMetrics().density; 
    // Convert the dps to pixels, based on density scale 
    return (int) (pixels * scale + 0.5f); 
} 
} 

XML файлы XML страницы, которые содержат expandablelist products.xml

<ExpandableListView 
    android:id="@+id/products" 
    android:layout_width="match_parent" 
    android:layout_height="fill_parent" > 
</ExpandableListView> 

parent_view.xml

<TextView 
    android:id="@+id/head" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:paddingLeft="25dp"/> 

child_view.xml

<TextView 
    android:id="@+id/laptop" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentLeft="true" 
    android:layout_centerVertical="true" 
    android:paddingLeft="25dp" /> 

<ImageView 
    android:id="@+id/delete" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentRight="true" 
    android:contentDescription="@string/app_name" 
    android:src="@drawable/ic_delete" /> 

+0

Мое приложение продолжает сбой на этой странице, и я не могу понять, почему. – user2998687

+0

Просьба также отправить файл xml. Итак, мы можем попытаться в конце и посмотреть, можем ли мы сможем помочь. – Prem

+0

Добавлено. Благодарю . – user2998687

ответ

4

пожалуйста, попробуйте и любезно изменить getapplicationcontext() вместо getactivity() и изменить OnCreate для деятельности

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.app.Fragment; 
    import android.app.ProgressDialog; 
    import android.content.Intent; 
    import android.os.AsyncTask; 
    import android.os.Bundle; 
    import android.util.Log; 
    import android.view.LayoutInflater; 
    import android.view.View; 
    import android.view.ViewGroup; 
    import android.widget.ExpandableListAdapter; 
    import android.widget.ExpandableListView; 
    import android.widget.ExpandableListView.OnChildClickListener; 
    import android.widget.ExpandableListView.OnGroupClickListener; 
    import android.widget.ExpandableListView.OnGroupCollapseListener; 
    import android.widget.ExpandableListView.OnGroupExpandListener; 
    import android.widget.TextView; 
    import android.widget.Toast; 

    public class HomeFragment extends Fragment { 
     private static String url = "http://www.androidbegin.com/tutorial/jsonparsetutorial.txt"; 
     private ProgressDialog mprocessingdialog; 
     private TextView tv_welcomeuser, tv_recentupdate; 
     private ExpandableListAdapter expandableListAdapter; 
     private ExpandableListView exp_leaseoffer; 
     private List<String> listDataHeader; 
     private View rootView; 
     private HashMap<String, List<String>> listDataChild; 

     @Override 
     public View onCreateView(LayoutInflater inflater, ViewGroup container, 
       Bundle savedInstanceState) { 

      rootView = inflater.inflate(R.layout.wellcome_page, container, false); 
      tv_welcomeuser = (TextView) rootView.findViewById(R.id.tv_welcomeuser); 
      tv_recentupdate = (TextView) rootView 
        .findViewById(R.id.tv_recentupdate); 

      exp_leaseoffer = (ExpandableListView) rootView.findViewById(R.id.lvExp); 

      new DownloadJason().execute(); 

      return rootView; 
     } 

     private class DownloadJason extends AsyncTask<Void, Void, Void> { 

      @Override 
      protected void onPreExecute() { 
       // TODO Auto-generated method stub 
       super.onPreExecute(); 
       mprocessingdialog = new ProgressDialog(getActivity()); 
       mprocessingdialog.setTitle("Please Wait.."); 
       mprocessingdialog.setMessage("Loading"); 
       mprocessingdialog.setIndeterminate(false); 
       mprocessingdialog.show(); 
      } 

      @Override 
      protected Void doInBackground(Void... arg0) { 
       // TODO Auto-generated method stub 
       listDataHeader = new ArrayList<String>(); 
       JSONParser jp = new JSONParser(); 
       String jsonstr = jp.makeServiceCall(url, JSONParser.GET); 
       Log.d("Json url view", jsonstr); 

       if (jsonstr != null) { 

        listDataHeader = new ArrayList<String>(); 
        listDataChild = new HashMap<String, List<String>>(); 

        try { 
         JSONObject jobj = new JSONObject(jsonstr); 
         JSONArray jarray = jobj.getJSONArray("worldpopulation"); 
         for (int hk = 0; hk < jarray.length(); hk++) { 
          JSONObject d = jarray.getJSONObject(hk); 
          // Adding Header data 

          listDataHeader.add(d.getString("country")); 
          // Adding child data for lease offer 
          List<String> lease_offer = new ArrayList<String>(); 

          lease_offer.add(d.getString("country") + "'s Rank is : " 
            + d.getString("rank")); 
          lease_offer.add("And Population is "+d.getString("population")); 
          // Header into Child data 
          listDataChild.put(listDataHeader.get(hk), lease_offer); 

         } 
        } catch (JSONException e) { 
         // TODO Auto-generated catch block 
         e.printStackTrace(); 
        } 

       } else { 
        Toast.makeText(getActivity(), 
          "Please Check internet Connection", Toast.LENGTH_SHORT) 
          .show(); 

       } 

       return null; 
      } 

      @Override 
      protected void onPostExecute(Void result) { 
       // TODO Auto-generated method stub 
       super.onPostExecute(result); 
       mprocessingdialog.dismiss(); 

       expandableListAdapter = new info.tranetech.adurec.fragments.Expandable_adapter(
         getActivity(), listDataHeader, listDataChild); 
       Log.i("groups", listDataHeader.toString()); 
       Log.i("details", listDataChild.toString()); 
       exp_leaseoffer.setAdapter(expandableListAdapter); 

       exp_leaseoffer.setOnGroupClickListener(new OnGroupClickListener() { 

        @Override 
        public boolean onGroupClick(ExpandableListView parent, View v, 
          int groupPosition, long id) { 
         // TODO Auto-generated method stub 
         return false; 
        } 

       }); 
       // Listview Group expanded listener 
       exp_leaseoffer 
         .setOnGroupExpandListener(new OnGroupExpandListener() { 

          @Override 
          public void onGroupExpand(int groupPosition) { 
           // Toast.makeText(getActivity().getApplicationContext(), 
           // listDataHeader.get(groupPosition) + " Expanded", 
           // Toast.LENGTH_SHORT).show(); 
          } 
         }); 
       exp_leaseoffer 
         .setOnGroupCollapseListener(new OnGroupCollapseListener() { 

          @Override 
          public void onGroupCollapse(int groupPosition) { 
           Toast.makeText(
             getActivity().getApplicationContext(), 
             listDataHeader.get(groupPosition) 
               + " Collapsed", Toast.LENGTH_SHORT) 
             .show(); 
          } 
         }); 
       exp_leaseoffer.setOnChildClickListener(new OnChildClickListener() { 

        @Override 
        public boolean onChildClick(ExpandableListView parent, View v, 
          int groupPosition, int childPosition, long id) { 
         // Toast.makeText(
         // getActivity().getApplicationContext(), 
         // listDataHeader.get(groupPosition) 
         // + " : " 
         // + listDataChild.get(
         // listDataHeader.get(groupPosition)).get(
         // childPosition), Toast.LENGTH_SHORT) 
         // .show(); 

    //     Intent ilk = new Intent(getActivity(), 
    //       Lease_Offer_one.class); 
    //     startActivity(ilk); 

         return false; 
        } 
       }); 

      } 
     } 

     // public Boolean isWifiAvailable() { 
     // 
     // try { 
     // ConnectivityManager connectivityManager = (ConnectivityManager) 
     // getActivity() 
     // .getSystemService(Context.CONNECTIVITY_SERVICE); 
     // NetworkInfo wifiInfo = connectivityManager 
     // .getNetworkInfo(ConnectivityManager.TYPE_WIFI); 
     // 
     // if (wifiInfo.isConnected()) { 
     // return true; 
     // } 
     // } catch (Exception e) { 
     // e.printStackTrace(); 
     // } 
     // return false; 
     // } 

     // public boolean isNetworkAvailable() { 
     // ConnectivityManager connectivityManager = (ConnectivityManager) 
     // getActivity() 
     // .getSystemService(Context.CONNECTIVITY_SERVICE); 
     // NetworkInfo activeNetworkInfo = connectivityManager 
     // .getActiveNetworkInfo(); 
     // return activeNetworkInfo != null && activeNetworkInfo.isConnected(); 
     // } 

    } 

    **This is Expandable_adapter java class** 




    import java.util.HashMap; 
    import java.util.List; 

    import android.content.Context; 
    import android.graphics.Typeface; 
    import android.view.LayoutInflater; 
    import android.view.View; 
    import android.view.ViewGroup; 
    import android.widget.BaseExpandableListAdapter; 
    import android.widget.TextView; 

    public class Expandable_adapter extends BaseExpandableListAdapter { 

     private Context _context; 
     private List<String> _listDataHeader; 
     private HashMap<String, List<String>> _listDataChild; 

     public Expandable_adapter(Context context, List<String> listDataHeader, 
       HashMap<String, List<String>> listDataChild) { 
      this._context = context; 
      this._listDataHeader = listDataHeader; 
      this._listDataChild = listDataChild; 
     } 

     @Override 
     public Object getChild(int groupPosition, int childPosition) { 
      return this._listDataChild.get(this._listDataHeader.get(groupPosition)) 
        .get(childPosition); 
     } 

     @Override 
     public long getChildId(int groupPosition, int childPosition) { 
      return childPosition; 
     } 

     @Override 
     public View getChildView(int groupPosition, final int childPosition, 
       boolean isLastChild, View convertView, ViewGroup parent) { 
      final String childText = (String) getChild(groupPosition, childPosition); 
      if (convertView == null) { 
       LayoutInflater layoutInflater = (LayoutInflater) this._context 
         .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
       convertView = layoutInflater.inflate(R.layout.list_child, null); 
      } 
      TextView expandedListTextView = (TextView) convertView 
        .findViewById(R.id.tv_listchild); 
      expandedListTextView.setText(childText); 
      return convertView; 
     } 

     @Override 
     public int getChildrenCount(int groupPosition) { 
      return this._listDataChild.get(this._listDataHeader.get(groupPosition)) 
        .size(); 
     } 

     @Override 
     public Object getGroup(int groupPosition) { 
      return this._listDataHeader.get(groupPosition); 
     } 

     @Override 
     public int getGroupCount() { 
      return this._listDataHeader.size(); 
     } 

     @Override 
     public long getGroupId(int groupPosition) { 
      return groupPosition; 
     } 

     @Override 
     public View getGroupView(int groupPosition, boolean isExpanded, 
       View convertView, ViewGroup parent) { 
      String headerTitle = (String) getGroup(groupPosition); 
      if (convertView == null) { 
       LayoutInflater layoutInflater = (LayoutInflater) this._context 
         .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
       convertView = layoutInflater.inflate(R.layout.list_group, null); 
      } 
      TextView listTitle = (TextView) convertView 
        .findViewById(R.id.tv_listtitle); 
      listTitle.setTypeface(null, Typeface.BOLD); 
      listTitle.setText(headerTitle); 
      return convertView; 
     } 

     @Override 
     public boolean hasStableIds() { 
      return false; 
     } 

     @Override 
     public boolean isChildSelectable(int groupPosition, int childPosition) { 
      return true; 
     } 
    } 
**xml wellcome_page** 
<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="wrap_content" 
    android:layout_height="match_parent" 
    android:background="@drawable/background_welcome" > 

    <LinearLayout 
     android:id="@+id/header" 
     android:layout_width="fill_parent" 
     android:layout_height="40dp" 
     android:layout_alignParentBottom="true" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentRight="true" 
     android:background="@drawable/bottom_bar" 
     android:orientation="horizontal" > 
    </LinearLayout> 

    <TextView 
     android:id="@+id/tv_welcomeuser" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentTop="true" 
     android:layout_marginTop="8dp" 
     android:gravity="center" 
     android:text="WELCOME USER" 
     android:textColor="#FFFFFF" 
     android:textSize="16sp" 
     tools:ignore="HardcodedText" /> 

    <LinearLayout 
     android:id="@+id/eeeee" 
     android:layout_width="200dp" 
     android:layout_height="30dp" 
     android:layout_below="@+id/tv_welcomeuser" 
     android:layout_centerHorizontal="true" 
     android:layout_marginTop="20dp" 
     android:background="@drawable/edit_text" 
     android:gravity="center" > 

     <TextView 
      android:id="@+id/tv_recentupdate" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:gravity="center" 
      android:paddingLeft="20dp" 
      android:paddingRight="20dp" 
      android:singleLine="true" 
      android:text="RECENT UPDATES" 
      android:textColor="#FFFFFF" 
      android:textSize="18sp" 
      tools:ignore="HardcodedText" /> 

    </LinearLayout> 

    <RelativeLayout 
     android:id="@+id/expl" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:layout_above="@+id/header" 
     android:layout_alignParentLeft="true" 
     android:layout_below="@+id/eeeee" 
     android:layout_marginTop="20dp" > 

     <LinearLayout 
      android:id="@+id/textLin" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:layout_alignParentBottom="true" 
      android:gravity="center" 
      android:orientation="vertical" 
      android:weightSum="4" > 

      <TextView 
       android:id="@+id/tv_adurec" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_below="@+id/lvExp" 
       android:layout_centerHorizontal="true" 
       android:layout_weight="1" 
       android:fontFamily="times_roman" 
       android:text=" Powered by " 
       android:textColor="#ffffff" 
       android:textSize="15dp" 
       tools:ignore="ObsoleteLayoutParam,HardcodedText,SpUsage" /> 

      <TextView 
       android:id="@+id/textView1" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_alignRight="@+id/tv_adurec" 
       android:layout_centerVertical="true" 
       android:layout_marginBottom="10dp" 
       android:layout_weight="1" 
       android:text="ADUREC" 
       android:textAppearance="?android:attr/textAppearanceMedium" 
       android:textColor="#ffffff" 
       tools:ignore="ObsoleteLayoutParam,HardcodedText" /> 

     </LinearLayout> 

     <ExpandableListView 
      android:id="@+id/lvExp" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:layout_above="@+id/textLin" 
      android:listSelector="@drawable/buttons_effacts" 
      android:divider="@color/list_divider" 
      android:dividerHeight="0.8dip" 
      android:layout_alignParentLeft="true" 
      android:layout_alignParentTop="true" > 
     </ExpandableListView> 
    </RelativeLayout> 

</RelativeLayout> 

**list_child.xml ** 
<?xml version="1.0" encoding="utf-8"?> 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:gravity="center"> 
    <TextView 
     android:id="@+id/tv_listchild" 
     android:layout_width="fill_parent" 
     android:layout_height="40dp" 
     android:paddingTop="10dp" 
     android:textSize="16sp" 
     android:gravity="center" 
     android:textColor="#7D1023" 
     android:background="#ffffff" 
     android:paddingBottom="10dp" /> 
</LinearLayout> 

**list_group.xml** 
<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" > 

    <TextView 
     android:id="@+id/tv_listtitle" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:background="@drawable/buttons_effacts" 
     android:padding="15dp" 
     android:gravity="center" 
     android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft" 
     android:textColor="#ffffff" 
     android:textSize="16sp" /> 

</LinearLayout> 
Смежные вопросы