Android get image from gallery

This tutorial you will learn how to get image from gallery and set to imageview.

main.xml

    
     
  
    






GetImageFromGalleryExample.java
package example.com.test;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class GetImageFromGalleryExample extends Activity implements OnClickListener {
 private static final int SELECT_PICTURE = 1;
 private String selectedImagePath = null;
 private ImageView iv;
 private Button button,button1;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        button = (Button)findViewById(R.id.button1);
        button1 = (Button)findViewById(R.id.button2);
        iv = (ImageView)findViewById(R.id.iv1);
        button.setOnClickListener(this);
        button1.setOnClickListener(this);
    }
    
    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 onActivityResult(int requestCode, int resultCode, Intent data) {
     // TODO Auto-generated method stub
     super.onActivityResult(requestCode, resultCode, data);
     if (resultCode == RESULT_OK) {
            if (requestCode == SELECT_PICTURE) {
                Uri selectedImageUri = data.getData();
                //SelectedImagePath is not use in this tutorial but you can use it when ever u want
                //selectedImagePath = getPath(selectedImageUri);
                iv.setImageURI(selectedImageUri);
            }
        }
    }

 @Override
 public void onClick(View v) {
  // TODO Auto-generated method stub
  if (v == button){
   Intent intent = new Intent();
            intent.setType("image/*");
            intent.putExtra("scale", true);
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
  }else{
   iv.setImageResource(R.drawable.icon);
  }
 }
}

0 comments:

Post a Comment