有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在另一个活动中检索SharedReference文件的值?

Activity 1st..
Here this is my first activity to add data


preferences=PreferenceManager.getDefaultSharedPreferences(context);
                  preferences = getPreferences(MODE_PRIVATE);
                  editor = preferences.edit();
                 editor.putString("userid",et_username.getText().toString());//adduserid
                editor.putString("password",et_password.getText().toString());//add password
                  editor.commit();

活动2 这是我检索数据的第二个活动

String userName=preferences.getString("userid","");
            String password=preferences.getString("password","");
            Log.d("user : second", ""+preferences.getString("userid",""));
            Log.d("password : second", ""+preferences.getString("password",""));

由于空值,此处不显示日志


共 (4) 个答案

  1. # 1 楼答案

    我只存储一个整数值,您必须在其中存储多个值

    PreferenceConnector.writeInteger(home.this, PreferenceConnector.com_id, homeComp_id);
    

    在要在其中使用的preferenceConnector类下面

    public class PreferenceConnector {
    
    public static final String PREF_NAME = "Shared Preference";
    public static final int MODE = Context.MODE_PRIVATE;
    
    public static final String com_id = "com_id";
    
    public static void writeBoolean(Context context, String key, boolean value) {
        getEditor(context).putBoolean(key, value).commit();
    }
    
    public static boolean readBoolean(Context context, String key, boolean defValue) {
        return getPreferences(context).getBoolean(key, defValue);
    }
    
    public static void writeInteger(Context context, String key, int value) {
        getEditor(context).putInt(key, value).commit();
    
    }
    
    public static int readInteger(Context context, String key, int defValue) {
        return getPreferences(context).getInt(key, defValue);
    }
    
    public static SharedPreferences getPreferences(Context context) {
        return context.getSharedPreferences(PREF_NAME, MODE);
    }
    
    public static Editor getEditor(Context context) {
        return getPreferences(context).edit();
    }
    
    }
    

    然后,你还可以将股票优先权价值用于其他活动,如以下

     int Pref = PreferenceConnector.readInteger(mainpage.this, PreferenceConnector.com_id, 0);
    

    希望以上代码有用

  2. # 2 楼答案

    String userName=preferences.getString("userid");
    String password=preferences.getString("password");
    Log.d("user : second", ""+userName);
    Log.d("password : second", ""+password);
    

    你能试试这条路吗

  3. # 3 楼答案

    检查preferences对象(可能是null)。这可能就是问题所在,因为其他字符串变量从不为null,所以可以是空字符串(""

    在本例中,您是否缺少第二个Activitypreferences的初始化

  4. # 4 楼答案

    在这两个活动中,只需使用此项即可获取SharedReferences对象:

    SharedPreferences prefs = getSharedPreferences("PREFS", Context.MODE_PRIVATE);

    可能是您试图从不同的活动访问不同的首选项文件

    或者只是使用

    PreferenceManager.getDefaultSharedPreferences(this);