0
在我的應用程序中,我想使用默認圖像配置文件製作個人資料頁面,並允許用戶通過從相機拍攝照片或從圖庫中選擇圖片進行更改,我成功完成了此操作,這裏是我的代碼:分享偏好來保存個人資料圖片
public class MainActivity extends AppCompatActivity {
private static final int pick = 1, capture = 2;
Uri imgeUri, touri;
ImageView imp;
SharedPreferences sh;
SharedPreferences.Editor editor;
String S;
boolean d=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("eee","in resume");
setContentView(R.layout.activity_main);
sh = getSharedPreferences("my" ,Context.MODE_PRIVATE);
editor=sh.edit();
imp = (ImageView) findViewById(R.id.profile_image);
if(d==false) {
imp.setImageResource(R.drawable.photo);
}
else{
imp.setImageURI(Uri.parse(sh.getString("link", null)));
}
}
public void changepic(View V) {
final String[] items = {"Take picture", "Choose Picture",
"cancle"};
AlertDialog.Builder build = new AlertDialog.Builder(this);
build.setTitle("Add Photo");
build.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (items[which].equals("Choose Picture")) {
Log.d("test","bh");
Intent i = new Intent(Intent.ACTION_PICK);
i.setType("image/*");
startActivityForResult(i, pick);
} else if (items[which].equals("Take picture")) {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, capture);
}
}
}).create().show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == pick && resultCode == RESULT_OK) {
imgeUri = data.getData();
Log.d("test","pick");
imp.setImageURI(imgeUri);
editor.putString("link",String.valueOf(imgeUri));
//Log.d("test",f);
editor.commit();
d=true;
} else if (requestCode == capture && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
imp.setImageBitmap(imageBitmap);
}
}
但問題是,選擇圖像我將它保存在共享偏好時,我'在活動時去到另一個,並返回這個消失,活動顯示默認的圖像的圖像看起來只是罰款時,我知道它的原因,因爲每次我回到配置文件活動時,都會再次創建,並且布爾變量d再次爲false。 我該如何解決,當我必須調用獲取偏好。