活动之间的共享偏好

sharedpreferences between activities

这个问题有点类似于其他共享偏好问题,但我真的不知道如何在不同的活动之间使用它?请尽可能提供完整的 activity 文件,而不是几行代码,因为我是这个领域的菜鸟!

我有两个活动。一个是 userprofile,另一个是 edituserprofile。无论用户在 edituserprofile 中编辑什么,都应该在用户从 edituserprofile 的应用栏中单击保存图像按钮后立即显示在 userprofile activity 中。 sharedpreferences 在 edituserprofile 中完美运行,用户可以在其中查看输入的数据,也可以像 edittextview 一样对其进行更改。但是,我无法将相同的逻辑应用于用户配置文件 activity。当我从 edituserprofile 单击保存按钮时,它会带我到 userprofile,我可以看到在 edituserprofile 中所做的更改,但是一旦我退出 userprofile 并重新启动它,数据就会在 userprofile 中被清除,但不会从 edituserprofile 中清除!我希望用户配置文件保存,显示来自 edituserprofile 的数据,甚至用户退出并重新启动应用程序!

以下是用户资料 activity!

package com.example.android.coffeeshop6menus;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;


public class UserProfile extends AppCompatActivity {

    public static final int Edit_Profile = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_profile);
        Toolbar userProfileToolbar = (Toolbar) findViewById(R.id.my_toolbar);
        setSupportActionBar(userProfileToolbar);
        SharedPreferences sharedpreferences = getPreferences(MODE_PRIVATE);
        displayMessage(sharedpreferences.getString("nameKey", ""));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.userprofile_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_editProfile:
                Intent userProfileIntent = new Intent(UserProfile.this, EditUserProfile.class);
                startActivityForResult(userProfileIntent, Edit_Profile);
        }
        return true;
    }

    // Call Back method  to get the Message form other Activity

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case Edit_Profile:
                if (resultCode == RESULT_OK) {
                    String name = data.getStringExtra("");
                    displayMessage(name);
                }
                break;
        }
    }

    public void displayMessage(String message) {
        TextView usernameTextView = (TextView) findViewById(R.id.importProfile);
        usernameTextView.setText(message);
    }
}

下面是 edituserprofile activity,效果非常好!

package com.example.android.coffeeshop6menus;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class EditUserProfile extends AppCompatActivity {

    private CoordinatorLayout coordinatorLayout;
    public static final String Name = "nameKey";
    SharedPreferences sharedpreferences;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_user_profile);
        Toolbar userProfileToolbar = (Toolbar) findViewById(R.id.my_toolbar);
        setSupportActionBar(userProfileToolbar);
        TextView usernameTextView = (TextView) findViewById(R.id.username);
        sharedpreferences = getSharedPreferences(Name, Context.MODE_PRIVATE);
        if (sharedpreferences.contains(Name)) {
            usernameTextView.setText(sharedpreferences.getString(Name, ""));
        }
        coordinatorLayout = (CoordinatorLayout) findViewById(R.id
                .coordinatorLayout);

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.editprofile_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_save:
                TextView usernameTextView = (TextView) findViewById(R.id.username);
                String usernameString = usernameTextView.getText().toString();
                SharedPreferences.Editor editor = sharedpreferences.edit();
                editor.putString(Name, usernameString);
                editor.apply();
                Snackbar snackbar = Snackbar
                        .make(coordinatorLayout, "Saved!", Snackbar.LENGTH_LONG);

                snackbar.show();
                Intent userProfileIntent = new Intent(EditUserProfile.this, UserProfile.class);
                userProfileIntent.putExtra("", usernameString);
                setResult(RESULT_OK, userProfileIntent);
                finish();

        }
        return true;
    }


}

下面是 userprofile.xml 文件

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout

        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context="com.example.android.coffeeshop6menus.UserProfile">

        <include
            layout="@layout/toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"

            />


        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="16dp"
            android:text="Name"
            android:textSize="20dp" />

        <TextView
            android:id="@+id/importProfile"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="16dp"
            android:text="@string/userNameImport"
            android:textSize="20dp" />





    </LinearLayout>

</ScrollView>

下面是 edituserprofile xml 文件:

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout

        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context="com.example.android.coffeeshop6menus.UserProfile">

        <include
            layout="@layout/toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"

            />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">


            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="16dp"
                android:text="User Profile"
                android:textSize="20dp" />


        </LinearLayout>


        <EditText
            android:id="@+id/username"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp"
            android:cursorVisible="true"
            android:hint="@string/EditTextHint"
            android:inputType="textNoSuggestions" />

        <EditText
            android:id="@+id/usercontact"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp"
            android:cursorVisible="true"
            android:hint="@string/usercontactHint"
            android:inputType="textNoSuggestions" />

        <EditText
            android:id="@+id/useremail"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp"
            android:cursorVisible="true"
            android:hint="@string/useremailHint"
            android:inputType="textEmailAddress" />


    </LinearLayout>

</ScrollView>

请帮忙!

您正在使用两个活动的本地共享首选项,如 docs for this method:

Retrieve a SharedPreferences object for accessing preferences that are private to this activity.

解决方案是使用全局共享首选项:

 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

一个主要的难题是您在 UserProfile 中使用 getPreferences(),但在 EditUserProfile 中使用 getSharedPreferences()。第一种方法只会获取 UserProfile activity 的键值对,而第二种方法可供应用程序的任何部分访问。将 getPreferences() 切换为 getSharedPreferences(),你应该没问题。

http://developer.android.com/guide/topics/data/data-storage.html#pref

来自该网站: public class 计算扩展 Activity { public 静态最终字符串 PREFS_NAME = "MyPrefsFile";

@Override
protected void onCreate(Bundle state){
   super.onCreate(state);
   . . .

   // Restore preferences
   SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
   boolean silent = settings.getBoolean("silentMode", false);
   setSilent(silent);
}

@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.putBoolean("silentMode", mSilentMode);

  // Commit the edits!
  editor.commit();
}

在你的 UserProfile class 和其他地方改变 -

SharedPreferences sharedpreferences = getPreferences(MODE_PRIVATE);

由此-

 sharedpreferences = getSharedPreferences("nameKey", Context.MODE_PRIVATE);

你很高兴去!