2015-08-06 3 views
1

Может кто-нибудь помочь мне понять, как использовать OnPause() и OnResume() в этом коде? Я пытаюсь сохранить последнее выбранное или захваченное изображение в imageView, поэтому, когда пользователь закрывает программу и возвращается снова, ему не нужно снова устанавливать или снимать изображение.Сохранить изображение Открыть

package com.example.thang.sdcardimagesactivity; 

public class MainActivity extends Activity { 

private static final int REQUEST_CODE = 1; 
private Bitmap bitmap; 
Button button; 
ImageView imageView; 
String selectedImagePath; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    button=(Button) findViewById(R.id.click); 
    imageView=(ImageView) findViewById(R.id.image); 
    imageView.setOnLongClickListener(new View.OnLongClickListener() { 
     @Override 
     public boolean onLongClick(View v) { 
      Switch(); 
      return true; 
     } 
    }); 
} 
public void Switch(){ 
    Intent intent = new Intent(); 
    intent.setType("image/*"); 
    intent.setAction(Intent.ACTION_GET_CONTENT); 
    startActivityForResult(Intent.createChooser(intent,"Select Picture"), REQUEST_CODE); 
} 

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (requestCode==REQUEST_CODE&&resultCode== Activity.RESULT_OK){ 
     try{ 
      Uri selectedImage = data.getData(); 
      String[] filePathColumn = {MediaStore.Images.Media.DATA}; 
      Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null); 
      cursor.moveToFirst(); 
      int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 
      String filePath = cursor.getString(columnIndex); 
      Log.v("roni", filePath); 
      cursor.close(); 
      if(bitmap != null && !bitmap.isRecycled()) 
      { 
       bitmap = null; 
      } 
      bitmap = BitmapFactory.decodeFile(filePath); 
      //imageView.setBackgroundResource(0); 
      imageView.setImageBitmap(bitmap); 
     }catch (Exception e){ 
      e.printStackTrace(); 
     } 
    } 
} 

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 
    SharedPreferences.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(); 
} 

@Override 
protected void onResume() { 
    SharedPreferences sp = getSharedPreferences("AppSharedPref", 1); 
    selectedImagePath = sp.getString("ImagePath", ""); 
    Bitmap myBitmap = BitmapFactory.decodeFile(selectedImagePath); 
    imageView.setImageBitmap(myBitmap); 
    super.onResume(); 
} 
} 

View Activity 


public class ViewActivity extends Activity { 
ImageButton imageViews; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_view); 
    imageViews = (ImageButton) findViewById(R.id.image); 
    // textView=(TextView) findViewById(R.id.textview); 
    Intent intent = getIntent(); 
    Uri data = intent.getData(); 

    if (intent.getType().indexOf("image/") != -1) 
    { 
     imageViews.setImageURI(data); 
    } 
    setResult(RESULT_OK, intent); 
    Bundle bundle=new Bundle(); 
    bundle.putInt("image",R.id.image); 
    intent.putExtras(bundle); 
    finish(); 
} 
    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); 
    } 
} 
+0

Вы хотите выбрать изображение из галереи камер и устройств? –

+0

Не могу понять ваш путь. Вы хотите захватить изображение при щелчке изображения? и хотите установить захваченное изображение как src изображения? –

ответ

0

Вы можете сохранить изображение на SD-карте, чтобы его можно было постоянно получать. Лучше всего это сделать сразу в методе onActivityResult().

File imagesFolder = new File(Environment.getExternalStorageDirectory(), "ImagesFolder"); 
File file = new File(imagesFolder, "image.jpg"); 
String fileName = file.getAbsolutePath(); 
try { 
    FileOutputStream out = new FileOutputStream(file); 
    squareBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out); 
    out.flush(); 
    out.close(); 
} catch (Exception e) { 
    Log.e("Image", "Convert"); 
} 

И загрузить его обратно при перезапуске приложения (в OnCreate или предпочтительно в onResume):

try { 
    File imagesFolder = new File(Environment.getExternalStorageDirectory(), "ImagesFolder"); 
    if (!imagesFolder.exists()) 
     imagesFolder.mkdirs(); 
    if (new File(imagesFolder, "image.jpg").exists()) { 
     String fileName = new File(imagesFolder, "image.jpg").getAbsolutePath(); 
     Bitmap bitmap = BitmapFactory.decodeFile(fileName); 
     ImageView imageView = (ImageView) findViewById(R.id.image_view); 
     imageView.setImageBitmap(bitmap); 
    } 
} catch (NullPointerException e) { 
    Log.e("Exception", "null"); 
} 

Конечно, вы можете изменить имя папки и изображения.