如何使用JSON中的数据每秒刷新我的应用程序?

时间:2016-01-08 11:36:09

标签: php android json handler android-volley

我已经构建了一个从JSON URL获取信息的应用程序,并将其放在textview和BarChart(mikephil的API)中,但我希望它每秒刷新一次。 这是我的MainActivity:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.grafiek);
    if(savedInstanceState!=null){
        Log.d("STATE", savedInstanceState.toString());
    }

    requestQueue = Volley.newRequestQueue(this);
    chart = (BarChart) findViewById(R.id.chart);
    JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, loginURL, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {

                    try{

                        JSONArray ja = response.getJSONArray("result");
                        for(int i=0; i < ja.length(); i++){

                            JSONObject jsonObject = ja.getJSONObject(i);

                            String agv = jsonObject.getString("agv");
                            String binnenschip = jsonObject.getString("binnenschip");
                            String vrachtwagen = jsonObject.getString("vrachtwagen");
                            String zeeschip = jsonObject.getString("zeeschip");
                            String opslag = jsonObject.getString("opslag");
                            String trein = jsonObject.getString("trein");
                            String diversen = jsonObject.getString("diversen");

                            agvz = Integer.parseInt(agv);
                            binns = Integer.parseInt(binnenschip);
                            vracht = Integer.parseInt(vrachtwagen);
                            zschip = Integer.parseInt(zeeschip);
                            opsl = Integer.parseInt(opslag);
                            trei = Integer.parseInt(trein);
                            divers = Integer.parseInt(diversen);

                            ArrayList<BarEntry> entries = new ArrayList<>();
                            entries.add(new BarEntry(agvz, 0));
                            entries.add(new BarEntry(binns, 1));
                            entries.add(new BarEntry(vracht, 2));
                            entries.add(new BarEntry(zschip, 3));
                            entries.add(new BarEntry(opsl, 4));
                            entries.add(new BarEntry(trei, 5));
                            entries.add(new BarEntry(divers, 6));
                            BarDataSet dataset = new BarDataSet(entries, "Aantal containers");

                            ArrayList<String> labels = new ArrayList<String>();
                            labels.add("AGV");
                            labels.add("Binnenschip");
                            labels.add("Vrachtwagen");
                            labels.add("Zeeschip");
                            labels.add("Opslag");
                            labels.add("Trein");
                            labels.add("Diversen");


                            chart = new BarChart(mContext);

                            setContentView(chart);

                            BarData data = new BarData(labels, dataset);
                            chart.setData(data);

                            chart.setDescription("");

                            dataset.setColors(ColorTemplate.COLORFUL_COLORS);

                            /*if(counter == 0) {
                                chart.animateY(2500);
                                counter++;
                            }*/


                        }

                    }
                    catch(JSONException e){
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("Volley","Error");

                }
            }
    );
    requestQueue.add(jor);

这是我的xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/grafiek"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:orientation="vertical" >
<com.github.mikephil.charting.charts.BarChart
    android:id="@+id/chart"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"/>
<Button
    android:id="@+id/parseJsongraph"
    android:text="get DATA"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="0" />
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/json"/>
</RelativeLayout>

最后:这是我开始活动的地方:

public class MainMenu extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.menu);
    final Button grafiek = (Button) findViewById(R.id.grafiek);
    final Button info = (Button) findViewById(R.id.info);

    grafiek.setOnClickListener(new View.OnClickListener() {


        public void onClick(View v) {
            grafiek.setBackgroundColor(Color.GRAY);
            new CountDownTimer(1000, 50) {

                @Override
                public void onTick(long arg0) {
                }

                @Override
                public void onFinish() {
                    grafiek.setBackgroundColor(Color.BLACK);
                }
            }.start();
            goToGrafiek();

        }

    });
    info.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            info.setBackgroundColor(Color.GRAY);
            new CountDownTimer(1000, 50) {

                @Override
                public void onTick(long arg0) {
                }

                @Override
                public void onFinish() {
                    info.setBackgroundColor(Color.BLACK);
                }
            }.start();
            goToInfo();

        }

    });
}
private void goToGrafiek() {

    Intent intent = new Intent(MainMenu.this, grafiek.class);
    startActivity(intent);
}
private void goToInfo(){
    Intent intents = new Intent(MainMenu.this, MainActivity.class);
    startActivity(intents);
}

}

