簡體   English   中英

我如何每分鍾運行asyncTask並在Android中的UI上替換?

[英]How can i run asyncTask at every minute and replace on UI in android?

我想從本地服務器xammp中的JSON文件加載更新的數據。 我已經做過從json文件獲取數據

這是我的fragment_one.xml

<?xml version="1.0" encoding="utf-8"?>

<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:focusableInTouchMode="true"
        android:orientation="vertical">

        <ListView
            android:id="@+id/listview"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:divider="@null">
        </ListView>
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="50dp"
            android:orientation="horizontal">
            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="50dp"
                android:orientation="horizontal"
                android:layout_weight="1"
                android:layout_marginLeft="5dp">

                <TextView
                    android:id="@+id/txtbExtras"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:textColor="#000000"
                    android:textSize="12dp"
                    android:text="Extras:"/>
                <TextView
                    android:id="@+id/txtbWide"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:textColor="#000000"
                    android:textSize="12dp"
                    android:text="W-,"/>
                <TextView
                    android:id="@+id/txtbNb"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:textColor="#000000"
                    android:textSize="12dp"
                    android:text="Nb-,"/>

                <TextView
                    android:id="@+id/txtbBye"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:textSize="12dp"
                    android:textColor="#000000"
                    android:text="B-,"/>

                <TextView
                    android:id="@+id/txtbLegBye"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:textSize="12dp"
                    android:textColor="#000000"
                    android:text="Lb-,"/>
            </LinearLayout>

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="50dp"
                android:layout_weight="2"
                android:layout_marginRight="5dp"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/txtbTotal"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="right"
                    android:textSize="13dp"
                    android:textColor="#000000"
                    android:text="Total:"/>
                <TextView
                    android:id="@+id/txtbRR"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="right"
                    android:textSize="13dp"
                    android:textColor="#000000"
                    android:text="RR:"/>
            </LinearLayout>
        </LinearLayout>
        <View
            android:layout_width="fill_parent"
            android:layout_height="2dp"
            android:background="#80CBC4"></View>
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="45dp"
            android:layout_marginLeft="5dp"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/txtyetBat"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:textColor="#000000"
                android:textSize="12dp"
                android:text="What is you rname"/>
        </LinearLayout>
        <ListView
            android:id="@+id/listBowling"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:divider="@null">
        </ListView>

        <ListView
            android:id="@+id/listFallofWickets"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:divider="@null">
        </ListView>
    </LinearLayout>
</ScrollView>

這是我的OneFragment.java,它會在布局上方充氣並設置適配器類的值。

package com.domore.tabfinaldemo;

import android.app.ProgressDialog;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import Adapter.FirstBowlingAdapter;
import Adapter.FullScoreAdapter;
import Adapter.WicketAdapter;


public class OneFragment extends Fragment {

    View rootView;

    ListView lst,lstBowling,lstWicket;
    FullScoreAdapter adapter=null;
    FirstBowlingAdapter adapter_bowlilng=null;
    WicketAdapter wicketAdapter=null;

    ArrayList<String> p_name=null;
    ArrayList<JSONObject> p_key=null;
    ArrayList<JSONObject> bowling_object=null;
    ArrayList<String> lstbowling=null;
    ArrayList<String> fall_wicket=null;
    ArrayList<String> player_key1=null;

    ArrayList<String> symmentric=null;
    ArrayList<String> union=null;
    ArrayList<String> intersection=null;
    ArrayList<String> p_name11=null;
    ArrayList<String> playing_11=null;


    View batting_header,bowling_header,wicket_header;

    TextView txtBattingtotal;
    String bat_order="";
    String[] parts;
    String[] score;

    Typeface tf;
    String jsonStr="";

    String target="";
    String wicket="";
    String[] inn_value;
    String topScore="";
    String inning_name="";
    String team_name="";
    String yetBat="";
    String strextras="",strwide="",strnb="",strbye="",strlb="",strtotal="",strRR="";

    JSONArray team_value;
    JSONObject teamobject;

    TextView txtextras;
    TextView txtwide;
    TextView txtNb;
    TextView txtBye;
    TextView txtLb;
    TextView txtTotal;
    TextView txtRR;
    TextView txtyetBat;

    private static final String url="http://10.0.2.2/JSON/fullList.php";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        ScoreCard scoreCard=(ScoreCard)getActivity();

        bat_order=scoreCard.setInnings();
        topScore=scoreCard.setInningScore();

        rootView = inflater.inflate(R.layout.fragment_one, container, false);
        new JSONLoader().execute();

