当将大量数据插入sqlite时,我的UI变慢了

时间:2017-05-11 10:40:32

标签: java android sqlite android-sqlite

在我的应用程序中,我正在从web加载批量数据并将其插入到sqlite表中,当我将数据存储到sqlite表中时,我的App UI变慢并显示ANR对话框, 下面是我从web加载数据的代码,并插入到sqlite表

StringRequest request = new StringRequest(url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONArray array = new JSONArray(response);
                        if (array.length() != 0) {
                            for (int i = 0; i < array.length(); i++) {
                                JSONObject object = array.getJSONObject(i);
                                AirportModel model = new AirportModel();

                                String cityName = object.getString("airport_city_name");
                                String cityCode = object.getString("airport_city_code");
                                String country = object.getString("airport_country_name");
                                String name = object.getString("airport_name");

                                dbHelper.insertAiports(cityName, cityCode, name, country);
                            }
                        }
                        Toast.makeText(getApplicationContext(), String.valueOf(array.length()), Toast.LENGTH_SHORT).show();

                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(getApplicationContext(), "Founded JSON Exception", Toast.LENGTH_SHORT).show();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(FlightSearchActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
            RequestQueue queue = Volley.newRequestQueue(FlightSearchActivity.this);
            queue.add(request);

这是我的代码,用于将数据插入到sqlite表

public void insertAiports(String airportCityName, String aiportCityCode, String airportName, String airportConutryName) {

            SQLiteDatabase database = getWritableDatabase();

            ContentValues values = new ContentValues();
            values.put(AIRPORT_FIELD_CITY_NAME, airportCityName);
            values.put(AIRPORT_FIELD_CITY_CODE, aiportCityCode);
            values.put(AIRPORT_FIELD_NAME, airportName);
            values.put(AIRPORT_FIELD_COUNTRY_NAME, airportConutryName);

            database.insert(TABLE_AIRPORTS, null, values);
        }

运行此代码时,我的应用程序UI变慢并显示对话框&#34;应用程序没有响应  你想要关闭吗?&#34; 任何人都可以建议在不挂起我的UI的情况下将批量数据插入sqlite表。

4 个答案:

答案 0 :(得分:1)

如果您在db中进行批量操作,请使用事务以获得更好的性能。

例如:

   db.beginTransaction();

    try { 
        // do your bulk insert
        db.setTransactionSuccessful();
    } finally { 
        db.endTransaction();
    } 

答案 1 :(得分:0)

您应该使用AsyncTask在后台执行批量处理,而不是在主线程(UI线程)中。

https://developer.android.com/reference/android/os/AsyncTask.html

答案 2 :(得分:0)

在单独的线程上执行数据库操作,因为它需要时间。你可以使用:

1.AsyncTask
2.Service

答案 3 :(得分:0)

使用AsyncTask获取其下的json数据并将数据添加到sqlite, 看看它的演示:

public class MainActivity extends AppCompatActivity {
    private Button button;
    private EditText time;
    private TextView finalResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        time = (EditText) findViewById(R.id.in_time);
        button = (Button) findViewById(R.id.btn_run);
        finalResult = (TextView) findViewById(R.id.tv_result);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AsyncTaskRunner runner = new AsyncTaskRunner();
                String sleepTime = time.getText().toString();
                runner .execute(sleepTime);
            }
        });
    }

    private class AsyncTaskRunner extends AsyncTask<String, String, String> {

        private String resp;
        ProgressDialog progressDialog;

        @Override
        protected String doInBackground(String... params) {
            publishProgress("Sleeping..."); // Calls onProgressUpdate()
            try {
                int time = Integer.parseInt(params[0])*1000;

                Thread.sleep(time);
                resp = "Slept for " + params[0] + " seconds";
            } catch (InterruptedException e) {
                e.printStackTrace();
                resp = e.getMessage();
            } catch (Exception e) {
                e.printStackTrace();
                resp = e.getMessage();
            }
            return resp;
        }


        @Override
        protected void onPostExecute(String result) {
            // execution of result of Long time consuming operation
            progressDialog.dismiss();
            finalResult.setText(result);
        }


        @Override
        protected void onPreExecute() {
            progressDialog = ProgressDialog.show(MainActivity.this,
                    "ProgressDialog",
                    "Wait for "+time.getText().toString()+ " seconds");
        }


        @Override
        protected void onProgressUpdate(String... text) {
            finalResult.setText(text[0]);

        }
    }
}