How do I ask someone for their name and then save it into a string (on Android). I tried creating an EditText and saving it into a string, but I can't use that string across all my classes, so then I tried to save it into the internal storage of my phone, but I got a logic error which I couldn't solve, so I just gave up on that. How do I do this? It can be either Java or XML (I prefer XML). Please, any suggestions?
答案 0 :(得分:0)
You can use SharedPreferences. But you need a Context to gain access to it, e.g. via the getSharedPreferences()
method.
So a quick solution (not elegant though) would be to keep a reference to your main activity (or to any other instance of a class that extends Context) in some place that is visible to the whole app (maybe a class named Globals with some public static field) and then retrieve and use the shared preferences from wherever you need via this reference.
Here is an example of how you can set and get the shared preferences.