在 PreLoad 中将批量数据输入到 SQLite 时,SharedPreferences 如何获取 FirstRun(false)?

How SharedPreferences getFirstRun(false) when bulk data has been entered to SQLite in PreLoad?

我的应用程序可以使用 DatabaseHelper.java extends SQLiteOpenHelper 和 PreLoadActivity.java extends AsyncTask(使用进度条在后台加载数据)将批量数据从文本插入 SQLite。但是当我每次总是加载数据时打开我的应用程序时出现问题。我在我的应用程序中使用 SharedPreferences。

这是代码。

AppPreference.java

public class AppPreference {

    SharedPreferences prefs;
    Context context;

    public AppPreference(Context context) {
        prefs = PreferenceManager.getDefaultSharedPreferences(context);
        this.context = context;
    }

    public void setFirstRun(Boolean input) {
        SharedPreferences.Editor editor = prefs.edit();
        String key = context.getResources().getString(R.string.app_first_run);
        editor.putBoolean(key, input);
        editor.commit();
    }

    public Boolean getFirstRun() {
        String key = context.getResources().getString(R.string.app_first_run);
        return prefs.getBoolean(key, true);
    }
}

DatabaseHelper.java(片段代码)

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "kamus.db";
    private static final int DATABASE_VERSION = 1;
    private static final String LOG = "DatabaseHelper";
    private static SQLiteDatabase db;

    private static DatabaseHelper instance;
    private static Context context;

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_ENGLISH);
        db.execSQL(CREATE_TABLE_INDONESIA);
    }

    @Override
    public synchronized void close(){
        if (instance != null)
            db.close();
    }

    public void insertEnglish(ArrayList<EnglishIndonesiaModel> kamusEnglish) {
        db.beginTransaction();
        try {
            for (EnglishIndonesiaModel data : kamusEnglish) {
                Log.d("tag", "insert eng: " + data.getWord());
                insertDataEnglish(data.getWord(), data.getTranslate());
            }
            db.setTransactionSuccessful();
        } catch (Exception error) {
            Log.e("tag", "error " + error.getLocalizedMessage());
        } finally {
            db.endTransaction();
        }
    }

    public void insertIndonesia(ArrayList<IndonesiaEnglishModel> kamusIndonesia) {
        db.beginTransaction();
        try {
            for (IndonesiaEnglishModel data : kamusIndonesia) {
                Log.d("tag", "insert ina:  " + data.getKata());
                insertDataIndonesia(data.getKata(), data.getTerjemahan());
            }
            db.setTransactionSuccessful();
        } catch (Exception error) {
            Log.e("tag", "eror " + error.getLocalizedMessage());
        } finally {
            db.endTransaction();
        }
    }
}

PreLoadActivity.java(片段代码)

public class PreloadActivity extends AppCompatActivity {

    ProgressBar progressBar;
    TextView tvLoading;

    private DatabaseHelper databaseHelper;

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

        progressBar = findViewById(R.id.progress_bar);
        tvLoading = findViewById(R.id.tv_loading);

        databaseHelper = DatabaseHelper.getInstance(PreloadActivity.this);
        new LoadData().execute();
    }

private class LoadData extends AsyncTask<Void, Integer, String> {
        final String TAG = LoadData.class.getSimpleName();
        AppPreference appPreference;
        double progress;
        double maxProgress = 100;

 @Override
        protected void onPreExecute() {
            Log.d(TAG, "onpre");
            appPreference = new AppPreference(PreloadActivity.this);
        }

        @Override
        protected String doInBackground(Void... params) {

            Log.d(TAG, "doinbackground");

            ArrayList<EnglishIndonesiaModel> kamusEnglish = preLoadEnglishRaw(R.raw.english_indonesia);
            ArrayList<IndonesiaEnglishModel> kamusIndonesia = preLoadRaw(R.raw.indonesia_english);

            databaseHelper.insertEnglish(kamusEnglish);
            databaseHelper.insertIndonesia(kamusIndonesia);

            Boolean firstRun = appPreference.getFirstRun();
            if (firstRun) {

                Log.d("tag", "eng_ind size " + kamusEnglish.size());
                Log.d("tag", "ind_eng size " + kamusIndonesia.size());

                progress = 30;
                publishProgress((int) progress);
                Double progressMaxInsert = 100.0;
                Double progressDiff = (progressMaxInsert - progress) / kamusEnglish.size() + kamusIndonesia.size();

                // When DatabaseHelper.close() or insert Data SQLiteDatabase endTransaction() or setTransactionSuccessfull() then AppPreference.setFirstRun(false)
                ...................
                ...................
                ...................

                appPreference.setFirstRun(false);

                progress += progressDiff;
                publishProgress((int) maxProgress);

            } else {
                tvLoading.setVisibility(View.VISIBLE);
                try {
                    synchronized (this) {
                        this.wait(2000);
                        publishProgress(50);

                        this.wait(2000);
                        publishProgress((int) maxProgress);
                    }
                } catch (Exception e) {
                }
            }

            return "data inserted";
        }
    }
}

你在检查条件时搞砸了。 如果 firstRun 已完成,则根本不要调用 AsyncTask

AppPreference appPreference = new AppPreference(PreloadActivity.this);
Boolean firstRun = appPreference.getFirstRun();
    if(firstRun) {
        new LoadData().execute();
 }

并在 doInBackground() 内设置 setFirstRun(false).

appPreference.setFirstRun(false);
public SharedPreferences pref;
public SharedPreferences.Editor editor;
private final String myPreference = "login";
private String firstTime = "firstTime";

public Method(Activity activity) {
    this.activity = activity;
    pref = activity.getSharedPreferences(myPreference, 0); // 0 - for private mode
    editor = pref.edit();
}

if (!pref.getBoolean(firstTime, false)) {
      editor.putBoolean(firstTime, true);
      editor.commit();
}

you can get value pref.getBoolean(firstTime, false) // retun true allways

if(pref.getBoolean(firstTime, false)){
//your code
}

像这样更改您的 AppPreference 代码:

prefs= context.getSharedPreferences(your_preference_name, Context.MODE_PRIVATE);