        txtextras=(TextView)rootView.findViewById(R.id.txtbExtras);
        txtwide=(TextView)rootView.findViewById(R.id.txtbWide);
        txtNb=(TextView)rootView.findViewById(R.id.txtbNb);
        txtBye=(TextView)rootView.findViewById(R.id.txtbBye);
        txtLb=(TextView)rootView.findViewById(R.id.txtbLegBye);
        txtTotal=(TextView)rootView.findViewById(R.id.txtbTotal);
        txtRR=(TextView)rootView.findViewById(R.id.txtbRR);
        txtyetBat=(TextView)rootView.findViewById(R.id.txtyetBat);

        tf=Typeface.createFromAsset(getActivity().getAssets(), "Roboto-Medium.ttf");
        lst=(ListView)rootView.findViewById(R.id.listview);

        batting_header=inflater.inflate(R.layout.batting_header, lst, false);

        txtBattingtotal=(TextView)batting_header.findViewById(R.id.txtBattingtotal);
        txtBattingtotal.setTypeface(tf);

        lstBowling=(ListView)rootView.findViewById(R.id.listBowling);
        bowling_header=inflater.inflate(R.layout.bowling_header,lstBowling,false);

        lstWicket=(ListView)rootView.findViewById(R.id.listFallofWickets);
        wicket_header=inflater.inflate(R.layout.wicket_header,lstWicket,false);

