在向多个表添加数据行时实现AsyncTask

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在向多个表添加数据行时实现AsyncTask相关的知识,希望对你有一定的参考价值。

我创建了一个显示TextViewProgressBar的屏幕。 ProgressBar代表数据库创建,并使用SQLite将1000 ++数据添加到GSON中。为了实现这一点,我创建了三个不同的文件,LocalDBHelper(这是我的数据库设置),GSONHandler(将我的JSON文件转换为SQLite)和加载(我的AsyncTask)。

我的问题是,我的ProgressBar是静态的,并没有显示添加数据的进度。我是android开发的新手,并且在继续我的代码时一无所知。

main activity.Java

public class MainActivity extends AppCompatActivity implements Loading.LoadingTaskFinishedListener {

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

        LocalDBHelper mydb = LocalDBHelper.newInstance(this);
        //check if db exist, delete db if exist
            if (doesDatabaseExist(mydb.getDatabaseName()))
                this.deleteDatabase(mydb.getDatabaseName());

        ProgressBar progressBar = findViewById(R.id.progressBar);
            new Loading(progressBar, this, this).execute("");

        }

      @Override
      public void onTaskFinished() {
        finish();
      }

        public boolean doesDatabaseExist(String databaseName) {
            File dbFile = this.getDatabasePath(databaseName);
            return dbFile.exists();
        }
}

loading.Java

public class Loading extends AsyncTask<String, Integer, Integer> {

    public interface LoadingTaskFinishedListener {
        void onTaskFinished();
    }

    private LocalDBHelper mydb = null;

    private final ProgressBar progressBar;
    private Context mContext;
    private final LoadingTaskFinishedListener finishedListener;

    public Loading(ProgressBar progressBar, LoadingTaskFinishedListener finishedListener, Context context) {
        this.progressBar = progressBar;
        this.finishedListener = finishedListener;
        this.mydb = LocalDBHelper.newInstance(context);
        mContext = context;

    }

    @Override
    protected Integer doInBackground(String... params) {
        SQLiteDatabase sqLiteDatabase = mydb.getWritableDatabase();
        GSONHandler.newInstance(mContext, sqLiteDatabase);

        return 1234;

    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        progressBar.setProgress(values[0]);
    }

    @Override
    protected void onPostExecute(Integer result) {
        super.onPostExecute(result);
        finishedListener.onTaskFinished();
    }
}

G son handler.Java

public class GSONHandler {

    static final String TAG = GSONHandler.class.getSimpleName();

    private Context context;
    private LocalDBHelper mydb;
    private SQLiteDatabase sqLiteDatabase;

    private static GSONHandler mGsonHandler = null;

    public static GSONHandler newInstance(Context context, SQLiteDatabase sqLiteDatabase){
        if (mGsonHandler == null){
            mGsonHandler = new GSONHandler(context.getApplicationContext(), sqLiteDatabase);
        }
        return mGsonHandler;
    }

    private GSONHandler(Context context, SQLiteDatabase sqLiteDatabase) {
        this.context = context;
        this.sqLiteDatabase = sqLiteDatabase;

        onCreate();
    }

    //assign json data to tables
    private void onCreate() {

        //get local json and save it to db
        premiseCategoryMasterSetup();
        premiseCategorySetup();
        inspcTypeSetup();
        inspcStatusSetup();
        stateSetup();
        areaSetup();
        districtSetup();
        analysisGroupSetup();
        analysisSubGroup();
        parameterSetup();
        subParameterSetup();
        identificationSetup();
        premiseCertliSetup();
        txn_premiseSetup();
        prosecutionOtherSetup();
        txn_layoutSectionSetup();
        txn_layoutCardSetup();
        txn_layoutInputFieldSetup();
    }

    private void areaSetup() {
        Log.d(TAG, "areaSetup");
        InputStream inputStream = context.getResources().openRawResource(R.raw.ref_area);
        String jsonString = readJsonFile(inputStream);

        Gson gson = new Gson();
        List<Area> areaList = Arrays.asList(gson.fromJson(jsonString, Area[].class));

        for (Area area : areaList)
        {
            if(sqLiteDatabase != null) {
                ContentValues values = new ContentValues();
                values.put(Constants.COLUMN_AREA_ID, area.getAreaId());
                values.put(Constants.COLUMN_AREA_CODE, area.getAreaCode());
                values.put(Constants.COLUMN_AREA_NAME, area.getAreaName());
                values.put(Constants.COLUMN_ACTIVE, area.getActive());
                values.put(Constants.COLUMN_FK_STATE_ID, area.getFk_stateId());

                long id = sqLiteDatabase.insertOrThrow(Constants.REF_AREA_TABLE,
                        null, values);
            }
        }

    }

    ....

    private String readJsonFile(InputStream inputStream) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte bufferByte[] = new byte[1024];
        int length;

        try {
            while ((length = inputStream.read(bufferByte)) != -1) {
                outputStream.write(bufferByte, 0 , length);
            }
            outputStream.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return outputStream.toString();
    }

}
答案

您正在onProgressUpdate方法中设置进度条的进度,但从不调用它。要调用onProgressUpdate方法,需要在publishProgress方法中调用doInBackground方法。在调用onProgressUpdate方法之后,在UI线程上调用publishProgress方法。

另一答案

doInBackground()中调用publishProgress();方法来显示和更新进度条。希望这会有所帮助。

以上是关于在向多个表添加数据行时实现AsyncTask的主要内容,如果未能解决你的问题,请参考以下文章

NSFetchedResultsController 在向第二部分插入行时在第一部分返回错误的行数

数据表并发锁定

添加行时在列中重新编号 sql

跟踪 SQL 中的新主键

Android源代码解析之--&gt;HandlerThread

我可以添加多个 AsyncTask 并同时执行吗?