Android: perform a task while the app is open for the first time?

I need to create a database table when the application is launched for the first time after installation. So how do I get the status of an application being launched the first time the application is installed? I have heard about SharedPreferences but am not familiar with it. Any code help is greatly appreciated and thanks in advance ...

+3


source to share


3 answers


SQLiteOpenHelper has an onCreate method that is called if the database does not exist and needs to be created the first time.



Use this to create and initialize a database with whatever data you need in tables.

+3


source


if you are trying to insert a value into the database the first time you run your application, you can put the value in sharedPref like this:

    private static void SaveBooleanPreferences(String key, boolean value, Context context){
        SharedPreferences sharedPreferences = context.getSharedPreferences(PREFS_NAME,0);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean(key, value);
        editor.commit();

    }
    private static boolean getBooleanPreferences(String key, Context context){
        SharedPreferences sharedPreferences = context.getSharedPreferences(PREFS_NAME,0);
        return sharedPreferences.getBoolean(key, false);

    }

      



after you find the first run value, try to insert it into the database, Android OS will hand over the database creation to you, you don't need to create it yourself!

+1


source


I solved it by referencing the following code:

SharedPreferences prefs = getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
boolean haveWeShownPreferences = prefs.getBoolean("HaveShownPrefs", false);

if (!haveWeShownPreferences) 
{
    // launch the preferences activity

}
else
{
   // we have already shown the preferences activity before
}

SharedPreferences prefs1 = getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
SharedPreferences.Editor ed = prefs1.edit();
ed.putBoolean("HaveShownPrefs", true);
ed.commit();`

      

+1


source







All Articles