-1

I have one label in xml file and i want to store some text in this label e.g when i first run my app the label should show the message that "First time run" and when i close it and open it again it should show me the message that "Second time run" and when i delete the app and run it again it should show me again "First time run".Can anyone help me how to do it please.How should i use shared preferences in this type of situation?

[This is the code i have tried][1]

Ruby prO
  • 109
  • 2
  • 12

1 Answers1

1

Do it by using application run counter. You can do this by following:

Every time you run your get and update shared preferences values for application counter

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mobile_main);
    int appCounter = getIntPreferences("SP_APP_COUNTER");
    if(appCounter == -1) {
        // Label your text here for first run            
    } else {
       // Label your text here for second run and so for...
    }
       // update counter
       appCounter++;
       updatePreferences("SP_APP_COUNTER", appCounter);

}


public void updatePreferences(String key, int value) {
    SharedPreferences settings = context.getSharedPreferences("your_project_name", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = settings.edit();
    editor.putInt(key, value);
    editor.commit();

}

public int getIntPreferences(String key) {
    SharedPreferences settings = context.getSharedPreferences("your_project_name", 0);
    return settings.getInt(key, -1);
}
Adnan Amjad
  • 2,553
  • 1
  • 20
  • 29
  • Thank you so much for the help i understood it except one part can you please tell me what is the context? e.g context.getSharedPreferences? – Ruby prO Apr 10 '16 at 09:17
  • it is your application context. use getApplicationContext() – Adnan Amjad Apr 10 '16 at 09:20
  • At the left of my answer. You can see up and down arrows. Click on up button first and then click on Tick mark (below down arrow) – Adnan Amjad Apr 10 '16 at 11:41