Search This Blog

Friday, February 10, 2012

Selecting The Image From The Gallery And Set The Path Into The EditText

First of all we have to reach to the android default gallery and select the file from that and set that path to the edit text.


Make an .xml file named main.xml file and copy this into it.


<?xml version="1.0" encoding="utf-8" ?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" 
        android:layout_height="fill_parent" 
        android:orientation="vertical">
   <EditText android:id="@+id/absolutepathofimage" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" />
  <Button android:text="Browse" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:id="@+id/btnBrowse" />
  </LinearLayout>


Now make the java file named BrowseImagefromGallery and copy this code into it



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.widget.Button;
import android.widget.EditText;


public class BrowseImagefromGallery extends Activity {
private static final int GET_PICTURE = 1;


private String selectedImagePath;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Button btnBrowse = (Button)findViewById(R.id.btnBrowse);
        btnBrowse.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent,
                        "Select Picture"), GET_PICTURE);

}
});
        
        
    }
    
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
   if (resultCode == RESULT_OK) {
       if (requestCode == GET_PICTURE) {
           Uri selectedImageUri = data.getData();
           selectedImagePath = getPath(selectedImageUri);
           EditText imageBrowse = (EditText)findViewById(R.id.absolutepathofimage);
           imageBrowse.setText(selectedImagePath);
       }
   }
}


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

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.