0

I struggled a serious problem

i want to call async function that return me json object and update my ui (If it necessary) every second like setInterval .

one call i succeeded(the code below work 100%) but I would like that it's execute every second

i attach my activity class and asyncRequest class

public class AsyncRequest extends AsyncTask<String, Integer, String> {

 OnAsyncRequestComplete caller;
 Context context;
 String method = "GET";
 List<NameValuePair> parameters = null;
 ProgressDialog pDialog = null;

 String label="";
 // Three Constructors
 public AsyncRequest(Activity a, String m, List<NameValuePair> p) {
  caller = (OnAsyncRequestComplete) a;
  context = a;
  method = m;
  parameters = p;
 }

 public AsyncRequest(Activity a, String m) {
  caller = (OnAsyncRequestComplete) a;
  context = a;
  method = m;
 }

 public AsyncRequest(Activity a) {
  caller = (OnAsyncRequestComplete) a;
  context = a;
 }

 public AsyncRequest(Activity a, String m, List<NameValuePair> p, String l)    {
      caller = (OnAsyncRequestComplete) a;
      context = a;
      method = m;
      parameters = p;
      label = l;
     }

 // Interface to be implemented by calling activity
 public interface OnAsyncRequestComplete {
  public void asyncResponse(String response);
 }

 public String doInBackground(String... urls) {
  // get url pointing to entry point of API
  String address = urls[0].toString();
  if (method == "POST") {
   return post(address);
  }

  if (method == "GET") {
   return get(address);
  }

  return null;
 }

 public void onPreExecute() {
  pDialog = new ProgressDialog(context);
  pDialog.setMessage("Loading data.."); // typically you will define such
            // strings in a remote file.
  pDialog.show();
 }

 public void onProgressUpdate(Integer... progress) {
  // you can implement some progressBar and update it in this record
  // setProgressPercent(progress[0]);
 }

 public void onPostExecute(String response) {
  if (pDialog != null && pDialog.isShowing()) {
   pDialog.dismiss();
  }
  caller.asyncResponse(response);
 }

 protected void onCancelled(String response) {
  if (pDialog != null && pDialog.isShowing()) {
   pDialog.dismiss();
  }
  caller.asyncResponse(response);
 }

 @SuppressWarnings("deprecation")
 private String get(String address) {
  try {

   if (parameters != null) {

    String query = "";
    String EQ = "="; String AMP = "&";
    for (NameValuePair param : parameters) {
     query += param.getName() + EQ + URLEncoder.encode(param.getValue()) + AMP;
    }

    if (query != "") {
     address += "?" + query;
    }
   }

   HttpClient client = new DefaultHttpClient();
   HttpGet get= new HttpGet(address);

   HttpResponse response = client.execute(get);
   return stringifyResponse(response);

  } catch (ClientProtocolException e) {
   // TODO Auto-generated catch block
  } catch (IOException e) {
   // TODO Auto-generated catch block
  }

  return null;
 }

 private String post(String address) {
  try {

   HttpClient client = new DefaultHttpClient();
   HttpPost post = new HttpPost(address);

   if (parameters != null) {
    post.setEntity(new UrlEncodedFormEntity(parameters));
   }

   HttpResponse response = client.execute(post);
   return stringifyResponse(response);

  } catch (ClientProtocolException e) {
   // TODO Auto-generated catch block
  } catch (IOException e) {
   // TODO Auto-generated catch block
  }

  return null;
 }

 private String stringifyResponse(HttpResponse response) {
  BufferedReader in;
  try {
   in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

   StringBuffer sb = new StringBuffer("");
   String line = "";
   while ((line = in.readLine()) != null) {
    sb.append(line);
   }
   in.close();

   return sb.toString();
  } catch (IllegalStateException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

  return null;
 }
}

and my main activity

    public class MainActivity extends Activity implements
    AsyncRequest.OnAsyncRequestComplete {

 TextView titlesView;
 String apiURL = "url that return json";
 ArrayList<NameValuePair> params;

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

  // TODO Auto-generated method stub
  titlesView = (TextView) findViewById(R.id.post_titles);
  params = getParams();
  AsyncRequest getPosts = new AsyncRequest(this, "GET", params);
  getPosts.execute(apiURL);
 }

 // override method from AsyncRequest.OnAsyncRequestComplete interface
 // the response can contain other parameters specifying if the request was
 // successful or not and other things
 // in a real world application various checks will be done on the response
 @Override
 public void asyncResponse(String response) {

  try {
   // create a JSON array from the response string
   //JSONArray objects = new JSONArray(response);

      JSONObject json = new JSONObject(response);

        String str = "";
        JSONArray articles = json.getJSONArray("GetTrainStationsResult");

   // define a string to hold out titles (in a real word application you will be using a ListView and an Adapter to do such listing)
   String titles = "";
   String NL = "\n";
   String DOT = ". ";
   for (int i = 0; i < articles.length(); i++) {
    JSONObject object = (JSONObject) articles.getJSONObject(i);
    titles += object.getString("Description") + DOT + object.getString("LocationLat") + NL;
   }
   titlesView.setText(titles);
  } catch (JSONException e) {
   e.printStackTrace();
  }
 }

 // here you specify and return a list of parameter/value pairs supported by
 // the API
 private ArrayList<NameValuePair> getParams() {
  // define and ArrayList whose elements are of type NameValuePair
  ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
  params.add(new BasicNameValuePair("start", "0"));
  params.add(new BasicNameValuePair("limit", "10"));
  params.add(new BasicNameValuePair("fields", "id,title"));
  return params;
 }

}

Would appreciate help Thanks

1 Answers1

0

AlarmManager can be the solution you are looking for. There is another question like yours so give a look here

Community
  • 1
  • 1
FrancescoAzzola
  • 2,666
  • 2
  • 15
  • 22