使用AsyncTask会使应用程序变慢

时间:2014-08-12 14:42:34

标签: android json parsing android-asynctask progress-bar

我有这个problem,你建议使用AsyncTask或Service。 所以现在我第一次使用AsyncTask类,我在其中添加用于下载和解析JSON文件的代码。这是代码:

public class HomePage extends Activity{
    private Database db = new Database(this);

    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.homepage);

        new DownloadDataFromServer().execute(new String[] { "http://www.example.com/data.json" });
    }

    protected void onDestroy() {
        super.onDestroy();
        db.close();
    }

    // Async Task Class
    private class DownloadDataFromServer extends AsyncTask<String, Integer, String> {
        ProgressDialog dialog;

        @Override
        protected void onCancelled() {
            super.onCancelled();
        }

        @Override
        protected void onPreExecute() {
            dialog = new ProgressDialog(HomePage.this);
            dialog.setIndeterminate(false);
            dialog.setMax(100);
            dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            dialog.setCancelable(true);
            dialog.setTitle("Download JSON");
            dialog.setMessage("Please wait..");
            dialog.show();

            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... urls) {
            int count = 0;
            int lenghtOfFile = 0;

            // JSON DOWNLOADING AND PARSING
            SQLiteDatabase dbr = db.getReadableDatabase();

            try {
                StrictMode.ThreadPolicy policy= new StrictMode.ThreadPolicy.Builder().permitAll().build();
                StrictMode.setThreadPolicy(policy);

                HttpClient client = new DefaultHttpClient();
                HttpGet request = new HttpGet(urls[0]);
                request.addHeader("Cache-Control", "no-cache");
                long id = -1;

                HttpResponse response = client.execute(request);
                HttpEntity entity = response.getEntity();
                InputStreamReader in = new InputStreamReader(entity.getContent());
                BufferedReader reader = new BufferedReader(in);
                StringBuilder stringBuilder = new StringBuilder();
                String line = "";

                while ((line=reader.readLine()) != null) {
                    stringBuilder.append(line);
                }

                JSONArray jsonArray = new JSONArray(stringBuilder.toString());
                SQLiteDatabase dbWrite = db.getWritableDatabase();
                ContentValues values = new ContentValues();
                dbr.delete("users", "1", null);

                long total = 0;
                lenghtOfFile = jsonArray.length();

                for (int i = 0; i < lenghtOfFile; i++) {
                    JSONObject jObj = (JSONObject) jsonArray.getJSONObject(i);

                    values.put("_id", jObj.optString("id").toString());
                    values.put("city", jObj.optString("city").toString());
                    values.put("name",jObj.optString("name").toString());

                    id = dbWrite.insert("users", null, values);

                    count++;
                    total += count;
                    onProgressUpdate((int) ((total * 100) / lenghtOfFile));
                }           
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return lenghtOfFile+"";
        }

        protected void onProgressUpdate(Integer... progress) {
            dialog.setProgress(progress[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            if (Integer.parseInt(result) < 0) {
                Toast.makeText(getBaseContext(), "Failed!", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getBaseContext(), result + " users", Toast.LENGTH_SHORT).show();
            }
            dialog.dismiss();
        }
    }
}

需要很长时间才能达到100%,差不多1分钟! 除了进度条暂停0%一段时间,然后它只显示100%。 可能是什么问题?

2 个答案:

答案 0 :(得分:2)

这是因为每个insert()在DB中创建自己的事务。您必须在一个事务中包装所有insert()个调用,如下所示:

 dbWrite.beginTransaction();
        try {
           //put all insert() here
            dbWrite.setTransactionSuccessful();

        }catch {
            //Error in between database transaction 
        }finally {
                dbWrite.endTransaction();

        }
祝你好运! :)

此外,您应该使用publishPorgress方法更新ProgressDialog而不是直接调用onProgressUpdate

答案 1 :(得分:1)

要更新AsyncTask的进度,您应该调用publishProgress方法。 请勿直接致电onPublishProgress

相关问题