        return rootView;
    }

    public class JSONLoader extends AsyncTask<String, String, String> {

        private ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

//            dialog = new ProgressDialog(getActivity());
//            dialog.setMessage("Getting....");
//            dialog.setIndeterminate(false);
//            dialog.setCancelable(true);
//            dialog.show();
        }

        @Override
        protected String doInBackground(String... params) {

            ServiceHandler sh = new ServiceHandler();
            jsonStr = sh.makeServiceCall(url, ServiceHandler.POST);

            if (jsonStr != null) {
                try {

                    JSONObject mainObject = new JSONObject(jsonStr);

                    JSONObject dataObject = mainObject.getJSONObject("data");
                    JSONObject cardObject = dataObject.getJSONObject("card");

                    parts = bat_order.split("`");

                    JSONObject b_1 = new JSONObject(parts[0]);

                    //Get innings extras
                    strextras=b_1.getString("extras");
                    strwide=b_1.getString("wide");
                    strnb=b_1.getString("noball");
                    strbye=b_1.getString("bye");
                    strlb=b_1.getString("legbye");

                    strtotal=b_1.getString("runs");
                    strRR=b_1.getString("run_rate");

                    //Get innings extras completed

                    JSONArray batting_order = b_1.getJSONArray("batting_order");
                    p_name = new ArrayList<String>();
                    for (int i = 0; i < batting_order.length(); i++) {
                        p_name.add(batting_order.getString(i));
                    }

                    target = b_1.getString("runs");
                    wicket = b_1.getString("wickets");

                    JSONObject teams = cardObject.getJSONObject("teams");

                    score=topScore.split(",");
                    inning_name=score[0];
                    inn_value=inning_name.split("_");
                    team_value = teams.names();
                    for(int i=0;i<team_value.length();i++){
                        if(team_value.getString(i).equals(inn_value[0])){
                            teamobject=teams.getJSONObject(team_value.optString(i));
                        }
                    }
                    team_name=teamobject.getString("short_name");
                    JSONObject matchobject=teamobject.getJSONObject("match");

                    JSONArray playing_Xi=matchobject.getJSONArray("playing_xi");

                    playing_11=new ArrayList<>();
                    p_name11=new ArrayList<>();

                    p_name11.addAll(p_name);
                    for(int i=0;i<playing_Xi.length();i++){
                        playing_11.add(playing_Xi.getString(i));
                    }
                    union=new ArrayList<>(p_name11);
                    union.addAll(playing_11);

                    intersection=new ArrayList<>(p_name11);
                    intersection.retainAll(playing_11);

                    symmentric=new ArrayList<>(union);
                    symmentric.removeAll(intersection);

                    JSONObject players = cardObject.getJSONObject("players");

                    JSONArray player_arr = players.names();

                    JSONObject player_data = null;
                    ArrayList<String> player_key = new ArrayList<>();
                    for (int i = 0; i < player_arr.length(); i++) {
                        player_key.add(player_arr.getString(i));
                    }

                    p_key = new ArrayList<JSONObject>();

                    for (int i = 0; i < batting_order.length(); i++) {
                        for (int j = 0; j < player_arr.length(); j++) {
                            if (batting_order.getString(i).equals(player_arr.getString(j))) {
                                p_key.add(players.getJSONObject(player_arr.optString(j)));
                            }
                        }
                    }

                    //BOWLLING PART START
                    JSONArray bowling_arr = b_1.getJSONArray("bowling_order");

                    lstbowling = new ArrayList<String>();
                    for (int i = 0; i < bowling_arr.length(); i++) {
                        lstbowling.add(bowling_arr.getString(i));
                    }

                    JSONObject players1 = cardObject.getJSONObject("players");

                    JSONArray player_arr1 = players1.names();

                    player_key1 = new ArrayList<String>();
                    for (int i = 0; i < player_arr1.length(); i++) {
                        player_key1.add(player_arr1.getString(i));
                    }

                    bowling_object = new ArrayList<JSONObject>();
                    for (int i = 0; i < bowling_arr.length(); i++) {

                        for (int j = 0; j < player_arr.length(); j++) {
                            if (bowling_arr.getString(i).equals(player_arr1.getString(j))) {
                                bowling_object.add(players1.getJSONObject(player_arr1.optString(j)));
                            }
                        }
                    }

                    fall_wicket = new ArrayList<String>();
                    JSONArray fall_wicket_data = b_1.getJSONArray("fall_of_wickets");
                    for (int i = 0; i < fall_wicket_data.length(); i++) {
                        fall_wicket.add(fall_wicket_data.getString(i));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            else{
                Toast.makeText(getContext(), "There is no Data!!", Toast.LENGTH_SHORT).show();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
//            if (dialog.isShowing())
//                dialog.dismiss();

            txtyetBat.setText("Yet to bat:"+symmentric);
            txtBattingtotal.setText(team_name + "-" + target + "/" + wicket);
            txtextras.setText("Extras("+strextras+"):");
            txtwide.setText("W-"+strwide+",");
            txtNb.setText("Nb-"+strnb+",");
            txtBye.setText("B-"+strbye+",");
            txtLb.setText("Lb-"+strlb+",");
            txtTotal.setText("Total:"+strtotal+"/"+wicket);
            txtRR.setText("RR-"+strRR);

            lst.addHeaderView(batting_header, null, false);
            adapter=new FullScoreAdapter(getContext(),p_name,p_key);
            lst.setAdapter(adapter);
            Helper.getListViewSize(lst);

            lstBowling.addHeaderView(bowling_header, null, false);
            adapter_bowlilng=new FirstBowlingAdapter(getContext(),lstbowling,bowling_object);
            lstBowling.setAdapter(adapter_bowlilng);
            Helper.getListViewSize(lstBowling);

            lstWicket.addHeaderView(wicket_header, null, false);
            wicketAdapter=new WicketAdapter(getContext(),fall_wicket);
            lstWicket.setAdapter(wicketAdapter);
            Helper.getListViewSize(lstWicket);
        }
    }
}

請幫助我解決問題,以便我可以獲取特定時間間隔的更新數據。

您可以使用廣播接收器ACTION_TIME_TICK。這將每分鍾執行一次。

/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      hourText=(TextView)findViewById(R.id.hourText);
      minuteText=(TextView)findViewById(R.id.minuteText);


      //Create a broadcast receiver that will fire every minute
      tickReceiver=new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
        if(intent.getAction().compareTo(Intent.ACTION_TIME_TICK)==0)
        {
           //you can call webservice here to retrive new data
        }

        }
      };

      //Register the broadcast receiver to receive TIME_TICK
      registerReceiver(tickReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));

    }

    @Override
    public void onStop()
    {
      super.onStop();
      //unregister broadcast receiver.
      if(tickReceiver!=null)
      unregisterReceiver(tickReceiver);
    }

注意:請記住要調用方法“ unregisterReceiver”,否則您的應用程序將引發如下異常:

“Activity has leaked IntentReceiver that was originally registered here. Are you missing a call to unregisterReceiver()?”

然后在onPostExecute方法中寫下以下代碼,以檢查adaper是否為null;如果為null,則只需創建一個新實例;否則,只需提供一個新數據集,只需調用notifyDataSetChanged()即可更新UI。

if(youradapter == null)
 {
    youradapter = new CustomAdapter(this, yourList);
    listview.setAdapter(youradapter);

 }else{

     youradapter.setListArray(yourList); //<- provide a new data every minute here
     youradapter.notifyDataSetChanged();//<- this will update your UI with new data
  }

警告:每分鍾這樣做會耗盡電池電量。建議實施拉動刷新機制。 您可以在此處了解更多信息: http : //androidsrc.net/android-pull-refresh-view-using-swiperefreshlayout/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM