我正在尝试从我的网络服务器中提取数据并使用服务将它们添加到后台的本地数据库中。数据存储到本地数据库时没有任何问题但是当发生这种情况时手机变得很慢(有一些拖动) 。只是想知道我是否在写入DB时正确地做了事情,或者是否有更好更快的方法。
我正在使用AsyncHttpClient库从网络服务器提取数据。
final RequestParams requestParams = new RequestParams();
final String uploadWebsite = url_acc_details;
AsyncHttpClient client = new AsyncHttpClient();
client.post(uploadWebsite, requestParams, new JsonHttpResponseHandler()
{
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response)
{
try
{
success = response.getInt(TAG_SUCCESS);
if (success == Integer.parseInt(getResources().getString(R.string.successvalue)))
{
details = response.getJSONArray(TAG_DETAIL);
for (int i = 0; i < details.length(); i++)
{
JSONObject c = details.getJSONObject(i);
acc_iD = c.getString(TAG_ACC_ID);
acc_nAme = c.getString(TAG_ACC_NAME);
acc_Image = c.getString(TAG_ACC_IMAGE);
acc_active = c.getString(TAG_ACC_ACTIVE);
acc_priority = c.getString(TAG_ACC_PRIORITY);
acc_creator = c.getString(TAG_ACC_CREATOR);
dblocal.setAccDetails(Integer.valueOf(acc_iD), acc_nAme, acc_Image, acc_active, acc_priority, acc_creator);
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
stopSelf();
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse)
{
super.onFailure(statusCode, headers, throwable, errorResponse);
stopSelf();
}
});
同样地,我在同一时间以相同的逻辑开始在bankground中运行三个服务,但是获取不同的细节。
如果有人能让我知道如何更快更好地完成上述过程,那会很棒吗?
答案 0 :(得分:0)
首先,您应该为AsyncHttpClient使用Singleton模式。这样,您就不必为每个请求重新定义新资源。
public class MyAsyncHttpClient extends AsyncHttpClient {
private static MyAsyncHttpClient client;
private MyAsyncHttpClient() {
}
public static MyAsyncHttpClient getClient() {
if (client == null) {
client = new MyAsyncHttpClient();
// do whatever, setCookieStore, addHeader, etc
}
return client;
}
}
然后在你的asyncTask
中替换new AsyncHttpClient()
MyAsyncHttpClient.getClient()
其次,也要在后台进行数据库操作。 声明一个接口:
public interface DatabaseOperationListener {
public void perform();
public void onFinish();
}
...
client.post(uploadWebsite, requestParams, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response)
{
new DatabaseTask(new DatabaseOperationListener() {
@Override
public void perform() {
DatabaseManager dblocal = DatabaseManager.getInstance();
dblocal.setAccDetails(Integer.valueOf(acc_iD), acc_nAme, acc_Image, acc_active, acc_priority, acc_creator);
}
@Override
public void onFinish() {
// do something, perform another request, etc
}
}).execute();
@Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable error) {
super.onFailure(statusCode, headers, errorResponse, error);
// do something
}
});
请注意,我还有一个数据库的Singleton实例。