Android屏幕冻结,同时保存到数据库

时间:2013-04-18 02:56:39

标签: android

以下是我从网上下载数据的编码,在执行后我将其保存到数据库,然后更新ListAdapter for GUI。

问题是当保存到数据库时,屏幕会冻结它保存在数据库中的时间,对于600条记录,它约为20秒。

请告诉我,如何更改此内容,以便UI不会冻结。

private class DownloadWebPageTask extends AsyncTask<String, Void, String> {

    public DownloadWebPageTask() {

    }

    @Override
    protected void onPreExecute() {

        super.onPreExecute();



            progressDialog = ProgressDialog.show(getActivity(),

            "Please wait...", "Retrieving data ...", true);

            progressDialog.setCancelable(true);


            }

        }



    }

    @Override
    protected String doInBackground(String... urls) {

        String response = "";

        for (String url : urls) {

            DefaultHttpClient client = new DefaultHttpClient();

            HttpGet httpGet = new HttpGet(url);

            try {

                InputStream content = client.execute(httpGet).getEntity()

                .getContent();

                BufferedReader buffer = new BufferedReader(

                new InputStreamReader(content));

                String s = "";

                while ((s = buffer.readLine()) != null) {

                    response += s;

                }

            } catch (Exception e) {

                e.printStackTrace();

            }

        }

        return response;

    }

    @SuppressLint("NewApi")
    @Override
    protected void onPostExecute(String result) {


        try {



            if (type.equalsIgnoreCase("ALL COURSES")) {
                dbList = db.getAllCourseDBs(type);

                if (dbList.isEmpty())

                {
                progressDialog.dismiss();


                }






            if((result==null)|| result.isEmpty())
            {

            }
            else
            {
                if (type.equalsIgnoreCase("ALL COURSES")) {
                    db.deleteAllCourseByTypeDB(type);
                }
                else
                {
                    db.deleteAllCourseByCategoryIdDB(category_id);

                }



            JSONArray jArray = new JSONArray(result);
            for (int i = 0; i < jArray.length(); i++)
            {
                JSONObject json_data_one = jArray.getJSONObject(i);


                db.deleteAllCourseCategoryByTypeDB(type);


                for (int j = 0; i < jArray.length(); i++)

                {

                    CourseDB nbnt = new CourseDB();


                    long insideStart = System.currentTimeMillis();

                    JSONObject json_data = jArray.getJSONObject(i);
                    String crsCd=null, crsTitle=null;
                    if (type.equalsIgnoreCase("Area of Training")) {




                            crsCd = json_data.getString("courseCd");

                         crsTitle = json_data.getString("courseTitle");



                    }
                    else{


                    crsCd = (json_data.getString("crsCd"));


                     crsTitle = (json_data.getString("crsTitle"));
                    }



                    nbnt.setcourse_crs(crsCd);

                    nbnt.setcategory_course_type(type);

                    nbnt.setcourse_name(crsTitle);
                    nbnt.setcat_foreign_id(category_id);


                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
                    String currentDateandTime = sdf.format(new Date());
                    System.out.println("date to be inseted in DB"+currentDateandTime);
                    nbnt.setcourse_time(currentDateandTime);
                    arrayofWebData.add(nbnt);
                    db.beginTransaction();

                    SQLiteDatabase sqlDB = db.getWritableDatabase();


                    long startTime = System.currentTimeMillis();
                    db.addcourseByType(nbnt, sqlDB);
                    db.setTransactionSuccessful();

                    db.endTransaction();

                    db.close();

                    long endTime = System.currentTimeMillis();



                    readWebpagerating();
                     Collections.sort(arrayofWebData, new CourseDBComparator ());
                    listAdapter = new SelectArralAdapter(getActivity(),
                                arrayofWebData);

                        lv123.setAdapter(listAdapter);
                        lv123.setFastScrollEnabled(true);


                lv123.setOnItemClickListener(new OnItemClickListener() {

                    public void onItemClick(AdapterView<?> parent, View view,

                    int position, long id) {

                        CourseDB planet = listAdapter.getItem(position);


                        String key = planet.getcourse_crs();

                        String KEY_ID_NOTEBOOK = db.CourseDB(key);

                        System.out.println("value if key_id" + KEY_ID_NOTEBOOK);


                        Intent intent25 = new Intent(getActivity(),


                        CourseDetailsActivity.class);
                        intent25.putExtra("course_id", key);

                        intent25.putExtra("category_id", category_id);
                        intent25.putExtra("type", type);

                        intent25.putExtra("category_name", category_name);

                        startActivity(intent25);
                        getActivity().finish();

                    }

                });



            }
            }
        }
        }




    catch (JSONException e) {

            Log.e("log tag", "Error parsing data" + e.toString());

        }

    }

}

将代码更改为建议,屏幕现在不冻结,但是如果我移动到另一个屏幕,它会在帖子执行时崩溃。

private class DownloadWebPageTask extends AsyncTask<String, Void, String> {

    public DownloadWebPageTask() {

    }

    @Override
    protected void onPreExecute() {

        super.onPreExecute();

        if (type.equalsIgnoreCase("ALL COURSES")) {
        dbList = db.getAllCourseDBs(type);
        if (dbList.isEmpty())

        {

            progressDialog = ProgressDialog.show(getActivity(),

            "Please wait...", "Retrieving data ...", true);

            progressDialog.setCancelable(true);

        }
        }else if(type.equalsIgnoreCase("SEARCH")){
            // DO NOTHING
        }
        else
        {
            dbList = db.getAllCourseDBByTypes(category_id, type);
            if (dbList.isEmpty())

            {

                System.out.println("the value of the dbList inside all coursestypes"+dbList.size());
                progressDialog = ProgressDialog.show(getActivity(),

                "Please wait...", "Retrieving data ...", true);

                progressDialog.setCancelable(true);

            }

        }



    }

