How to save a gallery image and click on Activity?

Asked

Viewed 1,502 times

3

I would like to know how to save a gallery image and click on Activity in version 2.3.3 of the Eclipse emulator, because my code only works when I test on my Android device 4.1 and even then when I upload a large image it leaves a huge white space on 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);
    }
}

While running in 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 I used in my code I found that the error is on this line:

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

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

  • Are you sure it’s getContentResolver() that returns null? It won’t be selectedImage which is null?.

  • @ramaral Pois é fiz um teste aqui e não é o getContentResolver() que retorna null, mas fui tentar um teste para ver o selectedImage retorna null não tive secusso, pus um if(selectedImage == null) e não executa o que está no if(). To the.

  • @ramaral The problem I realize is that it cannot create and save a file even with the permission <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> on Androidmanifest

1 answer

2


Good, personal problem solved altogether, now it does not cause any error and the images are displayed in exactly the same size as the previous image had before. Of course, the code is not yet well structured, but it serves as a basis for solving a problem like this. In this my solution I add on Androidmanifest the permission: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />. And include a logic to know if I’m allowed to read and save files. For whitespace I used an xml attribute from imageview which is: android:scaleType="centerCrop". And to leave the images loaded with the same size as the previous one I re-configured the layout parameters of the imageview taking the image view itself and setting again as an absolute value, because before it was "WRAP_CONTENT". Follow my solution below I hope you help someone or someone help to improve her.

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);

    }

}   

Browser other questions tagged

You are not signed in. Login or sign up in order to post.