保存/显示SQLite数据库时显示ProgressBar

时间:2017-03-28 11:40:01

标签: android sqlite android-sqlite android-progressbar

我是Android开发的新手 我正在尝试完成我的应用程序,这个应用程序将数据保存到SQLite数据库,显示,更新,删除等。但是当我尝试显示数据库中的所有行时,这需要花费太多时间。我想添加一个ProgressBar来向用户表明它正在花时间。

我可以在此代码中添加ProgressBar吗?

这是MainActivity:

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //Instantiate database handler
    db=new DatabaseHandler(this);

    lv = (ListView) findViewById(R.id.list1);
    pic = (ImageView) findViewById(R.id.pic);

    nazev =(EditText) findViewById(R.id.nazev);
    objem =(EditText) findViewById(R.id.objem);
    obsah_alkoholu =(EditText) findViewById(R.id.obsah_alkoholu);
    aroma =(EditText) findViewById(R.id.aroma);
    chut =(EditText) findViewById(R.id.chut);
    dokonceni =(EditText) findViewById(R.id.dokonceni);
    poznamka =(EditText) findViewById(R.id.poznamka);
    vsechnyradky =(TextView) findViewById(R.id.textView);

    ShowRecords();



}

public void buttonClicked(View v){
    int id=v.getId();

    switch(id){

        case R.id.save:

            if(nazev.getText().toString().trim().equals("")){
                Toast.makeText(getApplicationContext(),"Není název.", Toast.LENGTH_LONG).show();
            }  else{
                addRumy();
            }
            ShowRecords();
            break;

        case R.id.display:

            ShowRecords();
            break;
        case R.id.pic:
            selectImage();
            break;
    }
}

public void selectImage(){
    Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
    photoPickerIntent.setType("image/*");
    startActivityForResult(photoPickerIntent, 2);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch(requestCode) {
        case 2:
            if(resultCode == RESULT_OK){
                Uri choosenImage = data.getData();

                if(choosenImage !=null){

                    bp=decodeUri(choosenImage, 400);
                    pic.setImageBitmap(bp);
                }
            }
    }
}

//COnvert and resize our image to 400dp for faster uploading our images to DB
protected Bitmap decodeUri(Uri selectedImage, int REQUIRED_SIZE) {

    try {

        // Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o);

        // The new size we want to scale to
        // final int REQUIRED_SIZE =  size;

        // Find the correct scale value. It should be the power of 2.
        int width_tmp = o.outWidth, height_tmp = o.outHeight;
        int scale = 1;
        while (true) {
            if (width_tmp / 2 < REQUIRED_SIZE
                    || height_tmp / 2 < REQUIRED_SIZE) {
                break;
            }
            width_tmp /= 2;
            height_tmp /= 2;
            scale *= 2;
        }

        // Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        return BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o2);
    }
    catch (Exception e){
        e.printStackTrace();
    }
    return null;
}

//Convert bitmap to bytes
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
private byte[] profileImage(Bitmap b){

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    b.compress(Bitmap.CompressFormat.PNG, 0, bos);
    return bos.toByteArray();

}

// function to get values from the Edittext and image
private void getValues(){
    f_nazev = nazev.getText().toString();
    f_objem = objem.getText().toString();
    f_obsah_alkoholu = obsah_alkoholu.getText().toString();
    f_aroma = aroma.getText().toString();
    f_chut = chut.getText().toString();
    f_dokonceni = dokonceni.getText().toString();
    f_poznamka = poznamka.getText().toString();
    photo = profileImage(bp);
}

//Insert data to the database
private void addRumy(){
    getValues();

    db.addRumy(new Rumy(f_nazev, f_objem, f_obsah_alkoholu, f_aroma, f_chut, f_dokonceni, f_poznamka, photo));
    showProgressDialogHorizontal();

    db.close();
}
//Retrieve data from the database and set to the list view
private void ShowRecords(){
    final ArrayList<Rumy> rumy = new ArrayList<>(db.getAllRumy());
    data=new DataAdapter(this, rumy);

    lv.setAdapter(data);

    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            dataModel = rumy.get(position);

            final Dialog openDialog = new Dialog(context2);
            openDialog.setContentView(R.layout.dialogove_okno_mazani);
            AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
            alertDialog.setTitle("Souhrn záznamu k odeslání:");
            alertDialog.setMessage("Opravdu si přejete smazat tento záznam???");

            alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "Zpět",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Zrušit mazání",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            startActivity(getIntent());
                        }
                    });
            alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Smazat trvale!",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                           // db.deleteRumy(String.valueOf(dataModel.getID()));
                            showProgressDialogHorizontal();
                            db.clearDatabase();
                            db.close();
                           // ShowRecords();
                            finish();

                        //    Toast.makeText(getApplicationContext(),String.valueOf(dataModel.getID()), Toast.LENGTH_SHORT).show();
                        //    startActivity(getIntent());


                        }
                    });
            alertDialog.show();              
        }
    });
}}

db.getAllRumy

public List<Rumy> getAllRumy() {
    List<Rumy> rumytList = new ArrayList<Rumy>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_NAME;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            Rumy rumy = new Rumy();
            rumy.setID(Integer.parseInt(cursor.getString(0)));
            rumy.setNazev(cursor.getString(1));
            rumy.setObjem(cursor.getString(2));
            rumy.setObsahAlkoholu(cursor.getString(3));
            rumy.setAroma(cursor.getString(4));
            rumy.setChut(cursor.getString(5));
            rumy.setDokonceni(cursor.getString(6));
            rumy.setPoznamka(cursor.getString(7));
            rumy.setFoto(cursor.getBlob(8));

            // Adding contact to list
            rumytList.add(rumy);
        } while (cursor.moveToNext());
    }

    // return contact list
    return rumytList;
}

Error

3 个答案:

答案 0 :(得分:1)

使用此

ProgressDialog pDialog = new ProgressDialog(this);
        pDialog.setMessage("please wait...");
        pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pDialog.setCancelable(false);
        pDialog.show();

并在数据加载后关闭进度对话框

pDialog.dismiss();

答案 1 :(得分:1)

对ShowRecords()使用asyncTask并覆盖OnProgressUpdate方法

@Override
protected void onProgressUpdate(Integer... values) {
    // use the values to update your progress bar
}

你的ShowRecords应该是这样的

    private void ShowRecords() {
        final ProgressDialog pDialog = new ProgressDialog(this);
        pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pDialog.setCancelable(false);
        new AsyncTask<Object,Integer,ArrayList<Rumy>>() {
            @Override
            protected ArrayList<Rumy> doInBackground(Object[] params) {
                ArrayList<Rumy> rumy = db.getAllRumy();
                return rumy;
            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                pDialog.setMessage("please wait..."+ values[0]);
                pDialog.show();
            }

            @Override
            protected void onPostExecute(ArrayList<Rumy> list) {
                data=new DataAdapter(this,list);
                lv.setAdapter(list);
                //lv.setOnItemClickListener can be put here
            }
        }.execute();
    }

答案 2 :(得分:0)

当你的函数showRecords()在下一行中调用时,可以看到进度条可见,当函数完全执行时,进度条就会消失。 我想你知道如何添加进度条,因为你没有提到如何使用它。