2 个答案:

答案 0 :(得分:0)

Handler autoUpdateHandler;

在OnCreateView中添加

autoUpdateHandler= new Handler

这将每1秒调用一次udpateChartFromJson()。

autoUpdateHandler.postDelayed(new Runnable() {
            @Override
            public void run()
            {
                //start the following method every 1 second. 
                  updateChartFromJson(); 
                  autoUpdateHandler.postDelayed(this,1000);

            }
        },1000);

当Volley将其网络呼叫作为异步任务处理时,此数据将在后台更新。

这就像正常方法宣言:

 public void  updateChartFromJson()
    {
    JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, loginURL, null,
                new Response.Listener<JSONObject>() {
                    @Override 
                    public void onResponse(JSONObject response) {

                        try{ 

                            JSONArray ja = response.getJSONArray("result");
                            for(int i=0; i < ja.length(); i++){

                                JSONObject jsonObject = ja.getJSONObject(i);

                                String agv = jsonObject.getString("agv");
                                String binnenschip = jsonObject.getString("binnenschip");
                                String vrachtwagen = jsonObject.getString("vrachtwagen");
                                String zeeschip = jsonObject.getString("zeeschip");
                                String opslag = jsonObject.getString("opslag");
                                String trein = jsonObject.getString("trein");
                                String diversen = jsonObject.getString("diversen");

                                agvz = Integer.parseInt(agv);
                                binns = Integer.parseInt(binnenschip);
                                vracht = Integer.parseInt(vrachtwagen);
                                zschip = Integer.parseInt(zeeschip);
                                opsl = Integer.parseInt(opslag);
                                trei = Integer.parseInt(trein);
                                divers = Integer.parseInt(diversen);

                                ArrayList<BarEntry> entries = new ArrayList<>();
                                entries.add(new BarEntry(agvz, 0));
                                entries.add(new BarEntry(binns, 1));
                                entries.add(new BarEntry(vracht, 2));
                                entries.add(new BarEntry(zschip, 3));
                                entries.add(new BarEntry(opsl, 4));
                                entries.add(new BarEntry(trei, 5));
                                entries.add(new BarEntry(divers, 6));
                                BarDataSet dataset = new BarDataSet(entries, "Aantal containers");

                                ArrayList<String> labels = new ArrayList<String>();
                                labels.add("AGV");
                                labels.add("Binnenschip");
                                labels.add("Vrachtwagen");
                                labels.add("Zeeschip");
                                labels.add("Opslag");
                                labels.add("Trein");
                                labels.add("Diversen");


                                chart = new BarChart(mContext); 

                                setContentView(chart);

                                BarData data = new BarData(labels, dataset);
                                chart.setData(data);

                                chart.setDescription(""); 

                                dataset.setColors(ColorTemplate.COLORFUL_COLORS);

                                /*if(counter == 0) { 
                                    chart.animateY(2500); 
                                    counter++; 
                                }*/ 


                            } 

                        } 
                        catch(JSONException e){
                            e.printStackTrace();
                        } 
                    } 
                }, 
                new Response.ErrorListener() {
                    @Override 
                    public void onErrorResponse(VolleyError error) {
                        Log.e("Volley","Error");

                    } 
                } 
        ); 
        requestQueue.add(jor);

    }

答案 1 :(得分:0)

swipeRefreshLayout.setOnRefreshListener(() -> {
        homeCategoriesModalList.clear(); // Clean The List Before Adding Updated Data
        categoryCityAreaRecyclerViewAdapter.notifyDataSetChanged();
        jsonResponse();
        categoryCityAreaRecyclerViewAdapter.notifyDataSetChanged();

        swipeRefreshLayout.setRefreshing(false);
    });
<块引用>

处理我的项目