如何:在spcard中存储图像,在Profile Pic的共享偏好中存储和获取imagepath

时间:2016-04-08 17:08:58

标签: android sharedpreferences

可以选择和设置配置文件图片一段时间,但我们通常想要的(第一个对象)是当用户重新启动该页面时,应该有用户先前设置的图像,如果用户没有设置该图像,应该有默认图像。我已经对文本视图使用了共享首选项,但据说对于图像视图,通常最好先将所选图像存储在SD卡中,然后获取该Uri,使其成为字符串,然后将其用于共享首选项。我不知道它是否可以通过onPause和onResume来完成!如果是这样,那么哪种方式更适合?以及如何做到这一点?另一件事是(第二个对象)我有一个活动,即用户个人资料,我想从编辑个人资料活动中膨胀数据(这里,用户选择的个人资料图片)。这与编辑配置文件的情况相同,如果用户没有设置自定义配置文件pic,则应该有默认pic。以下是我的编辑个人资料活动:

type Tagged[U] = { type Tag = U }
type @@[T, U] = T with Tagged[U]

trait Kilogram
trait Meter
type Kg = Double @@ Kilogram
type M = Double @@ Meter

def bmi(mass: Kg, height: M): Double = mass / pow(height, 2)  

以下是用户个人资料活动,其中我想要从编辑个人资料活动中提升默认或自定义个人资料照片,就像我能够夸大其余文字观看一样:

public class EditUserProfile extends AppCompatActivity {

    private CoordinatorLayout coordinatorLayout;
    public static final String Uimage = "Uimage";
    public static final String Name = "nameKey";
    public static final String UContact = "UContact";
    public static final String Uemail = "Uemail";
    private TextInputLayout inputLayoutName, inputLayoutEmail, inputLayoutContact;
    private EditText usernameTextView, userEmailTextView, userContactTextView;
    private ImageView userImageView;
    SharedPreferences sharedpreferences;
    private int PICK_IMAGE_REQUEST = 1;

