How to keep information about an app in Android?

前端 未结 2 558
滥情空心
滥情空心 2021-01-27 01:39

I want to know if its possible to keep information about an app in a while for example.

I have an app that access this file and get information about the choices that th

相关标签:
2条回答
  • 2021-01-27 02:07

    Use Shared Preferences. Like so:

    Create these methods for use, or just use the content inside of the methods whenever you want:

    public String getPrefValue()
    {
      SharedPreferences sp = getSharedPreferences("preferenceName", 0);
      String str = sp.getString("myStore","TheDefaultValueIfNoValueFoundOfThisKey");
      return str;
    }
    
    public void writeToPref(String thePreference)
    {
      SharedPreferences.Editor pref =getSharedPreferences("preferenceName",0).edit();
      pref.putString("myStore", thePreference);
      pref.commit();
    }
    

    You could call them like this:

    // when they click the button:
    writeToPref("theyClickedTheButton");
    
    if (getPrefValue().equals("theyClickedTheButton"))
    {
       // they have clicked the button
    }
    else if (getPrefValue().equals("TheDefaultValueIfNoValueFoundOfThisKey"))
    {
       // this preference has not been created (have not clicked the button)
    }
    else
    {
       // this preference has been created, but they have not clicked the button
    }
    

    Explanation of the code:

    "preferenceName" is the name of the preference you're referring to and therefore has to be the same every time you access that specific preference. eg: "password", "theirSettings"

    "myStore" refers to a specific String stored in that preference and their can be multiple. eg: you have preference "theirSettings", well then "myStore" could be "soundPrefs", "colourPrefs", "language", etc.

    Note: you can do this with boolean, integer, etc.

    All you have to do is change the String storing and reading to boolean, or whatever type you want.

    0 讨论(0)
  • 2021-01-27 02:29

    You can use SharedPreference to save your data in Android.

    To write your information

    SharedPreferences preferences = getSharedPreferences("PREF", Context.MODE_PRIVATE);
    SharedPreferences.Editor   editor = preferences.edit();
    editor.putString("user_Id",userid.getText().toString());
    editor.putString("user_Password",password.getText().toString());
    editor.commit(); 
    

    To read above information

    SharedPreferences prfs = getSharedPreferences("PREF", Context.MODE_PRIVATE);
    String username = prfs.getString("user_Id", "");
    

    In iOS NSUserDefaults is used to do the same

    //For saving

    NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
    [defaults setObject:your_username forKey:@"user_Id"];
    [defaults synchronize];
    

    //For retrieving

    NSString *username = [defaults objectForKey:@"user_Id"];
    

    Hope it helps.

    0 讨论(0)
提交回复
热议问题