How do I ask for someone's name then save it on Android?

时间:2015-07-28 22:15:42

标签: java android

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?

1 个答案:

答案 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.