自动刷新json php android

时间:2015-12-24 18:45:42

标签: php android json

我需要一些帮助。我需要每隔1秒从json php刷新我的结果到没有任何按钮或刷卡的Android应用程序刷新,这里我的代码:

/**
 * Created by no name on 12/24/2015.
 */
public class MainActivity extends Activity{
    /** Called when the activity is first created. */

    private static String url = "http://192.168.1.103/index.php";
    String p_id, value;
    TextView tv1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new JSONParse().execute();
    }

    private class JSONParse extends AsyncTask<String, String, JSONObject> {
        private ProgressDialog pDialog;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            tv1 = (TextView) findViewById(R.id.textView1);

            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Loading Data ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
            tv1.setText("Getting Values Pls wait..");
        }

        @Override
        protected JSONObject doInBackground(String... args) {
            JsonParser jParser = new JsonParser();
// Getting JSON from URL
            JSONObject json = jParser.getJSONFromUrl(url);
            return json;
        }

        @Override
        protected void onPostExecute(JSONObject json) {
            try {
                pDialog.dismiss();
                p_id = json.getString("pid");
                value = json.getString("value");
                tv1.setText(p_id + value + "(Candela)");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }

}

我可以刷新一些textView吗?

CMIW,谢谢之前:D

1 个答案:

答案 0 :(得分:0)

您可以使用TimerTask类:

final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask task = new TimerTask() {       
     @Override
     public void run() {
       handler.post(new Runnable() {
          public void run() {  
             new JSONParse().execute();
          }
        });
      }
};
timer.schedule(task, 0, 1000);