Android 如何:在SD卡中存储图像,在配置文件Pic的SharedReferences中存储并获取图像路径
个人资料图片可以选择和设置一段时间,但我们通常想要的(第一个对象)是当用户重新启动该页面时,应该有一个用户以前设置的图像,如果用户没有设置该图像,应该有默认图像。我已经将SharedReferences用于文本视图,但据说对于图像视图,通常最好先将选定的图像存储在SD卡中,然后获取该Uri,将其设置为字符串,然后将其用于SharedReferences。我不知道是否可以通过onPause和onResume来完成!如果是这样,那么应该选择哪种方式?如何做到这一点?另一件事是(第二个对象),我有一个活动,即用户配置文件,我想从编辑配置文件活动中放大数据(这里是用户选择的配置文件pic)。这里的情况与编辑配置文件相同,如果用户没有设置自定义配置文件pic,那么应该有默认pic。以下是我的编辑配置文件活动:Android 如何:在SD卡中存储图像,在配置文件Pic的SharedReferences中存储并获取图像路径,android,sharedpreferences,Android,Sharedpreferences,个人资料图片可以选择和设置一段时间,但我们通常想要的(第一个对象)是当用户重新启动该页面时,应该有一个用户以前设置的图像,如果用户没有设置该图像,应该有默认图像。我已经将SharedReferences用于文本视图,但据说对于图像视图,通常最好先将选定的图像存储在SD卡中,然后获取该Uri,将其设置为字符串,然后将其用于SharedReferences。我不知道是否可以通过onPause和onResume来完成!如果是这样,那么应该选择哪种方式?如何做到这一点?另一件事是(第二个对象),我有一个
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;
}
}
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;
}
}
以下是“用户配置文件”活动,在该活动中,我希望从“编辑配置文件”活动中放大默认或自定义配置文件pic,就像我能够放大其余文本视图一样:
public class UserProfile extends AppCompatActivity {
SharedPreferences sharedpreferences;
public static final String Uimage = "Uimage";
public static final String Name = "nameKey";
public static final String UContact = "UContact";
public static final String Uemail = "Uemail";
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 = getSharedPreferences(Uimage, MODE_PRIVATE);
sharedpreferences = getSharedPreferences(Name, MODE_PRIVATE);
sharedpreferences = getSharedPreferences(UContact, MODE_PRIVATE);
sharedpreferences = getSharedPreferences(Uemail, MODE_PRIVATE);
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;
}
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(Name);
String Result_UContact = data.getStringExtra(UContact);
String Result_UEmail = data.getStringExtra(Uemail);
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);
}
}
请考虑我在编程、编码或Android开发方面没有经验,我刚刚开始学习!p> 你说得对。您可以将图像存储在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()方法中处理这些问题
希望有帮助 你说得对。您可以将图像存储在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.存储一些字符串时,单击“保存”按钮时存储它们是有意义的:
// 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.加载这些值(例如,在设置内容后在ur onCreate()方法中):
从SharedReferences加载值始终需要第二个参数,这将是在没有为此键保存任何内容时的结果。例如,如果您的应用程序是第一次启动的,并且用户没有在EditText中输入任何内容,则“尚未输入任何名称”等将从SharedReferences加载
和。。到目前为止就是这样。
为什么我没有提供有关如何在SharedReferences中存储位图的信息?
-SharedReferences只能存储基本类型,如浮点型、整数型、字符串型和布尔型
-您可以将图像保存到sd卡中,但请记住:并非所有设备都使用sd卡。如果您的应用程序使用相机意图,则您的foto已自动保存在库中。您可以将此路径作为字符串存储在sharedPrefs中。我没有多少时间来编写整个答案,但下面是如何将一些字符串存储到应用程序共享首选项中: 1.存储一些字符串时,单击“保存”按钮时存储它们是有意义的:
// 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.加载这些值(例如,在设置内容后在ur onCreate()方法中):
从SharedReferences加载值始终需要第二个参数,这将是在没有为此键保存任何内容时的结果。例如,如果您的应用程序是第一次启动的,并且用户没有在EditText中输入任何内容,则“尚未输入任何名称”等将从SharedReferences加载
和。。到目前为止就是这样。
为什么我没有提供有关如何在SharedReferences中存储位图的信息?
-SharedReferences只能存储基本类型,如浮点型、整数型、字符串型和布尔型
-您可以将图像保存到sd卡中,但请记住:并非所有设备都使用sd卡。如果您的应用程序使用相机意图,则您的foto已自动保存在库中。您可以将此路径作为字符串存储在SharedPref中。我们可以使用如下方法检索所选图像的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);
}
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Uimage, stringUri);
editor.apply();
@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;
}
}
@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);
}
}
所以现在我们有了一个字符串,它表示或已经存储了我们所选图像的Uri值。
接下来,将此字符串用于SharedReference,如下所示:
@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);
}
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Uimage, stringUri);
editor.apply();
@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;
}
}
@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);
}
}
Uimage是键,它带有字符串值stringUri!每次用户更改配置文件pic时,我们都会同时更新Uimage和关联的stringUri。
现在,在onCreate方法中,我们将检查是否有具有此值的SharedReferences可用,如果有,那么我们希望显示所选图像。这里需要注意的是,SharedReferences用于在重新启动应用程序期间保存和保留原始数据。Editor.putString用于存储某些值,SharedReferences.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 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);
}
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Uimage, stringUri);
editor.apply();
@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;
}
}
@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);
}
}
..并在用户配置文件活动中阅读和处理此意图,如下所示:
@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);
}
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Uimage, stringUri);
editor.apply();
@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;
}
}
@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);
}
}
其中:
public void displayUimage (String imageString){
ImageView importImage = (ImageView) findViewById(R.id.importImage);
imageString = sharedpreferences.getString(Uimage, "");
uriString = Uri.parse(imageString);
importImage.setImageURI(uriString);
}
意图用于从编辑配置文件活动到用户配置文件活动获取pic。如果我们按back或退出应用程序并重新启动