    @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);

        inputLayoutName = (TextInputLayout) findViewById(R.id.input_layout_username);
        inputLayoutEmail = (TextInputLayout) findViewById(R.id.input_layout_useremail);
        inputLayoutContact = (TextInputLayout) findViewById(R.id.input_layout_usercontact);

        userImageView = (ImageView) findViewById(R.id.userImage );
        usernameTextView = (EditText) findViewById(R.id.username);
        userContactTextView = (EditText) findViewById(R.id.usercontact);
        userEmailTextView = (EditText) findViewById(R.id.useremail);

        Button btnSave = (Button) findViewById(R.id.action_save);

        sharedpreferences = getSharedPreferences(Uimage, Context.MODE_PRIVATE);
        sharedpreferences = getSharedPreferences(Name, Context.MODE_PRIVATE);
        sharedpreferences = getSharedPreferences(UContact, Context.MODE_PRIVATE);
        sharedpreferences = getSharedPreferences(Uemail, Context.MODE_PRIVATE);

        if (sharedpreferences.contains(Name)) {
            usernameTextView.setText(sharedpreferences.getString(Name, ""));
        }
        if (sharedpreferences.contains(UContact)) {
            userContactTextView.setText(sharedpreferences.getString(UContact, ""));
        }
        if (sharedpreferences.contains(Uemail)) {
            userEmailTextView.setText(sharedpreferences.getString(Uemail, ""));
        }

        usernameTextView.addTextChangedListener(new MyTextWatcher(usernameTextView));
        userEmailTextView.addTextChangedListener(new MyTextWatcher(userEmailTextView));
        userContactTextView.addTextChangedListener(new MyTextWatcher(userContactTextView));

        coordinatorLayout = (CoordinatorLayout) findViewById(R.id
               .coordinatorLayout);

        final ImageButton button = (ImageButton) findViewById(R.id.editImage);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click

                Intent intent = new Intent();
                // Show only images, no videos or anything else
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                // Always show the chooser (if there are multiple options available)
                startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

            Uri uri = data.getData();

            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
                // Log.d(TAG, String.valueOf(bitmap));
                userImageView.setImageBitmap(bitmap);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * Validating form
     */

    private boolean submitForm() {
        if (!validateName()) {
            return false;
        }

        if (!validateContact()) {
            return false;
        }

        if (!validateEmail()) {
            return false;
        }

        Snackbar snackbar = Snackbar
                .make(coordinatorLayout, "Saved!", Snackbar.LENGTH_LONG);

        snackbar.show();

        return true;
    }

    private boolean validateName() {
        if (usernameTextView.getText().toString().trim().isEmpty()) {
            inputLayoutName.setError(getString(R.string.err_msg_name));
            requestFocus(usernameTextView);
            return false;
        } else {
            inputLayoutName.setError(null);
        }

        return true;
    }

    private boolean validateEmail() {
        String email = userEmailTextView.getText().toString().trim();

        if (email.isEmpty() || !isValidEmail(email)) {
            inputLayoutEmail.setError(getString(R.string.err_msg_email));
            requestFocus(userEmailTextView);
            return false;
        } else {
            inputLayoutEmail.setError(null);
        }

        return true;
    }

    private boolean validateContact() {
        if (userContactTextView.getText().toString().trim().isEmpty()) {
            inputLayoutContact.setError(getString(R.string.err_msg_contact));
            requestFocus(userContactTextView);
            return false;
        } else {
            inputLayoutContact.setError(null);
        }

        return true;
    }

    private static boolean isValidEmail(String email) {
        return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
    }

    private void requestFocus(View view) {
        if (view.requestFocus()) {
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }
    }

    private class MyTextWatcher implements TextWatcher {

        private View view;

        private MyTextWatcher(View view) {
            this.view = view;
        }

        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        public void afterTextChanged(Editable editable) {
            switch (view.getId()) {
                case R.id.username:
                    validateName();
                    break;
                case R.id.useremail:
                    validateEmail();
                    break;
                case R.id.usercontact:
                    validateContact();
                    break;
            }
        }
    }

    @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:

              if (!submitForm()){

                  return false;
              }

                TextView usernameTextView = (TextView) findViewById(R.id.username);
                String usernameString = usernameTextView.getText().toString();

                SharedPreferences.Editor editor = sharedpreferences.edit();
                editor.putString(Name, usernameString);
                editor.apply();

                TextView ucontactTV = (TextView) findViewById(R.id.usercontact);
                String uContactS = ucontactTV.getText().toString();

                editor.putString(UContact, uContactS);
                editor.apply();

                TextView uEmailTV = (TextView) findViewById(R.id.useremail);
                String uEmailS = uEmailTV.getText().toString();

                editor.putString(Uemail, uEmailS);
                editor.apply();

                Snackbar snackbar = Snackbar
                        .make(coordinatorLayout, "Saved!", Snackbar.LENGTH_LONG);

                snackbar.show();

                Intent userProfileIntent = new Intent(EditUserProfile.this, UserProfile.class);
                userProfileIntent.putExtra(Name, usernameString);
                userProfileIntent.putExtra(UContact, uContactS);
                userProfileIntent.putExtra(Uemail, uEmailS);

                setResult(RESULT_OK, userProfileIntent);
                finish();

        }
        return true;
    }

}

请考虑我没有编程,编码或Android开发的经验,我刚刚开始学习它!

3 个答案:

答案 0 :(得分:1)

你是对的。您可以将图像存储在SD卡中,然后使用uri加载图像。

您可以考虑将图像uri保存在存储的首选项中。有了这个,你只需要处理两个案例。

在你的onCreate()方法中

 - Check if the image uri is valid (image exist)
 - If it does, load it and make it the display image
 - If it is missing, load the default image
 * Alternatively, you can set the default image as the image for the imageview

每当用户更新图片时

 - Store the image into the sd card
 - Update your shared preference 

因此,您不需要在onPause()和onResume()方法中处理这些。

希望它有所帮助!

答案 1 :(得分:1)

我没有多少计时器来编写整个答案,但这里是如何将一些字符串存储到应用程序共享首选项: 1.存储一些字符串,当你单击" save" -button时存储它们是有意义的:

