Android take data from Imagebutton to send in a post

Asked

Viewed 85 times

2

I have a view type Fragment with a form, in this form I have an imagebutton in which I load images from the Android gallery when I save this form I need to take this image and post in Base64.

public class EditarPerfilActivity extends Fragment {

ImageButton imgButton;

public static EditarPerfilActivity newInstance() {
    EditarPerfilActivity fragment = new EditarPerfilActivity();
    return fragment;
}


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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.activity_editar_perfil, container, false);

    btnSalvarPerfil = (Button) view.findViewById(R.id.btSalvarPerfil);


    imgButton = (ImageButton) view.findViewById(R.id.imgperfil);
    imgButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            openGallery(10);
            Toast.makeText(getActivity().getApplicationContext(), "Clicked Image Button!!", Toast.LENGTH_LONG).show();

        }
    });


    //AQUI QUE DEVERIA CONSEGUIR PEGAR OS DADOS DA IMAGEM
    btnSalvarPerfil.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            ConnectivityManager conn = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkinfo = conn.getActiveNetworkInfo();

            if (networkinfo != null && networkinfo.isConnected()) {


                nome = hintNome.getText().toString();
                idade = hintIdade.getText().toString();

                Bitmap bm = BitmapFactory.decodeFile(selectedPath);
                ByteArrayOutputStream bao = new ByteArrayOutputStream();
                bm.compress(Bitmap.CompressFormat.JPEG, 90, bao);
                byte[] pathImage = bao.toByteArray();


                if (nome.isEmpty() || email.isEmpty()) {
                    Toast.makeText(getActivity().getApplicationContext(), "Preencha o nome ou Email", Toast.LENGTH_LONG).show();
                } else {
                    parametros = "id=" + IdUser +"&nome=" + nome + "&idade=" + idade;

                    new EditarPerfilActivity.SolicitaDados().execute(url);
                }
            } else {
                //error connecting
                Toast.makeText(getActivity().getApplicationContext(), "Nenhuma conexão encontrada", Toast.LENGTH_LONG).show();
            }
        }
    });
    return view;
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if(data.getData() != null){
            selectedImageUri = data.getData();
        }else{
            Log.d("selectedPath1 : ","Came here its null !");
            Toast.makeText(getActivity().getApplicationContext(), "failed to get Image!", Toast.LENGTH_LONG).show();
        }
        if (requestCode == 100 && resultCode == RESULT_OK) {
            Bitmap photo = (Bitmap) data.getExtras().get("data");
            selectedPath = getPath(selectedImageUri);
            imgButton.setImageURI(selectedImageUri);
            Log.d("selectedPath1 : " ,selectedPath);
        }
        if (requestCode == 10)
        {
            selectedPath = getPath(selectedImageUri);
            imgButton.setImageURI(selectedImageUri);
            Log.d("selectedPath1 : " ,selectedPath);
        }
    }
}

public String getPath(Uri uri) {
    String res = null;
    String[] proj = { MediaStore.Images.Media.DATA };
    Cursor cursor = getActivity().getContentResolver().query(uri, proj, null, null, null);
    if(cursor.moveToFirst()){;
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        res = cursor.getString(column_index);
    }
    cursor.close();
    return res;
}

public void openGallery(int req_code){
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent,"Select file to upload "), req_code);
}

}

Does anyone have an idea how I can do this?

  • I uploaded the image from the gallery, Imagebutton when you receive a click opens the gallery to choose an image, and this image is loaded on the same button, but when I save this form I am unable to access the image.

  • But what happens? Can debug to see if it enters Bitmap photo = (Bitmap) data.getExtras(). get("date"); after that selects the image? Inside the onActivityResult

  • If the image loads normally is when I go to save the form data it does not load the image, it seems that it cannot find the imagembutton

1 answer

1


I believe your problem is in onActivityResult!

When the method onActivityResult returns, he already delivers a URi where we can set directly on ImageButton:

   photo.setImageURI(data.getData());

Also, we can transform this URi in a Bitmap as follows:

try {
        bitmapPhoto = MediaStore.Images.Media.getBitmap(getContentResolver(), data.getData());
    }catch (final IOException e){
         Toast.makeText(getApplicationContext(), e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
    }

So, when sending this information, you can directly validate the Bitmap!

Here is a complete example:

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class MainActivity extends AppCompatActivity {


    /**
     * Código para saber quando retornar em onActivityResult
     */
    final int REQUEST_CODE_IMAGE = 123;

    private ImageButton photo;
    /*
       Instancia da imagem selecionada.
       Se for nula, o usuario não selecionou!
     */
    private Bitmap bitmapPhoto = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        photo = ImageButton.class.cast(findViewById(R.id.photo));
        photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openGallery();
            }
        });
    }


    public void enviar(final View view) {
        if (bitmapPhoto == null) {
            /**
             * A imagem não foi selecionada!
             */
            Toast.makeText(getApplicationContext(), "Selecione a sua imagem de perfil!", Toast.LENGTH_SHORT).show();

        } else {
            /**
             * Vamos Transformar a imagem em  Base64...
             */
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmapPhoto.compress(Bitmap.CompressFormat.PNG, 90, stream);
            fima byte[] img_byte = stream.toByteArray();
            String img_str = Base64.encodeToString(img_byte, Base64.DEFAULT);
            Log.i("BASE64", img_str);
        }
    }


    /**
     * Sempre que solicitar uma imagem, sempre vamos passar a constante REQUEST_CODE_IMAGE
     */
    public void openGallery() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Selecione uma imagem de perfil"), REQUEST_CODE_IMAGE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // OK, o resultado é positivo
        if (resultCode == RESULT_OK) { 
           // é a nossa solicitação de imagem...
            if (requestCode == REQUEST_CODE_IMAGE) { 

                final Uri pathImgSelecionada = data.getData();
                if (null == pathImgSelecionada) {
                    Toast.makeText(getApplicationContext(), "URi Nula!", Toast.LENGTH_SHORT).show();
                }
                /**
                 * Passamos diretamente a URi para o Image Button..
                 */
                photo.setImageURI(pathImgSelecionada);


                /**
                 * Transformamos a URi em um Bitmap
                 */
                try {
                    bitmapPhoto = MediaStore.Images.Media.getBitmap(getContentResolver(), pathImgSelecionada);
                } catch (final IOException e) {
                    Toast.makeText(getApplicationContext(), e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                }

            }
        }
    }

}
  • Thanks Thiago really worked out so, no onActivityResult I took Bitmap and managed to work with him inside the onClick Thank you very much for your help.

Browser other questions tagged

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