2015-02-07 2 views
1

Я пытаюсь заполнить расширяемую ListView из базы данных и сбои приложения без какого-либо журналаPopulate расширяемый ListView из MySQL аварий приложение

Моего кода:

onCreateView:

private View rootView; 
    private ExpandableListView lv; 
    private BaseExpandableListAdapter adapter; 
    private String jsonResult; 
    private String url = "http://reservations.cretantaxiservices.gr/files/getspirits.php"; 
    ProgressDialog pDialog; 
    ArrayList<ProductList> childs; 
    String[] products; 
    ArrayList<ExpandableListParent> customList; 

    @Override 
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 
     rootView = inflater.inflate(R.layout.activity_spirits_fragment, container, false); 
     lv = (ExpandableListView)rootView.findViewById(R.id.spiritsListView); 
     final SwipeRefreshLayout mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.activity_main_swipe_refresh_layout); 
     ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(getActivity().getApplicationContext().CONNECTIVITY_SERVICE); 
     NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); 
     boolean network_connected = activeNetwork != null && activeNetwork.isAvailable() && activeNetwork.isConnectedOrConnecting(); 

     if (!network_connected) { 
      onDetectNetworkState().show(); 
     } else { 
      if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) { 
       accessWebService(); 
       registerCallClickBack(); 
       mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { 
        @Override 
        public void onRefresh() { 
         accessWebService(); 
         mSwipeRefreshLayout.setRefreshing(false); 
        } 
       }); 
      } 
     } 
     return rootView; 
    } 

JSONTask

public class JsonReadTask extends AsyncTask<String , Void, ArrayList<ExpandableListParent>> { 
     public JsonReadTask() { 
      super(); 
     } 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      pDialog = new ProgressDialog(getActivity(), ProgressDialog.THEME_DEVICE_DEFAULT_DARK); 
      pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); 
      pDialog.setIndeterminate(true); 
      pDialog.setMessage(getString(R.string.get_stocks)); 
      pDialog.setCancelable(false); 
      pDialog.setInverseBackgroundForced(true); 
      pDialog.show(); 
     } 

     @Override 
     protected ArrayList<ExpandableListParent> doInBackground(String... params) { 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost(params[0]); 
      try { 
       HttpResponse response = httpclient.execute(httppost); 
       jsonResult = inputStreamToString(
         response.getEntity().getContent()).toString(); 
       customList = new ArrayList<>(); 

       JSONObject jsonResponse = new JSONObject(jsonResult); 
       JSONArray jsonMainNode = jsonResponse.optJSONArray("spirits"); 
       for (int i = 0; i < jsonMainNode.length(); i++) { 
        JSONObject jsonChildNode = jsonMainNode.getJSONObject(i); 
        String name = jsonChildNode.optString("type"); 
        String price = jsonChildNode.optString("price"); 
        String image = jsonChildNode.optString("image"); 

        String p1 = jsonChildNode.optString("product1"); 
        String p2 = jsonChildNode.optString("product2"); 
        String p3 = jsonChildNode.optString("product3"); 


        products = new String[]{p1, p2, p3}; 

        childs.add(new ProductList(price, products, image)); 

        customList.add(new ExpandableListParent(name, childs)); 
       } 
       return customList; 
      } catch (Exception e) { 
       e.printStackTrace(); 
       getActivity().finish(); 
      } 
      return null; 
     } 

     private StringBuilder inputStreamToString(InputStream is) { 
      String rLine = ""; 
      StringBuilder answer = new StringBuilder(); 
      BufferedReader rd = new BufferedReader(new InputStreamReader(is)); 
      try { 
       while ((rLine = rd.readLine()) != null) { 
        answer.append(rLine); 
       } 
      } catch (Exception e) { 
       getActivity().finish(); 
      } 
      return answer; 
     } 

     @Override 
     protected void onPostExecute(ArrayList<ExpandableListParent> customList) { 
      if(customList == null){ 
       Log.d("ERORR", "No result to show."); 
       return; 
      } 
      ListDrawer(customList); 
      pDialog.dismiss(); 
     } 
    }// end async task 

    public void accessWebService() { 
     JsonReadTask task = new JsonReadTask(); 
     task.execute(new String[]{url}); 
    } 

    public void ListDrawer(ArrayList<ExpandableListParent> customList) { 
     adapter = new ExpandListAdapter(getActivity().getApplicationContext(), customList); 
     lv.setAdapter(adapter); 
    } 

