android – Take the path of an image in the Gallery

Question:

How can I get the path of the image I just uploaded and then save it in the database with the path? I get the image from the Gallery, then with this image I wanted to get the path and save it in SQLite database. I'm kind of a layman on the subject 🙁

    	ImageButton contactImgView;
        private String imagePath;

       public void tela_cuidador_cadastrar_tema(){
	
	setContentView(R.layout.tela_cuidador_cadastrar_tema);
	
	contactImgView = (ImageButton) findViewById(R.id.imageButton1);


    //Procura Imagem da galeria


    contactImgView.setOnClickListener(new View.OnClickListener(){

    	  public void onClick(View v){
              Intent intent = new Intent();
              intent.setType("image/*");
              intent.setAction(Intent.ACTION_GET_CONTENT);
              startActivityForResult(Intent.createChooser(intent, "Select Contact Image"), 1);
 
    	}
    });       
}
@Override
public void onActivityResult(int reqCode, int resCode, Intent data) {
	super.onActivityResult(reqCode, resCode, data);
    if(resCode == RESULT_OK)    {
        if (reqCode == 1)
            contactImgView.setImageURI(data.getData());
        	Uri imageUri = data.getData();
        	imagePath = getImagePath(imageUri);
            Toast.makeText(MainActivity.this, imagePath, Toast.LENGTH_LONG).show();


    }
}

public String getImagePath(Uri contentUri) {
    String[] campos = { MediaStore.Images.Media.DATA };
    Cursor cursor = getContentResolver().query(contentUri, campos, null, null, null);
    cursor.moveToFirst();
    String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
    cursor.close();
    return path;
}

But the message that was supposed to be displayed appears blank and not the path :S .

Answer:

If you are getting the image from the Gallery using Intent.ACTION_PICK can, in the onActivityResult() method, use Uri imageUri = intent.getData(); to get the Uri to the image data. Use the getImagePath() method to read its path .

private String imagePath;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);

    switch (requestCode) {
    case REQUEST_PICK_IMAGE:
        if(RESULT_OK == resultCode){
            Uri imageUri = intent.getData();
            imagePath = getImagePath(imageUri)
            ......
            ......
        break;

    default:
        break;
    }
}

public String getImagePath(Uri contentUri) {
    String[] campos = { MediaStore.Images.Media.DATA };
    Cursor cursor = getContentResolver().query(contentUri, campos, null, null, null);
    cursor.moveToFirst();
    String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
    cursor.close();
    return path;
}
Scroll to Top