【发布时间】:2014-09-01 13:01:51
【问题描述】:
我正在编写一个 Android 应用程序,它偶尔需要下载一个大约 1MB 并包含大约 1000 个元素的 json 字符串,并将每个元素解析到一个 SQLite 数据库中,我用它来填充 ListActivity。
即使下载和解析不是每次与应用交互时都需要完成的事情(仅在首次运行或用户选择刷新数据时),我仍然担心解析部分是耗时太长,大约两到三分钟 - 从手机应用程序的角度来看,这似乎是永恒的!
我正在使用此代码... :-
public class CustomerAsyncTask extends AsyncTask<String, Integer, String> {
private Context context;
private String url_string;
private String usedMethod;
private String identifier;
List<NameValuePair> parameter;
private boolean runInBackground;
AsynTaskListener listener;
private Bitmap bm = null;
public ProgressDialog pDialog;
public String entityUtil;
int index = 0;
public static int retry = 0;
private String jsonString = "";
private String DialogString = "";
// use for AsyncTask web services-----------------
public CustomerAsyncTask(Context ctx, String url, String usedMethod,
String identifier, boolean runInBackground, String DialogString,
List<NameValuePair> parameter, AsynTaskListener callack) {
this.context = ctx;
this.url_string = url;
this.usedMethod = usedMethod;
this.identifier = identifier;
this.parameter = parameter;
this.runInBackground = runInBackground;
this.listener = callack;
this.DialogString = DialogString;
}
public CustomerAsyncTask(Context ctx, String url, String usedMethod,
String identifier, boolean runInBackground,
List<NameValuePair> parameter, AsynTaskListener callack, Bitmap bm) {
this.context = ctx;
this.url_string = url;
this.usedMethod = usedMethod;
this.identifier = identifier;
this.parameter = parameter;
this.runInBackground = runInBackground;
this.listener = callack;
this.bm = bm;
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (runInBackground)
initProgressDialog(DialogString);
}
@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
@SuppressWarnings("deprecation")
@Override
protected String doInBackground(String... params) {
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 10000; // mili second
HttpConnectionParams.setConnectionTimeout(httpParameters,
timeoutConnection);
int timeoutSocket = 10000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
try {
HttpResponse response = null;
if (usedMethod.equals(GlobalConst.POST)) {
HttpPost httppost = new HttpPost(this.url_string);
httppost.setHeader("Content-Type",
"application/x-www-form-urlencoded");
// Customer Login MObile
if (identifier.equals("Customer_Login")) {
if (params.length > 0) {
parameter = new ArrayList<NameValuePair>();
parameter.add(new BasicNameValuePair("cus_mob",
params[0]));
}
httppost.setEntity(new UrlEncodedFormEntity(parameter));
// Customer Verify Code
} else if (identifier.equals("Customer_mob_verify")) {
if (params.length > 0) {
parameter = new ArrayList<NameValuePair>();
parameter.add(new BasicNameValuePair("cus_verify",
params[0]));
parameter.add(new BasicNameValuePair("cus_mobile",
params[1]));
}
httppost.setEntity(new UrlEncodedFormEntity(parameter));
} else if (identifier.equals("Dashboard")) {
if (params.length > 0) {
parameter = new ArrayList<NameValuePair>();
parameter.add(new BasicNameValuePair("cus_id",
params[0]));
}
httppost.setEntity(new UrlEncodedFormEntity(parameter));
}
response = (HttpResponse) httpClient.execute(httppost);
} else if (usedMethod.equals(GlobalConst.GET)) {
HttpGet httpput = new HttpGet(this.url_string);
httpput.setHeader("Content-Type",
"application/x-www-form-urlencoded");
response = (HttpResponse) httpClient.execute(httpput);
}
// Buffer Reader------------------------
InputStream inputStream = null;
String result = null;
try {
HttpEntity entity1 = response.getEntity();
inputStream = entity1.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
} finally {
try {
if (inputStream != null)
inputStream.close();
} catch (Exception squish) {
}
}
jsonString = result;
} catch (ClientProtocolException e) {
e.printStackTrace();
return AsyncResultConst.CONNEERROR;
} catch (IOException e) {
e.printStackTrace();
return AsyncResultConst.CONNEERROR;
} catch (Exception e1) {
e1.printStackTrace();
return AsyncResultConst.EXCEPTION;
} finally {
httpClient.getConnectionManager().shutdown();
}
return AsyncResultConst.SUCCESS;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
if (runInBackground)
pDialog.dismiss();
if (result.equals(AsyncResultConst.SUCCESS)) {
listener.onRecieveResult(identifier, jsonString);
} else if (result.equals(AsyncResultConst.PARSINGERROR)) {
// showAlertMessage(context, "Error", "Parsing Error", null);
listener.onRecieveException(identifier, result);
} else {
if (retry < 0) {
retry++;
new CustomerAsyncTask(context, url_string, usedMethod,
identifier, runInBackground, DialogString, parameter,
listener).execute("");
} else {
// showAlertMessage(context, "Error", "Connection Error", null);
listener.onRecieveException(identifier, result);
}
}
super.onPostExecute(result);
}
private void initProgressDialog(String loadingText) {
pDialog = new ProgressDialog(this.context);
pDialog.setMessage(loadingText);
pDialog.setCancelable(false);
pDialog.show();
}
}
【问题讨论】:
-
或许向我们展示您的解决方案。 3 分钟听起来不可能
-
如果您正在控制数据,您可能需要考虑分批下载,以便逐步填充数据库。
-
检查我更新的代码
-
使用 Traceview、日志语句等来确定准确您的问题出在哪里。另请注意,您的代码没有进行任何解析,因此如果您已经确定解析是您的问题,那么此代码将不会说明这一点。请记住,Google 不推荐使用 HttpClient。
-
你测量过服务器响应获取时间和json解析时间吗?与从服务器检索数据所需的时间相比,任何解析延迟都是微不足道的。从其他地方(例如在 Fiddler 中)获得响应需要多长时间如果服务器处理请求缓慢,则无济于事。 webservice 是否接受 OData 参数来拆分数据?要回答的问题太多了
标签: java android performance android-json