// assume a,b,c are strings with the information from ur edittexts to be saved:
String a,b,c;
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sp.edit();
editor.putString("namekey",a);
editor.putString("UContact", b);
editor.putString("UEmail", c);
editor.commit();

现在保存了这三件事。 2.加载这些值(例如在设置内容后的on onCreate()方法中):

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
// check if the namevalues "namekey", "UContact", "UEmail" have values saved in the sharedPreferences. If not, load defaultvalue 
String user_name = sp.getString("namekey", "no name entered yet");
String user_email = sp.getString("UEmail", "no email entered yet");
String user_contact = sp.getString("UContact", "no Contact entered yet");
displayMessage(user_name);
displayUContact(user_contact);
displayUEmail(user_email);

从sharedPreferences加载一个值总是需要第二个参数,这个结果是没有为此键保存任何内容的结果。例如,如果您的应用程序是第一次启动,并且用户没有在edittexts中输入任何内容,那么"尚未输入名称"等等,从sharedPreferences加载。

和...到目前为止。 为什么我没有提供有关如何在sharedPreferences中存储位图的信息? - sharedPreferences只能存储基本类型,如Float,Integer,String,Boolean - 您可以将图像保存到SD卡中,但请记住:并非每台设备都使用SD卡。如果您的应用程序使用相机意图,则您的照片已自动保存在库中。您可以将此路径存储为sharedPrefs中的String。

答案 2 :(得分:0)

我们可以使用方法检索所选图像的Uri,如下所示:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

        Uri uri = data.getData();

        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
            // CALL THIS METHOD TO GET THE ACTUAL PATH
            File finalFile = new File(getRealPathFromURI(uri));

            outputFileUri = Uri.fromFile(finalFile);

            stringUri = outputFileUri.toString();
            // Log.d(TAG, String.valueOf(bitmap));
            userImageView.setImageBitmap(bitmap);

            SharedPreferences.Editor editor = sharedpreferences.edit();
            editor.putString(Uimage, stringUri);
            editor.apply();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public String getRealPathFromURI(Uri uri) {
    Cursor cursor = getContentResolver().query(uri, null, null, null, null);
    cursor.moveToFirst();
    int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
    return cursor.getString(idx);
}

所以现在我们有一个String代表或已经存储了我们所选图像的Uri值。 接下来是将此字符串用于sharedpreferences,如下所示:

    SharedPreferences.Editor editor = sharedpreferences.edit();
    editor.putString(Uimage, stringUri);
    editor.apply();

Uimage是关键,它有字符串值stringUri!每次用户更改配置文件时,我们都会同时更新Uimage和相关的stringUri。 现在,在onCreate方法中,我们将检查是否存在此值的共享首选项,如果是,则我们要显示所选图像。这里应该注意,共享偏好用于在重新启动应用程序时保存和保留原始数据。 Editor.putString用于存储一些值,sharedpreferences.getString用于读取该值。

if (sharedpreferences.contains(Uimage)){
    String imagepath = sharedpreferences.getString(Uimage, "");
    uriString = Uri.parse(imagepath);
    userImageView.setImageURI(uriString);
}

uriString是Uri! 它奏效了! 接下来是将此配置文件pic发送到用户配置文件活动。我们将使用intent将选定的pic发送到用户配置文件活动和用户配置文件活动的onCreate方法中的共享偏好,以便在重新启动时保存并保留该pic,如下所示: 1.使用编辑个人资料活动中的意图将pic发送到用户个人资料活动,如下所示:

   @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_save:


                Snackbar snackbar = Snackbar
                        .make(coordinatorLayout, "Saved!", Snackbar.LENGTH_LONG);

                snackbar.show();

                Intent userProfileIntent = new Intent(EditUserProfile.this, UserProfile.class);


                if (sharedpreferences.contains(stringUri)){

                    userProfileIntent.putExtra(Uimage, stringUri);
                }

                setResult(RESULT_OK, userProfileIntent);
                finish();

        }
        return true;
    }

