简体   繁体   English

Android储存价值

[英]Android Storing Values

I apologize in advance, this might sound like an incredibly dumb question. 我事先表示歉意,这听起来像是一个非常愚蠢的问题。 I am a bit out of it today. 我今天有点不高兴。 So I am finishing up a Login Verification activity that uses a REST API to authenticate. 因此,我正在完成一个使用REST API进行身份验证的登录验证活动。 It works just fine, but I would like on success to save that email in an object so that the rest of the application knows the email of the user currently in the app. 它工作正常,但我希望成功地将该电子邮件保存在一个对象中,以便应用程序的其余部分知道当前在应用程序中的用户的电子邮件。 I made a POJO class called AccountInformation that will hold this email (among other details later on), but I am drawing a blank as to how I can access those values outside of the class. 我创建了一个名为AccountInformation的POJO类,该类将保存此电子邮件(稍后会提供其他详细信息),但是我在如何访问类之外的这些值方面还是空白。

For example, I have to make a call in the Account Modification class that requires me to send the email in a request. 例如,我必须在“帐户修改”类中打电话,要求我发送请求中的电子邮件。 But the email was stored in an object I made in a separate activity. 但是电子邮件是存储在我在单独活动中创建的对象中。 I am so sorry if I'm not making sense, but I really feel like an idiot right now because this should be simple. 如果我没有道理,我感到非常抱歉,但是现在我真的感觉像个白痴,因为这应该很简单。

You should store it in something persistent like SharedPreferences . 您应该将其存储在诸如SharedPreferences持久性内容中。 When the app goes into the background, the whole process could be destroyed without warning. 当应用程序进入后台时,整个过程可能会在没有警告的情况下被破坏。 When you return to the app, the fields of your POJO will be uninitialized, or the reference to the POJO itself will be null, depending now it's initialized. 当您返回应用程序时,POJO的字段将未初始化,或者对POJO本身的引用将为null,具体取决于现在已初始化。

Yes, this should be simple. 是的,这应该很简单。 The entire Android framework is extraordinarily and unnecessarily complicated. 整个Android框架异常复杂,而且不必要。

A simple example for shared preference saving User_name 共享首选项保存User_name的简单示例

@Override    
enter code here

    // Restore preferences
    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    String Name = settings.getString("user_name", "unknown");
    }

@Override

protected void onStop(){ super.onStop();


    // We need an Editor object to make preference changes.
    // All objects are from android.context.Context
    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putString("user_name", mUserName);

    // Commit the edits!
    editor.apply();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM