How do I save an image from the gallery and load it into the activity?

3

I would like to know how to save an image from the gallery and load the activity in version 2.3.3 of the Eclipse emulator, because my code only works when I test it on my Android 4.1 device and even then when I load a large image it leaves a huge white space at the top and bottom of the image.

My code goes below:

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


    Log.i("AQUI!", "Entrou no onActivityResult");
    //Detects request codes
    if(requestCode == RESULT_LOAD_IMAGE && resultCode == Activity.RESULT_OK) {
        Log.i("AQUI!", "Entrou no IF");
        Uri selectedImage = data.getData();
        Bitmap bitmap = null;
        try {
                bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
                Log.i("AQUI!", "Bitmap recebeu a imagem");
                imguser.setImageBitmap(bitmap);
        } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
        } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
        }
    }
}

public void onClick(View v) {
    // TODO Auto-generated method stub

    if(v.getId() == R.id.btneditar) {
        String filename = "profile.jpg";
        // cria o arquivo
        File file = new File(Environment.getExternalStorageDirectory(), filename);

        Intent cropIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
        cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        cropIntent.putExtra("crop", "true");            
        cropIntent.putExtra("aspectX", 1);
        cropIntent.putExtra("aspectY", 1);
        cropIntent.putExtra("scale", true);
        cropIntent.putExtra("outputX", 500);
        cropIntent.putExtra("outputY", 500);
        cropIntent.putExtra("return-data", false);

        startActivityForResult(cropIntent, RESULT_LOAD_IMAGE);
    }
}

When I run the emulator I get the following Log error:

01-23 18:31:36.146: E/AndroidRuntime(336): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { act=file:///mnt/sdcard/profile.jpg (has extras) }} to activity {com.example.meuapp/com.example.meuapp.atividades.EditarContaActivity}: java.lang.NullPointerException

Thanks to the Log.i's that I used in my code I discovered that the error is in this line:

bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);

this.getContentResolver() is returning null , but this error only occurs in the Android 2.3.3 emulator, it already runs on my device (Android 4.1).

    
asked by anonymous 24.01.2016 / 21:22

1 answer

2

Well, staff problem solved completely, it now causes no error and the images are displayed exactly the same size as the previous image had before. Of course the code is still not well structured, but it serves as the basis for solving a problem like this. In this my solution I add in the AndroidManifest permission: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> . And include a logic to know if I have permission to read and save files. For the blanks I used an attribute in the imageview's xml which is: android:scaleType="centerCrop" . And to leave the loaded images the same size as the previous one I reconfigured the layout parameters of the imageview picking up the imageview and setting it back as an absolute value, since it was previously "WRAP_CONTENT". Below is my solution hope it helps someone or someone help improve it.

public class EditarContaActivity extends Activity implements OnClickListener {

private static int RESULT_LOAD_IMAGE = 1;    
Button btneditar1;
File file;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);        

    imguser = (ImageView)findViewById(R.id.imgdefault_user);

    btneditar = (Button)findViewById(R.id.btneditar);
    btneditar1.setOnClickListener(this);      

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_editarconta, menu);
    return true;
}

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


    //Detects request codes
    if(requestCode == RESULT_LOAD_IMAGE && resultCode == Activity.RESULT_OK) {
        Log.i("AQUI!", "Entrou no IF");
        Bitmap bitmap = null;
        Bundle extras = data.getExtras();
        bitmap = extras.getParcelable("data");
        Log.i("AQUI!", "Bitmap recebeu a imagem");  

        FileOutputStream fos;
        try {
            fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);  
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        int largura = imguser.getWidth();
        int altura = largura;
        RelativeLayout.LayoutParams margens = (RelativeLayout.LayoutParams) imguser.getLayoutParams();
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(largura, altura);
        params.addRule(RelativeLayout.CENTER_HORIZONTAL);
        params.setMargins(0, margens.topMargin, 0, 0);
        imguser.setLayoutParams(params);
        imguser.setImageBitmap(bitmap);

    }
}

public void onClick(View v) {
    // TODO Auto-generated method stub        

    if(v.getId() == R.id.btneditar) {
        boolean mExternalStorageAvailable = false; 
        boolean mExternalStorageWriteable = false; 
        String state = Environment.getExternalStorageState(); 
        if (Environment.MEDIA_MOUNTED.equals(state)) { 
            // Podemos ler e escrever os meios de comunicação 
            mExternalStorageAvailable = mExternalStorageWriteable = true; 
            Log.i("PERMISSÂO", "Podemos ler e escrever os meios de comunicação");
        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { 
            // Só podemos ler a mídia 
            mExternalStorageAvailable = true; 
            mExternalStorageWriteable = false; 
            Log.i("PERMISSÂO", "Só podemos ler a mídia");
        } else { 
            // Outra coisa que está errada. Pode ser um de muitos outros estados, mas tudo o que precisamos 
            // Para saber é que não podemos ler nem escrever 
            mExternalStorageAvailable = mExternalStorageWriteable = false; 
            Log.i("PERMISSÂO", "Não podemos ler nem escrever");
        }

        String filename = "profile.jpg";
        file = new File(Environment.getExternalStorageDirectory(), filename);


        Intent cropIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
        cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        cropIntent.putExtra("crop", "true");            
        cropIntent.putExtra("aspectX", 1);
        cropIntent.putExtra("aspectY", 1);
        cropIntent.putExtra("scale", true);
        cropIntent.putExtra("outputX", 300);
        cropIntent.putExtra("outputY", 300);
        cropIntent.putExtra("return-data", true);

    }

}   
    
27.01.2016 / 01:46