我正在尝试使用JSON解析在Android Studio中解析我的数据库中的一些值。我想使用AsyncTask并在BackgroundThread上运行它,因为它似乎要在主线程上运行太多。
我在一个地图活动中使用我的数据库中的数据,使用谷歌地图放置标记(可能是相关的)。
问题是,即使我正在尝试使用AsyncTask (我还是一个安卓新手),它仍然在控制台上告诉我:
I/Choreographer: Skipped 33 frames! The application may be doing too much work on its main thread. 下面是我的AsyncTask代码:
public class GetMarkers extends AsyncTask<String, Void, String> {
private ProgressDialog pDialog;
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllMarkersActivity.this);
pDialog.setMessage("Loading markers...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
Response.Listener<String> responseListener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
Iterator<String> keys = jsonObject.keys();
while( keys.hasNext() )
{
String key = keys.next();
if(!key.equals("success")){ // or use this if your keys are always in digits form.. if(TextUtils.isDigitsOnly(key))
Log.v("category key", key);
JSONObject innerJObject = jsonObject.getJSONObject(key);
String lat_str = innerJObject.getString("lat");
double lat = 0.0, lng = 0.0;
if(!TextUtils.isEmpty(lat_str) && TextUtils.isDigitsOnly(lat_str))
lat = Double.parseDouble(lat_str);
String lng_str = innerJObject.getString("lng");
if(!TextUtils.isEmpty(lng_str) && TextUtils.isDigitsOnly(lng_str))
lng = Double.parseDouble(lng_str);
LatLng Mplace = new LatLng(lat, lng);
MarkerOptions marker = new MarkerOptions().position(Mplace).title("Marker").snippet("Snippet:" + "0");
mMap.addMarker(marker);
}
}
} catch (JSONException e) {
e.printStackTrace();
Log.i("RESPONSE:", "[" + response + "]");
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
};
MarkerRequest markerRequest = new MarkerRequest(responseListener);
RequestQueue queue = Volley.newRequestQueue(AllMarkersActivity.this);
queue.add(markerRequest);
}
});
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}然后,当我想要执行时,我只需使用:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
new GetMarkers().execute();然而,由于某些原因,当我打开我的mapsactivity时,进度对话框从未出现,它给出了33个跳过的帧“错误”。
任何帮助都是非常感谢的!
请举个例子回答,还在学习!:)
谢谢!
发布于 2016-09-07 02:37:54
摆脱runOnUiThread(new Runnable() {
这里doInBackground的要点是这样它就不会在UI线程上运行。
您的UI内容应该在onPostExecute中进行
从技术上讲,既然您使用的是Response.Listener<String> responseListener,就不应该需要在AsyncTask中运行它
public void onResponse的行为类似于onPostExecute
https://stackoverflow.com/questions/39355536
复制相似问题