我正在Android中构建一个应用程序,其中第一个活动执行 Rest api 调用并在屏幕上显示结果。
要进行网络服务电话,我可以使用 asynctask 或加载程序或处理程序。服务不是一个好选择,因为它不是一个长期运行的操作,它与活动生命周期有关。
我可以使用volley和robospice之类的库。但是,在使用这些库之前,我想知道有效的方法。
使用什么 aysncTask ?如果由于屏幕方向重新启动等问题而不推荐使用。那么,何时应该使用?
或者装载机是最好的方法,因为它会处理所有问题?
我是新手。
任何建议都将不胜感激。
答案 0 :(得分:0)
了解Google SyncFramework。
有了它,您可以使用Volley进行数据提取,在片段/活动中,您可以使用Cursor with Loaders进行数据刷新/获取。
答案 1 :(得分:0)
void IncomeJsonData(String json) {
try {
//JSONObject jsonObject = new JSONObject(json);
JSONArray array = new JSONArray(json);
for (int i = 0; i < array.length(); i++)
{
JSONObject obj = array.getJSONObject(i);
Income income = new Income();
income.setId_id(obj.getInt("Id_id"));
income.setIn_addamount(obj.getDouble("In_addamount"));
income.setIn_amtdate(obj.getString("In_amtdate"));
income.setIn_amtcat(obj.getString("In_amtcat"));
income.setIn_mode(obj.getString("In_mode"));
income.setIn_description(obj.getString("In_description"));
income.setIn_active(obj.getBoolean("In_active"));
Log.e("BAVO", income.toString());
income_list.add(income);
}
Log.e("C", income_list.toString());
custom_class = new Custom_class(ViewIncomeActivity.this, income_list);
lst_income.setAdapter(custom_class);
//lst_income.setBackgroundResource(R.color.colorPrimaryDark);
} catch (Exception ex) {
Log.e("Show_Error", ex.toString());
ex.printStackTrace();
}
}
class ConsumeIncomeWebservice extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
String jsonString = new String();
HttpURLConnection urlConnection = null;
URL url = null;
try {
String url1 = "http://192.168.43.126/Android_webservices/Pocket_expence.svc/GetAllIncome";
URI uri = new URI(url1);
url = new URL(uri.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
//urlConnection.getResponseCode("GET");
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setDoOutput(true);
urlConnection.connect();
Log.e("Error_error", "Hal Ne bhai");
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
char[] buffer = new char[1024];
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
jsonString = sb.toString();
Log.d("", "doInBackground: " + jsonString);
}
catch (Exception e) {
Log.d("Error", e.toString());
}
return jsonString;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("Post_Exe", "PostExe");
if (s != null && !s.equals("")) {
IncomeJsonData(s);
} else {
Log.e("JSON_amit", "NOT AVAILABLE");
}
}
}