在从JSON文件存储数据之前执行下一个代码

时间:2017-01-04 04:06:35

标签: android json android-volley mpandroidchart

我正在使用Volley通过以下方式从服务器检索JSON格式:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_device_report);

        setContentView(R.layout.activity_fuel);
        linechart = (LineChart) findViewById(R.id.lineChart);

        requestQueue = Volley.newRequestQueue(this);
        JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, url,

                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try{
                            JSONArray dataset =  response.getJSONArray("dataset");
                            JSONObject petrol = dataset.getJSONObject(0);
                            JSONObject diesel = dataset.getJSONObject(1);
                            JSONArray categories = response.getJSONArray("categories");

                            JSONArray petrolarray = petrol.getJSONArray("data");
                            JSONArray dieselarray = diesel.getJSONArray("data");
                            Log.d("debug","Size of PetrolArray: " + petrolarray.length());
                            for(int i = 0; i<petrolarray.length();i++) {
                                Log.d("debug", "Petrol Prices consists of: " + petrolarray.getJSONObject(i).getString("value"));
                                float prtl = Float.parseFloat(petrolarray.getJSONObject(i).getString("value"));
                                float dsl = Float.parseFloat(dieselarray.getJSONObject(i).getString("value"));
                                petrolPrices.add(new Entry(i,prtl));
                                dieselPrices.add(new Entry(i,dsl));
                                xMonths.add(categories.getJSONObject(i).getString("label"));
                            }
                        } catch (JSONException e){
                            e.printStackTrace();
                        }
                    }
                },

                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
        requestQueue.add(req);

        ArrayList<ILineDataSet> lineDataSets= new ArrayList<>();

        LineDataSet lineDataSet1 = new LineDataSet(petrolPrices,"petrol");
        lineDataSets.add(lineDataSet1);

        Log.d("debug","Size of PetrolPrices: " + petrolPrices.size());
        linechart.setData(new LineData(lineDataSets));
        linechart.setVisibleXRangeMaximum(12);
    }

当我测试此代码时,首先出现带有“PetrolPrices大小”的调试消息,然后出现“PetrolArray大小”调试消息。这意味着当PetrolPrices arraylist绘制图形时会导致错误,因此它是空的。即使代码在之前,数据也不会被添加到其中。

我不确定我是否解释得很好,但希望这已经足够了。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

这与您为获取JSON数据而进行的异步请求有关。由于此部分代码必须等待服务器响应,因此它继续使用请求块下面的代码。要修复它,只需移动请求函数。

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_device_report);

        setContentView(R.layout.activity_fuel);
        linechart = (LineChart) findViewById(R.id.lineChart);

        requestQueue = Volley.newRequestQueue(this);
        JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, url,

                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try{
                            JSONArray dataset =  response.getJSONArray("dataset");
                            JSONObject petrol = dataset.getJSONObject(0);
                            JSONObject diesel = dataset.getJSONObject(1);
                            JSONArray categories = response.getJSONArray("categories");

                            JSONArray petrolarray = petrol.getJSONArray("data");
                            JSONArray dieselarray = diesel.getJSONArray("data");
                            Log.d("debug","Size of PetrolArray: " + petrolarray.length());
                            for(int i = 0; i<petrolarray.length();i++) {
                                Log.d("debug", "Petrol Prices consists of: " + petrolarray.getJSONObject(i).getString("value"));
                                float prtl = Float.parseFloat(petrolarray.getJSONObject(i).getString("value"));
                                float dsl = Float.parseFloat(dieselarray.getJSONObject(i).getString("value"));
                                petrolPrices.add(new Entry(i,prtl));
                                dieselPrices.add(new Entry(i,dsl));
                                xMonths.add(categories.getJSONObject(i).getString("label"));
                            }

                            ArrayList<ILineDataSet> lineDataSets= new ArrayList<>();

                            LineDataSet lineDataSet1 = new LineDataSet(petrolPrices,"petrol");
                            lineDataSets.add(lineDataSet1);

                            Log.d("debug","Size of PetrolPrices: " + petrolPrices.size());
                            // linechart.setData(new LineData(lineDataSets));
                            linechart.setVisibleXRangeMaximum(12);
                        } catch (JSONException e){
                            e.printStackTrace();
                        }
                    }
                },

                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
        requestQueue.add(req);


    }

答案 1 :(得分:1)

强烈建议使用函数来确保您的代码适合阅读和错误跟踪。

使用这样的代码。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_fuel);
    linechart = (LineChart) findViewById(R.id.lineChart);

    requestQueue = Volley.newRequestQueue(this);
    JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, url,

            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try{
                        JSONArray dataset =  response.getJSONArray("dataset");
                        JSONObject petrol = dataset.getJSONObject(0);
                        JSONObject diesel = dataset.getJSONObject(1);
                        JSONArray categories = response.getJSONArray("categories");

                        JSONArray petrolarray = petrol.getJSONArray("data");
                        JSONArray dieselarray = diesel.getJSONArray("data");
                        Log.d("debug","Size of PetrolArray: " + petrolarray.length());
                        for(int i = 0; i<petrolarray.length();i++) {
                            try{
                            Log.d("debug", "Petrol Prices consists of: " + petrolarray.getJSONObject(i).getString("value"));
                            float prtl = Float.parseFloat(petrolarray.getJSONObject(i).getString("value"));
                            float dsl = Float.parseFloat(dieselarray.getJSONObject(i).getString("value"));
                            petrolPrices.add(new Entry(i,prtl));
                            dieselPrices.add(new Entry(i,dsl));
                            xMonths.add(categories.getJSONObject(i).getString("label"));
                            } catch (JSONException e){
                            e.printStackTrace();
                            //This is make sure that if some json data is wrongly formatted it then it should not influence other results.
                            }
                        }
                      processResult(petrolPrices);
                    } catch (JSONException e){
                        e.printStackTrace();
                    }
                }
            },

            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });
    requestQueue.add(req);

}

并创建一个处理结果的函数。

private void processResult(Arraylist<Entry> petrolPrices)
{

    ArrayList<ILineDataSet> lineDataSets= new ArrayList<>();

    LineDataSet lineDataSet1 = new LineDataSet(petrolPrices,"petrol");
    lineDataSets.add(lineDataSet1);

    Log.d("debug","Size of PetrolPrices: " + petrolPrices.size());
    linechart.setData(new LineData(lineDataSets));
    linechart.setVisibleXRangeMaximum(12);
}