0
我掙扎着一個嚴重的問題Android的Web服務調用每秒
我想調用異步函數返回我JSON對象和更新我的UI (如果必要)每秒喜歡的setInterval。
一個電話我成功(以下工作100%的代碼) 但我想,它是每秒執行一次
我附上我的活動類和asyncRequest類
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;
}
}
,我的主要活動
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;
}
}
將不勝感激幫助 感謝
請解釋你面臨什麼問題,並分享日誌萬一你面臨任何錯誤 – AnswerDroid