2 clcurie 11 clcurie_11 于 2013.07.31 11:37 提问

使用Shared Preferences如何把多幅图像保存在ImageView中?

在一个activity中有两个ImageViews,用户可以长按一个 ImageView ,就可以从 camera gallery 中选择获取任何图像。我想保存这些图像的路径,所以当用户再次打开或关闭程序时,图像仍在imageView中,这是为什么呢?

这是 imageView所在的Activity A :

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
    if (requestCode == SELECT_PICTURE) {
    Uri selectedImageUri = data.getData();
    selectedImagePath = getPath(selectedImageUri);
    System.out.println("Image Path : " + selectedImagePath);
    im1.setImageURI(selectedImageUri);}}}

public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);};

    @Override
protected void onPause() {
    SharedPreferences sp = getSharedPreferences("AppSharedPref", 1); // Open SharedPreferences with name AppSharedPref
    Editor editor = sp.edit();
    editor.putString("ImagePath", selectedImagePath); // Store selectedImagePath with key "ImagePath". This key will be then used to retrieve data.         
    editor.commit();
    super.onPause();
    }   

protected void onResume1() {
    SharedPreferences sp = getSharedPreferences("AppSharedPref", 1);
    selectedImagePath = sp.getString("ImagePath", "");
    super.onResume();
    }

Activity B 获取 cam gallery图片,然后发送到 Activity A

 Button send = (Button) findViewById(R.id.send);
    send.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            Intent intent=new Intent();
            setResult(RESULT_OK, intent);
            Bundle bundle=new Bundle();
            bundle.putInt("image",R.id.showImg);
            intent.putExtras(bundle);
            finish();  }
            });
 public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            Uri selectedImageUri = data.getData();
            selectedImagePath = getPath(selectedImageUri);
            System.out.println("Image Path : " + selectedImagePath);
            img.setImageURI(selectedImageUri);
        }}}
 public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
    }
Csdn user default icon
上传中...
上传图片
插入图片