Android 活动之间的共享引用

Android 活动之间的共享引用,android,save,sharedpreferences,savestate,Android,Save,Sharedpreferences,Savestate,这个问题有点类似于其他SharedReference问题,但我真的不知道如何在不同的活动之间准确地使用它?请提供完整的活动文件,如果可能的话,而不是仅仅几行代码,因为我是这个领域的noob 我有两项活动。一个是userprofile,另一个是edituserprofile。无论用户在edituserprofile中编辑什么,只要用户单击edituserprofile应用程序栏上的“保存图像”按钮,都应在userprofile活动中显示。SharedReferences在edituserprofi

这个问题有点类似于其他SharedReference问题,但我真的不知道如何在不同的活动之间准确地使用它?请提供完整的活动文件,如果可能的话,而不是仅仅几行代码,因为我是这个领域的noob

我有两项活动。一个是userprofile,另一个是edituserprofile。无论用户在edituserprofile中编辑什么,只要用户单击edituserprofile应用程序栏上的“保存图像”按钮,都应在userprofile活动中显示。SharedReferences在edituserprofile中工作得非常好,用户可以在其中查看输入的数据,也可以在edittextview中更改数据。但是,我无法将相同的逻辑应用于userprofile活动。当我从edituserprofile单击save按钮时,它会将我带到userprofile,我可以看到在edituserprofile中所做的更改,但只要我退出userprofile并重新启动它,数据就会在userprofile中被清除,而不是从edituserprofile中清除!我希望userprofile保存、显示来自edituserprofile的数据,甚至用户退出并重新启动应用程序

下面是userprofile活动

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活动,效果非常好

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>



请帮忙

您使用的SharedReference是您两项活动的本地引用,如:

检索一个SharedReferences对象,以访问以下首选项: 这项活动是私人的

解决方案是将全局SharedReference用于:

 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

您正在使用两个活动的本地SharedReference,如:

检索一个SharedReferences对象,以访问以下首选项: 这项活动是私人的

解决方案是将全局SharedReference用于:

 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

一个主要的难题是,您在UserProfile中使用的是
getPreferences()
,而在EditUserProfile中使用的是
getSharedReferences()
。第一种方法仅获取UserProfile活动的键值对,而第二种方法用于访问应用程序的任何部分。将
getPreferences()
切换到
getSharedReferences()
,您应该会很好

从该网站: 公共类计算扩展活动{ 公共静态最终字符串PREFS\u NAME=“MyPrefsFile”


一个主要的难题是,您在UserProfile中使用
getPreferences()
,而在EditUserProfile中使用
getSharedReferences()
。第一种方法仅获取UserProfile活动的键值对,而第二种方法用于访问应用程序的任何部分。切换
getPreferences()
getSharedReferences()
你应该很好

从该网站: 公共类计算扩展活动{ 公共静态最终字符串PREFS\u NAME=“MyPrefsFile”


在您的
UserProfile
类和其他所有更改中-

SharedPreferences SharedPreferences=getPreferences(模式\私人)

由此-

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

在你的
UserProfile
类和其他任何地方都会发生变化-

SharedPreferences SharedPreferences=getPreferences(模式\私人)

由此-

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

而且你很好!成功了!我只需要在UserProfile类中以SharedReferences=GetSharedReferences(Name,MODE_PRIVATE);displayMessage(SharedReferences.getString(“nameKey”),Tysm!成功了!我只需要在UserProfile类中以SharedReferences=GetSharedReferences(Name,MODE_PRIVATE)的形式完成;displayMessage(SharedReferences.getString(“nameKey”),这意味着如果我们想在活动中使用SharedReferences,我们必须使用getPreferences(),如果我们想在活动之间使用它,我们必须使用GetSharedReferences()…是这样吗?顺便说一句,tysm提供了帮助!它起作用了!您不必在单个活动中使用第一个,但它更有用。这些键值对将仅对该活动可用。
GetSharedReferences()
创建可用于整个应用程序的对。当然。android网站说,
getSharedReferences()
用于“如果需要通过名称标识的多个首选项文件,请使用第一个参数指定。”这意味着,假设您希望两个人能够登录。这意味着两个用户名和两个与这些内容相关的其他任何内容。而不是说类似于
editor.putString(Name1,usernameString);
editor.putString(Name2,usernameString);
,您可以只打开两个共享首选项文件。
getSharedReferences(“第一个用户”,0);
getSharedReferences(“第二个用户”,0);
。这样,您就可以使用代码中使用的相同常量字符串,但使用不同的文件。
editor.putString(Name1,usernameString)
意味着,是的,您使用相同的常量字符串,但打开哪个编辑器将决定您获取的数据这意味着如果我们要在活动中使用SharedReferences,我们必须使用getPreferences(),如果我们要在活动之间使用它,我们必须使用GetSharedReferences()…是这样吗?顺便说一句,tysm提供了帮助!它起作用了!您不必在单个活动中使用第一个,但它更有用。这些键值对将仅对该活动可用。
GetSharedReferences()
创建可用于整个应用程序的对。当然。android网站说,
getSharedReferences()
用于“如果需要通过名称标识的多个首选项文件,请使用第一个参数指定。”这意味着,假设您希望两个人能够登录,这意味着两个用户名和两个与之相关的其他任何东西