Мой класс Adapter:

public class ExpandListAdapter extends BaseExpandableListAdapter { 

    private Context context; 
    private ArrayList<ExpandableListParent> groups; 


    public ExpandListAdapter(Context context, ArrayList<ExpandableListParent> groups) { 
     this.context = context; 
     this.groups = groups; 
    } 

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

    @Override 
    public int getChildrenCount(int groupPosition) { 
     return groups.get(groupPosition).getChilds().size(); 
    } 

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

    @Override 
    public Object getChild(int groupPosition, int childPosition) { 
     return groups.get(groupPosition).getChilds().get(childPosition); 
    } 

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

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

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

    @Override 
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { 
     ExpandableListParent group = (ExpandableListParent) getGroup(groupPosition); 
     if (convertView == null) { 
      LayoutInflater inf = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE); 
      convertView = inf.inflate(R.layout.exp_list_item_parent, null); 
     } 
     TextView tv = (TextView) convertView.findViewById(R.id.exp_text); 
     tv.setText(group.getName()); 
     return convertView; 
    } 

    @Override 
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { 
     ProductList child = (ProductList) getChild(groupPosition, childPosition); 
     if (convertView == null) { 
      LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE); 
      convertView = infalInflater.inflate(R.layout.list_item, null); 
     } 
     TextView tv = (TextView) convertView.findViewById(R.id.product_name_coffee); 
     tv.setText(child.getName()); 
     TextView tvp = (TextView) convertView.findViewById(R.id.product_price_coffee); 
     tvp.setText("5"); 
     ImageView iv = (ImageView)convertView.findViewById(R.id.product_image_coffee); 
     Ion.with(iv).error(R.drawable.ic_launcher).placeholder(R.drawable.ic_launcher).load(child.getImage()); 
     return convertView; 
    } 

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

Ошибка LogCat:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference 
     at fragments.SpiritsFragment$JsonReadTask.doInBackground(SpiritsFragment.java:225) 
     at fragments.SpiritsFragment$JsonReadTask.doInBackground(SpiritsFragment.java:161) 

Линии ошибок:

SpiritsFragment.java 225: childs.add(new ProductList(price, products, image)); 

SpiritsFragment.java 161: public class JsonReadTask extends AsyncTask<String , Void, ArrayList<ExpandableListParent>> 

И когда я открыть приложение это просто получает меня обратно к 1-ой деятельности без выхода LogCat для причина в том, что это происходит.

Любые идеи?

Спасибо заранее!

+0

'первая деятельность без выхода LogCat по той причине, что это happening' журнал не показывается, потому что вы не используя 'e.printStackTrace();' в блоке catch. используйте 'e.printStackTrace();' в каждом блоке catch и после журнала сбоев с вопросом –

+0

ну, я редактировал свой вопрос, и вы можете увидеть ошибку выше. Он также говорит, что у меня есть ошибка в 'SpiritFragment.java', где эта строка' pDialog.show(); 'любые идеи? –

+0

Является ли 'NewOrder' вашим классом? показать больше журнала, потому что проблема находится в 'NewOrder' class –

ответ

0

на вашем onCreateView инициализации ArrayList первый в

@Override 
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 
    childs = new ArrayList<ProductList>(); 
    ... 
} 
0

Похоже, проблема в вашем методе inputStreamToString в вашей AsyncTask.

В catch в этом методе, вы должны либо выбросить исключение снова так что doInBackground, метод вызова, может справиться с этим (и, следовательно, печать трассировки стека) ... или обрабатывать в нем каким-то образом в inputStreamToString.

Поскольку вы звоните getActivity().finish() здесь, действие заканчивается до того, как все может быть зарегистрировано вообще.

Например:

catch (Exception ex) { 
    throw new RuntimeException(ex.getMessage()); 
} 
+0

Я попробую это –

+0

, он дал мне ошибку выше..и изменил мой вопрос –

Смежные вопросы