从 mysql 填充可扩展列表视图导致应用程序崩溃

Populate Expandable Listview from mysql crashes app

我正在尝试从数据库中填充可扩展列表视图,但应用程序在没有任何日志的情况下崩溃了

我的代码:

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);
    }

我的适配器class:

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>>

当我打开应用程序时,它只是让我回到第一个 activity 而没有任何 logcat 输出,因为发生这种情况。

有什么想法吗??

提前致谢!!

看起来问题出在您的 AsyncTask 中的 inputStreamToString 方法中。

在此方法的 catch 中,您应该再次抛出异常,以便调用方法 doInBackground 可以处理它(并因此打印堆栈跟踪)...或者在 inputStreamToString.

中以某种方式处理它

由于您在此处调用 getActivity().finish(),因此 activity 即将结束,无法记录任何内容。

例如:

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

在您的 onCreateView 上首先将数组列表初始化为

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