sharedpreferences in the first Activity, show only once?

1

I'm developing an app where it will have the first Activity fault, and I want to show it only once, only when the app is first opened.

In this case, I created a Activity by calling a layout where it contains the textview and button , as soon as the user clicks the button, it will open Activity main of the app, and then I do not want the Activity of greeting to be shown anymore.

My layout (short):

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Saudação Aqui" />

<Button 
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="sendMessage"
android:text="Ok, entrar para Activity principal e não mostrar mais essa tela" />

Greeting activity:

Button button;

    public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
     button=(Button)findViewById(R.id.button1); 

    button.setOnClickListener(new View.OnClickListener() { 

    @Override 
    public void onClick(View v) { 
    // TODO Auto-generated method stub 

    Intent i = new Intent(getApplicationContext(),Activity Principal.class);
    startActivity(i); 
} 
}); 
}

Thank you!

    
asked by anonymous 22.02.2016 / 21:16

1 answer

2

First you implement a class to manage SharedPreferences (per organization).

public class PreferencesManager {
    public static final String ENTERING_FIRST_TIME = "EnteringFirstTime";

    public static void storeInt(Context context, String key, int value) {
        SharedPreferences prefs = context.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt(key, value);
        editor.commit();
    }

    public static int getInt(Context context, String key, int defaultValue){
        return context.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE).getInt(key, defaultValue);
    }
}

So when your app starts, you can check it like this:

if(PreferencesManager.getInt(view, PreferencesManager.ENTERING_FIRST_TIME, 1) == 1){
    //Salva informação de que o usuário já entrou no app a primeira vez
    PreferencesManager.storeInt(view, PreferencesManager.ENTERING_FIRST_TIME, 0);
    //Exibe saudação
}
else{
    //Esconde saudação
}

Ideally, you should read and write information in SharedPreferences outside of the UI thread to prevent your application from being destroyed by Application Not Responding (ANR). ANR's happen when your application processes something longer than allowed on the Main Thread (five seconds).

It may seem impossible for such a simple task to take more than five seconds, but in some cases resource competition can happen.

You can prevent this by calling the second block of code within a AsyncTask .

    
23.02.2016 / 10:34