....并在用户个人资料活动中阅读并处理此意图,如下所示:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {

            case Edit_Profile:
                if (resultCode == RESULT_OK) {

                    String imageIntent = data.getStringExtra(Uimage);

                    displayUimage(imageIntent);
                }

                break;
        }
    }

其中:

 public void displayUimage (String imageString){
        ImageView importImage = (ImageView) findViewById(R.id.importImage);
        imageString = sharedpreferences.getString(Uimage, "");
        uriString = Uri.parse(imageString);
        importImage.setImageURI(uriString);

    }

Intent用于从编辑个人资料活动到用户个人资料活动获取图片。如果我们按下或退出应用并重新启动它,用户个人资料活动将丢失该图片。为了在重新启动应用程序时保存并保留该图片,我们需要在那里使用共享偏好。

  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);
    
    importImage = (ImageView) findViewById(R.id.importImage);
    
    importImage.setImageResource(R.drawable.defaultprofilepic);
    
    sharedpreferences = getSharedPreferences(Uimage, MODE_PRIVATE);
    
    if (sharedpreferences.contains(Uimage)){
        String imagepath = sharedpreferences.getString(Uimage, "");
        uriString = Uri.parse(imagepath);
        importImage.setImageURI(uriString);
    }
    
    }
    
  2. 我们首先使用默认值初始化了我们的importImage,然后检查是否存在具有特殊键的共享偏好。

    这仅仅意味着,如果共享偏好包含Uimage(只有当用户更改了配置文件时才有可能,并且只要用户更改配置文件图片时Uimage将始终更新),那么我们将获得该图像的Uri将其设置为importImage,以便我们将具有与用户在编辑个人资料活动中选择的相同的个人资料图片。

    以下是完整的编辑个人资料活动:

    public class EditUserProfile extends AppCompatActivity {
    
        private CoordinatorLayout coordinatorLayout;
    
        public static final String Uimage = "Uimagepath";
        public static final String Name = "nameKey";
        public static final String UContact = "UContact";
        public static final String Uemail = "Uemail";
    
        private TextInputLayout inputLayoutName, inputLayoutEmail, inputLayoutContact;
        private EditText usernameTextView, userEmailTextView, userContactTextView;
        private ImageView userImageView;
    
        SharedPreferences sharedpreferences;
        private int PICK_IMAGE_REQUEST = 1;
    
        String stringUri;
        Uri outputFileUri;
        Uri uriString;
    
        @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);
    
            inputLayoutName = (TextInputLayout) findViewById(R.id.input_layout_username);
            inputLayoutEmail = (TextInputLayout) findViewById(R.id.input_layout_useremail);
            inputLayoutContact = (TextInputLayout) findViewById(R.id.input_layout_usercontact);
    
            userImageView = (ImageView) findViewById(R.id.userImage );
            usernameTextView = (EditText) findViewById(R.id.username);
            userContactTextView = (EditText) findViewById(R.id.usercontact);
            userEmailTextView = (EditText) findViewById(R.id.useremail);
    
            Button btnSave = (Button) findViewById(R.id.action_save);
    
            sharedpreferences = getSharedPreferences(Uimage, Context.MODE_PRIVATE);
            sharedpreferences = getSharedPreferences(Name, Context.MODE_PRIVATE);
            sharedpreferences = getSharedPreferences(UContact, Context.MODE_PRIVATE);
            sharedpreferences = getSharedPreferences(Uemail, Context.MODE_PRIVATE);
    
            if (sharedpreferences.contains(Uimage)){
                String imagepath = sharedpreferences.getString(Uimage, "");
                uriString = Uri.parse(imagepath);
                userImageView.setImageURI(uriString);
            }
    
            if (sharedpreferences.contains(Name)) {
                usernameTextView.setText(sharedpreferences.getString(Name, ""));
            }
            if (sharedpreferences.contains(UContact)) {
                userContactTextView.setText(sharedpreferences.getString(UContact, ""));
            }
            if (sharedpreferences.contains(Uemail)) {
                userEmailTextView.setText(sharedpreferences.getString(Uemail, ""));
            }
    
            usernameTextView.addTextChangedListener(new MyTextWatcher(usernameTextView));
            userEmailTextView.addTextChangedListener(new MyTextWatcher(userEmailTextView));
            userContactTextView.addTextChangedListener(new MyTextWatcher(userContactTextView));
    
            coordinatorLayout = (CoordinatorLayout) findViewById(R.id
                   .coordinatorLayout);
    
            final ImageButton button = (ImageButton) findViewById(R.id.editImage);
            button.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    // Perform action on click
    
                    Intent intent = new Intent();
                    // Show only images, no videos or anything else
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    // Always show the chooser (if there are multiple options available)
                    startActivityForResult(Intent.createChooser(intent, "Select Pic from"), PICK_IMAGE_REQUEST);
                }
            });
        }
    
        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
    
            if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
    
                Uri uri = data.getData();
    
                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
                    // CALL THIS METHOD TO GET THE ACTUAL PATH
                    File finalFile = new File(getRealPathFromURI(uri));
    
                    outputFileUri = Uri.fromFile(finalFile);
    
                    stringUri = outputFileUri.toString();
                    // Log.d(TAG, String.valueOf(bitmap));
                    userImageView.setImageBitmap(bitmap);
    
                    SharedPreferences.Editor editor = sharedpreferences.edit();
                    editor.putString(Uimage, stringUri);
                    editor.apply();
    
    
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
        }
    
        public String getRealPathFromURI(Uri uri) {
            Cursor cursor = getContentResolver().query(uri, null, null, null, null);
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            return cursor.getString(idx);
        }
    
        /**
         * Validating form
         */
    
        private boolean submitForm() {
            if (!validateName()) {
                return false;
            }
    
            if (!validateContact()) {
                return false;
            }
    
            if (!validateEmail()) {
                return false;
            }
    
            Snackbar snackbar = Snackbar
                    .make(coordinatorLayout, "Saved!", Snackbar.LENGTH_LONG);
    
            snackbar.show();
    
            return true;
        }
    
        private boolean validateName() {
            if (usernameTextView.getText().toString().trim().isEmpty()) {
                inputLayoutName.setError(getString(R.string.err_msg_name));
                requestFocus(usernameTextView);
                return false;
            } else {
                inputLayoutName.setError(null);
            }
    
            return true;
        }
    
        private boolean validateEmail() {
            String email = userEmailTextView.getText().toString().trim();
    
            if (email.isEmpty() || !isValidEmail(email)) {
                inputLayoutEmail.setError(getString(R.string.err_msg_email));
                requestFocus(userEmailTextView);
                return false;
            } else {
                inputLayoutEmail.setError(null);
            }
    
            return true;
        }
    
        private boolean validateContact() {
            if (userContactTextView.getText().toString().trim().isEmpty()) {
                inputLayoutContact.setError(getString(R.string.err_msg_contact));
                requestFocus(userContactTextView);
                return false;
            } else {
                inputLayoutContact.setError(null);
            }
    
            return true;
        }
    
        private static boolean isValidEmail(String email) {
            return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
        }
    
        private void requestFocus(View view) {
            if (view.requestFocus()) {
                getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
            }
        }
    
        private class MyTextWatcher implements TextWatcher {
    
            private View view;
    
            private MyTextWatcher(View view) {
                this.view = view;
            }
    
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }
    
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }
    
            public void afterTextChanged(Editable editable) {
                switch (view.getId()) {
                    case R.id.username:
                        validateName();
                        break;
                    case R.id.useremail:
                        validateEmail();
                        break;
                    case R.id.usercontact:
                        validateContact();
                        break;
                }
            }
        }
    
        @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:
    
                  if (!submitForm()){
    
                      return false;
                  }
    
                    SharedPreferences.Editor editor = sharedpreferences.edit();
    
                    TextView usernameTextView = (TextView) findViewById(R.id.username);
                    String usernameString = usernameTextView.getText().toString();
    
                    editor.putString(Name, usernameString);
                    editor.apply();
    
                    TextView ucontactTV = (TextView) findViewById(R.id.usercontact);
                    String uContactS = ucontactTV.getText().toString();
    
                    editor.putString(UContact, uContactS);
                    editor.apply();
    
                    TextView uEmailTV = (TextView) findViewById(R.id.useremail);
                    String uEmailS = uEmailTV.getText().toString();
    
                    editor.putString(Uemail, uEmailS);
                    editor.apply();
    
                    Snackbar snackbar = Snackbar
                            .make(coordinatorLayout, "Saved!", Snackbar.LENGTH_LONG);
    
                    snackbar.show();
    
                    Intent userProfileIntent = new Intent(EditUserProfile.this, UserProfile.class);
    
                    userProfileIntent.putExtra(Name, usernameString);
                    userProfileIntent.putExtra(UContact, uContactS);
                    userProfileIntent.putExtra(Uemail, uEmailS);
    
                    if (sharedpreferences.contains(stringUri)){
    
                        userProfileIntent.putExtra(Uimage, stringUri);
                    }
    
                    setResult(RESULT_OK, userProfileIntent);
                    finish();
    
            }
            return true;
        }
    
    }
    

    以下是显示已保存个人资料的完整用户个人资料活动:

    public class UserProfile extends AppCompatActivity {
        SharedPreferences sharedpreferences;
    
        public static final String Uimage = "Uimagepath";
        public static final String Name = "nameKey";
        public static final String UContact = "UContact";
        public static final String Uemail = "Uemail";
        ImageView importImage;
        Uri uriString;
    
        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);
    
            importImage = (ImageView) findViewById(R.id.importImage);
    
            importImage.setImageResource(R.drawable.defaultprofilepic);
    
            sharedpreferences = getSharedPreferences(Uimage, MODE_PRIVATE);
            sharedpreferences = getSharedPreferences(Name, MODE_PRIVATE);
            sharedpreferences = getSharedPreferences(UContact, MODE_PRIVATE);
            sharedpreferences = getSharedPreferences(Uemail, MODE_PRIVATE);
    
            if (sharedpreferences.contains(Uimage)){
                String imagepath = sharedpreferences.getString(Uimage, "");
                uriString = Uri.parse(imagepath);
                importImage.setImageURI(uriString);
            }
    
            displayMessage(sharedpreferences.getString(Name, ""));
            displayUContact(sharedpreferences.getString(UContact, ""));
            displayUEmail(sharedpreferences.getString(Uemail, ""));
        }
    
        @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;
    
                case R.id.action_dos:
    
                    Intent coffeeIntent = new Intent(UserProfile.this, Dos.class);
    
                    UserProfile.this.startActivity(coffeeIntent);
    
                    return true;
    
                case R.id.action_13:
    
                    Intent teaIntent = new Intent(UserProfile.this, thirteen.class);
    
                    UserProfile.this.startActivity(teaIntent);
    
                    return true;
    
            }
            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 imageIntent = data.getStringExtra(Uimage);
                        String name = data.getStringExtra(Name);
                        String Result_UContact = data.getStringExtra(UContact);
                        String Result_UEmail = data.getStringExtra(Uemail);
    
                        displayUimage(imageIntent);
                        displayMessage(name);
                        displayUContact(Result_UContact);
                        displayUEmail(Result_UEmail);
                    }
    
                    break;
            }
        }
    
        public void displayMessage(String message) {
            TextView usernameTextView = (TextView) findViewById(R.id.importProfile);
            usernameTextView.setText(message);
        }
    
        public void displayUContact(String contact) {
            TextView userContactTextView = (TextView) findViewById(R.id.importContact);
            userContactTextView.setText(contact);
        }
    
        public void displayUEmail(String email) {
            TextView userEmailTextView = (TextView) findViewById(R.id.importEmail);
            userEmailTextView.setText(email);
        }
    
        public void displayUimage (String imageString){
            ImageView importImage = (ImageView) findViewById(R.id.importImage);
            imageString = sharedpreferences.getString(Uimage, "");
            uriString = Uri.parse(imageString);
            importImage.setImageURI(uriString);
    
        }
    
    }
    

    希望这有助于某人!