    @Override
    protected String doInBackground(String... urls) {

        String response = "";

        for (String url : urls) {

            DefaultHttpClient client = new DefaultHttpClient();

            HttpGet httpGet = new HttpGet(url);

            try {

                InputStream content = client.execute(httpGet).getEntity()

                .getContent();

                BufferedReader buffer = new BufferedReader(

                new InputStreamReader(content));

                String s = "";

                while ((s = buffer.readLine()) != null) {

                    response += s;

                }

            } catch (Exception e) {

                e.printStackTrace();

            }


            System.out.println("value of the response"+response);









            //adding new */


            if((response==null)|| response.isEmpty())
            {

            }
            else
            {
                if (type.equalsIgnoreCase("ALL COURSES")) {
                    db.deleteAllCourseByTypeDB(type);
                }else if(type.equalsIgnoreCase("SEARCH")){
                    // DO NOTHING
                }
                else
                {
                    db.deleteAllCourseByCategoryIdDB(category_id);

                }



            JSONArray jArray;
            try {
                jArray = new JSONArray(response);

            for (int i = 0; i < jArray.length(); i++)
            {
                JSONObject json_data_one = jArray.getJSONObject(i);


                System.out.println("All the not empty");

                db.deleteAllCourseCategoryByTypeDB(type);





                for (int j = 0; i < jArray.length(); i++)

                {

                    CourseDB nbnt = new CourseDB();


                    long insideStart = System.currentTimeMillis();

                    JSONObject json_data = jArray.getJSONObject(i);
                    String crsCd=null, crsTitle=null;
                    if (type.equalsIgnoreCase("Area of Training")) {
                        System.out.println("im area of tarinin");



                            crsCd = json_data.getString("courseCd");

                         crsTitle = json_data.getString("courseTitle");



                    }
                    else{


                    crsCd = (json_data.getString("crsCd"));


                     crsTitle = (json_data.getString("crsTitle"));
                    }

                    System.out.println("Time for one JSON parsing "

                    + (System.currentTimeMillis() - insideStart));

                    nbnt.setcourse_crs(crsCd);

                    nbnt.setcategory_course_type(type);

                    nbnt.setcourse_name(crsTitle);
                    nbnt.setcat_foreign_id(category_id);


                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
                    String currentDateandTime = sdf.format(new Date());
                    System.out.println("date to be inseted in DB"+currentDateandTime);
                    nbnt.setcourse_time(currentDateandTime);
                    arrayofWebData.add(nbnt);
                    db.beginTransaction();

                    SQLiteDatabase sqlDB = db.getWritableDatabase();


                    long startTime = System.currentTimeMillis();
                    db.addcourseByType(nbnt, sqlDB);
                    db.setTransactionSuccessful();

                    db.endTransaction();

                    db.close();



            }
            }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }


        }

        return response;

    }

    @SuppressLint("NewApi")
    @Override
    protected void onPostExecute(String result) {


        if (type.equalsIgnoreCase("ALL COURSES")) {
            dbList = db.getAllCourseDBs(type);

            if (dbList.isEmpty())

            {
            progressDialog.dismiss();


            }
            }else if(type.equalsIgnoreCase("SEARCH")){
                // DO NOTHING
            }
            else
            {
                dbList = db.getAllCourseDBByTypes(category_id, type);

                if (dbList.isEmpty())

                {

                    System.out.println("the value of the dbList inside all coursestypes"+dbList.size());
                    progressDialog.dismiss();

                }

            }



                readWebpagerating();
                 Collections.sort(arrayofWebData, new CourseDBComparator ());
                listAdapter = new SelectArralAdapter(getActivity(),
                            arrayofWebData);

                    lv123.setAdapter(listAdapter);
                    lv123.setFastScrollEnabled(true);


            lv123.setOnItemClickListener(new OnItemClickListener() {

                public void onItemClick(AdapterView<?> parent, View view,

                int position, long id) {

                    CourseDB planet = listAdapter.getItem(position);


                    String key = planet.getcourse_crs();

                    String KEY_ID_NOTEBOOK = db.CourseDB(key);

                    System.out.println("value if key_id" + KEY_ID_NOTEBOOK);

                    System.out.println("category id on lcick listnere inside the post ecexute" + category_id);

                    Intent intent25 = new Intent(getActivity(),


                    CourseDetailsActivity.class);
                    intent25.putExtra("course_id", key);

                    intent25.putExtra("category_id", category_id);
                    intent25.putExtra("type", type);

                    intent25.putExtra("category_name", category_name);

                    startActivity(intent25);
                    getActivity().finish();

                }

            });

    }

}

2 个答案:

答案 0 :(得分:2)

数据库操作应该在doInBackground()

中完成

答案 1 :(得分:0)

就像LuxuryMode所说,所有阻止操作都需要在后台进行。

您的方法存在的问题是,您将所有这些都放在Activity中,其生命周期不适合后台操作。

创建位于外部的应用程序模型(通常在Application子类中)并在那里移动AsyncTask。在活动中使用简单模式(如observer / callback)绑定到该模型以更新适配器。