从ArrayList计算最大值不起作用

从ArrayList计算最大值不起作用

public class GraphFrameV2 extends Fragment implements AdapterView.OnItemSelectedListener {
    Integer hoodSelector = 27;
    ArrayList<HoodData> hoodDataList = new ArrayList<>();
    ArrayList<String> hoodList = new ArrayList<>();
    ArrayList<HoodData> completeHoodList = new ArrayList<>();

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        String item = parent.getItemAtPosition(position).toString();
        // Showing selected spinner item
        for(int i = 1; i < hoodList.size(); i++) {
            if (item.equals(hoodList.get(i))) {
                setHoodId(i + 27);
                refreshFragment();
            }

        }
    }
    public Double calculateMax(Integer year){
        Double max = completeHoodList.get(0).getPercentage();
        if(year == 2006){
            for(Integer z = 0; z < completeHoodList.size(); z ++){
                if(completeHoodList.get(z).getYear() == 2006){
                    if(completeHoodList.get(z).getPercentage() > max){
                        max = completeHoodList.get(z).getPercentage();
                    }
                }
            }
        }
        Toast.makeText(getActivity(), String.valueOf(max),
                Toast.LENGTH_LONG).show();
        return max;
    }
    public void calculateMin(Integer year){
        Double min = completeHoodList.get(0).getPercentage();
        if(year == 2006){
            for(Integer z = 0; z < completeHoodList.size(); z ++){
                if(completeHoodList.get(z).getYear() == 2006){
                    if(completeHoodList.get(z).getPercentage() < min){
                        min = completeHoodList.get(z).getPercentage();
                    }
                }
            }
        }
        if(year == 2007){
            for(Integer z = 0; z < completeHoodList.size(); z ++){
                if(completeHoodList.get(z).getYear() == 2007){
                    if(completeHoodList.get(z).getPercentage() < min){
                        min = completeHoodList.get(z).getPercentage();
                    }
                }
            }
        }
        if(year == 2008){
            for(Integer z = 0; z < completeHoodList.size(); z ++){
                if(completeHoodList.get(z).getYear() == 2008){
                    if(completeHoodList.get(z).getPercentage() < min){
                        min = completeHoodList.get(z).getPercentage();
                    }
                }
            }
        }
        if(year == 2009){
            for(Integer z = 0; z < completeHoodList.size(); z ++){
                if(completeHoodList.get(z).getYear() == 2009){
                    if(completeHoodList.get(z).getPercentage() < min){
                        min = completeHoodList.get(z).getPercentage();
                    }
                }
            }
        }
        if(year == 2011){
            for(Integer z = 0; z < completeHoodList.size(); z ++){
                if(completeHoodList.get(z).getYear() == 2011){
                    if(completeHoodList.get(z).getPercentage() < min){
                        min = completeHoodList.get(z).getPercentage();
                    }
                }
            }
        }
    }
    public Double calculateAvg(Integer year){
        Double avg = null;
        Double sum = 0.0;
        Integer counter = 0;
        if(year == 2006){
            for(Integer z = 0; z < completeHoodList.size(); z++){
                if(completeHoodList.get(z).getYear() == 2006){
                    sum = sum + completeHoodList.get(z).getPercentage();
                    counter = counter + 1;
                }
            }
        }
        return Math.round((sum/counter) * Math.pow(10, 1)) / Math.pow(10, 1);

    }
    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
    public void refreshFragment(){
        //refreshes the Fragment
        hoodDataList.clear();
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.detach(this).attach(this).commit();
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_graph,
                container, false);
        //API Request for all the hoods
        getAllData();
        getDataFromApi((GraphView) view.findViewById(R.id.graph));
        getDataForSpinner((Spinner) view.findViewById(R.id.spinner));
        return view;
    }

    public void setHoodId(Integer hood){
        hoodSelector = hood;
    }

    public void getAllData(){
        RequestQueue rq = Volley.newRequestQueue(getActivity().getApplicationContext());
        String url= "http://test.dontstealmywag.ga/api/theft_outof_car_wijk.php";
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        // Do something with the response
                        try{
                            JSONObject o = new JSONObject(response);
                            JSONArray values=o.getJSONArray("");
                            for (int i = 0; i < values.length(); i++) {
                                JSONObject jsonObject = values.getJSONObject(i);
                                completeHoodList.add(new HoodData(jsonObject.getDouble("percentage"), jsonObject.getInt("hood_id"), jsonObject.getInt("year"), jsonObject.getString("hood_name")));
                            }

                        }  catch (JSONException ex){}

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // Handle error
                    }
                });


        rq.add(stringRequest);
    }

    public void getDataFromApi(final GraphView graph) {
        RequestQueue rq = Volley.newRequestQueue(getActivity().getApplicationContext());
        String url= "http://test.dontstealmywag.ga/api/theft_outof_car_wijk.php?hood_id=" + hoodSelector;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        // Do something with the response
                        try{
                            JSONObject o = new JSONObject(response);
                            JSONArray values=o.getJSONArray("");
                            for (int i = 0; i < values.length(); i++) {
                                JSONObject jsonObject = values.getJSONObject(i);
                                hoodDataList.add(new HoodData(jsonObject.getDouble("percentage"), jsonObject.getInt("hood_id"), jsonObject.getInt("year"), jsonObject.getString("hood_name")));
                            }

                        }  catch (JSONException ex){}
                        StaticLabelsFormatter staticLabelsFormatter = new StaticLabelsFormatter(graph);
                        LineGraphSeries<DataPoint> series = new LineGraphSeries<>(new DataPoint[] {
                                new DataPoint(1, (calculateAvg(2006 /2))),
                                new DataPoint(2, hoodDataList.get(1).getPercentage()),
                                new DataPoint(3, hoodDataList.get(2).getPercentage()),
                                new DataPoint(4, hoodDataList.get(3).getPercentage()),
                                new DataPoint(5, hoodDataList.get(4).getPercentage())
                                //new DataPoint(12, 0)
                        });
                        LineGraphSeries<DataPoint> average = new LineGraphSeries<>(new DataPoint[]{
                                new DataPoint(1, 16.2),
                                new DataPoint(2, 15.5),
                                new DataPoint(3, 15.2),
                                new DataPoint(4, 15.9),
                                new DataPoint(5, 13.9)
                        });

                        // set manual x bounds
                        staticLabelsFormatter.setHorizontalLabels(new String[] {"2006", "2007","2008","2009","2011"});
                        //creates custom x-axis
                        graph.getGridLabelRenderer().setLabelFormatter(staticLabelsFormatter);
                        graph.setTitle("Wijk " + hoodSelector + " - " + hoodDataList.get(0).getHood_name());
                        //set nice background color :)
                        series.setDrawBackground(true);
                        //shows points at datapoints
                        series.setDrawDataPoints(true);
                        average.setDrawDataPoints(true);
                        //size of the points
                        series.setDataPointsRadius(10.0f);
                        series.setOnDataPointTapListener(new OnDataPointTapListener() {
                            @Override
                            public void onTap(Series series, DataPointInterface dataPoint) {
                                Toast.makeText(getActivity(), "Punt "+ dataPoint, Toast.LENGTH_SHORT).show();
                            }
                        });
                        series.setTitle("%");
                        series.setAnimated(true);
                        average.setAnimated(true);
                        average.setColor(Color.argb(255, 0, 51, 153));
                        average.setThickness(5);
                        series.setColor(Color.argb(255, 102, 204, 255));
                        graph.addSeries(average);
                        graph.getLegendRenderer().setVisible(true);
                        graph.getLegendRenderer().setAlign(LegendRenderer.LegendAlign.TOP);
                        graph.addSeries(series);




                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // Handle error
                    }
                });


        rq.add(stringRequest);
    }
    public void getDataForSpinner(final Spinner spinner){
        RequestQueue rq = Volley.newRequestQueue(getActivity().getApplicationContext());
        String url= "http://test.dontstealmywag.ga/api/theft_outof_car_wijk.php";
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        // Do something with the response

                        try{
                            JSONObject o = new JSONObject(response);
                            JSONArray values=o.getJSONArray("");
                            for (int i = 0; i < values.length(); i++) {
                                JSONObject jsonObject = values.getJSONObject(i);
                                if (!hoodList.contains(jsonObject.getString("hood_name"))) {
                                    hoodList.add(jsonObject.getString("hood_name"));
                                }
                            }
                        }  catch (JSONException ex){}

                        ArrayAdapter<String> adapter = new ArrayAdapter<String>(spinner.getContext(), android.R.layout.simple_spinner_item, hoodList);
                        // Specify the layout to use when the list of choices appears
                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        // Apply the adapter to the spinner
                        spinner.setPrompt("Title");
                        spinner.setAdapter(adapter);

                        spinner.setOnItemSelectedListener(GraphFrameV2.this);


                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // Handle error
                    }
                });


        rq.add(stringRequest);
    }


}


问题:

我已经编写了这段代码。当我在getAllData中调用calculateMax(2006)时,它可以很好地工作并给我想要的吐司,但是当我在getDataFromApi中调用它时,应用程序崩溃了,告诉我我的列表不包含任何项目。

这很奇怪,因为我的calculateAvg()方法确实有效。

谁能帮我解决这个问题?

最佳答案

该问题与以下事实有关:网络请求本质上是异步的。

假设有3个同步动作(A,B,C)

Start A
Complete A
Start B
Complete B
Start C
Complete C


如果B是异步的,则可能会发生

Start A
Complete A
Start B (async)
Start C (maybe C need the result from B, but unfortunately B is still running, on another thread)
Complete C
Complete B


因此,如果您的下一个操作需要执行异步操作,则基本上必须等到异步操作完成。

为此,您需要在回调onResponse()中执行下一个操作。仅在此数据可用。

关于java - 从ArrayList计算最大值不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43503280/

10-10 08:22