Get PicturePath selected from gallery to store it in dataBase - android

I used this code to upload image from gallery .it works perfectly..but the problem is that i wanna get the Image's path to store it in wamp dataBase ..`
public class Image extends Activity {
ImageView contact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image);
contact = (ImageView) findViewById(R.id.candidat);
contact.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 Contact Image"), 1);
}
});
}
public void onActivityResult(int reqCode, int resCode, Intent data) {
if (resCode == RESULT_OK) {
if (reqCode == 1)
contact.setImageURI(data.getData());
}
}
}
Thank you for help

You can get the exact path using this method -
public String getPathFromURI(Uri contentURI) {
String result = null;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int _id = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(_id);
cursor.close();
}
return result;
}
And use it like -
public void onActivityResult(int reqCode, int resCode, Intent data) {
if (resCode == RESULT_OK) {
if (reqCode == 1)
contact.setImageURI(data.getData());
String path = getPathFromURI(data.getData());
}
}

put this code:
public static final int IMAGEM = 1;
In the click put:
startActivityForResult(Intent.createChooser(new Intent(Intent.ACTION_PICK).setType("image/*"), "Select a image"), IMAGE);
In your activity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
try {
if (resultCode == RESULT_OK && requestCode == IMAGE){
String pathImg = getRealPathFromURI(intent.getData());
}
}catch (Exception e){
e.printStackTrace();
}
}
public String getRealPathFromURI(Uri uri) {
//this method work for any api
Cursor cursor = null;
try {
Uri newUri = handleImageUri(uri);
String[] proj = { MediaStore.Images.Media.DATA };
cursor = getContentResolver().query(newUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} catch (Exception e){
return null;
} finally {
if (cursor != null) {
cursor.close();
}
}
}

Related

selection of different/multiple contact numbers

my code below is working fine...but it gives me only one contact number upon selection whereas i want to select different / multiple contact numbers and selected contacts to be shown on the screen...
have tried loops and all but not getting where exactly i am doing wrong so as not to achieve what i require....
can someone help me with this ??
public class Main2Activity extends Activity {
private static final int RESULT_PICK_CONTACT = 85500;
private TextView textView1;
private TextView textView2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
textView1 = findViewById(R.id.textView1);
textView2 = findViewById(R.id.textView2);
}
public void selectContact(View v)
{
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case RESULT_PICK_CONTACT:
contactPicked(data);
break;
}
} else {
Log.e("Main2Activity", "Failed to pick contact");
}
}
private void contactPicked(Intent data) {
Cursor cursor = null;
try {
String phoneNo = null ;
String name = null;
Uri uri = data.getData();
cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int phoneIndex =cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int nameIndex =cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
phoneNo = cursor.getString(phoneIndex);
name = cursor.getString(nameIndex);
textView1.setText(name);
textView2.setText(phoneNo);
} catch (Exception e) {
e.printStackTrace();
}
}
}

get path of video file selected from gallery getting NULL. How to get path of video file?

get path of video file selected from gallery getting NULL. How to get path of video file ? Get URi in Activity Result also give null. converting Uri to String also getting Null.
Intent intent;
String selectedVideo1Path, selectedVideo2Path;
EditText e1,e2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.videos_activity);
Button button1 = (Button) findViewById(R.id.video1_btn);
Button button2 = (Button) findViewById(R.id.video2_btn);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectVideoFromGallery();
startActivityForResult(intent, 101);
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectVideoFromGallery();
startActivityForResult(intent, 102);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 101) {
if (data.getData() != null) {
selectedVideo1Path = getPath(data.getData());
Toast.makeText(MergeVideosActivity.this, "Path 1 : "+selectedVideo1Path, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Failed to select video", Toast.LENGTH_LONG).show();
}
}
if (requestCode == 102) {
if (data.getData() != null) {
selectedVideo2Path = getPath(data.getData());
//String str2 = selectedVideo2Path.toString();
// e2.setText(str2);
Toast.makeText(MergeVideosActivity.this, "Path 2 : "+selectedVideo2Path, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Failed to select video", Toast.LENGTH_LONG).show();
}
}
}
This is my getPath method
public String getPath(Uri uri) {
int column_index = 0;
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
cursor.moveToFirst();
}
return cursor.getString(column_index);
}
Selected Video from Gallery I hope its OK ? Check it
public void selectVideoFromGallery() {
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
} else {
intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.INTERNAL_CONTENT_URI);
}
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
}
}
Update your getPath method
public String generatePath(Uri uri,Context context) {
String filePath = null;
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
if(isKitKat){
filePath = generateFromKitkat(uri,context);
}
if(filePath != null){
return filePath;
}
Cursor cursor = context.getContentResolver().query(uri, new String[] { MediaStore.MediaColumns.DATA }, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
filePath = cursor.getString(columnIndex);
}
cursor.close();
}
return filePath == null ? uri.getPath() : filePath;
}
#TargetApi(19)
private String generateFromKitkat(Uri uri,Context context){
String filePath = null;
if(DocumentsContract.isDocumentUri(context, uri)){
String wholeID = DocumentsContract.getDocumentId(uri);
String id = wholeID.split(":")[1];
String[] column = { Media.DATA };
String sel = Media._ID + "=?";
Cursor cursor = context.getContentResolver().
query(Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{ id }, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
}
return filePath;
}

Name of an image from gallery in android

I am using yhe following lines of code for getting the image path from the gallery.
Now, how can i also pick the name of that image from the gallery?
public void selectImage() {
new AlertDialog.Builder(getActivity()).setTitle("Select Picture")
.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
}
}
}
}).show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == getActivity().RESULT_OK && null != data) {
Uri selectedImageUri = data.getData();
String selectedImagePath = getRealPathFromURIForGallery(selectedImageUri);
}
}
public String getRealPathFromURIForGallery(Uri uri) {
if (uri == null) {
return null;
}
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
return uri.getPath();
}

Xamarin Choose Image From Gallery Path is Null

using this recipe to try and choose an image from the gallery and then upload it to s3 but
my path always returns null.
private string _imgPath;
public void InitializeMediaPicker()
{
Intent = new Intent();
Intent.SetType("image/*");
Intent.SetAction(Intent.ActionGetContent);
StartActivityForResult(Intent.CreateChooser(Intent, "Select Picture"), 1000);
}
public string GetImage()
{
InitializeMediaPicker();
return _imgPath;
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
if ((requestCode != 1000) || (resultCode != Result.Ok) || (data == null)) return;
var uri = data.Data;
_imgPath = GetPathToImage(uri);
}
private string GetPathToImage(Android.Net.Uri uri)
{
string path = null;
// The projection contains the columns we want to return in our query.
var projection = new[] { Android.Provider.MediaStore.Images.Media.InterfaceConsts.Data };
using (var cursor = ManagedQuery(uri, projection, null, null, null))
{
if (cursor == null) return path;
var columnIndex = cursor.GetColumnIndexOrThrow(Android.Provider.MediaStore.Images.Media.InterfaceConsts.Data);
cursor.MoveToFirst();
path = cursor.GetString(columnIndex);
}
return path;
}
Here is a working implementation ported from this question and specifically, this answer.
Include the WRITE_EXTERNAL_STORAGE permission in your manifest for this code to work.
public delegate void OnImageResultHandler(bool success, string imagePath);
protected OnImageResultHandler _imagePickerCallback;
public void GetImage(OnImageResultHandler callback)
{
if (callback == null) {
throw new ArgumentException ("OnImageResultHandler callback cannot be null.");
}
_imagePickerCallback = callback;
InitializeMediaPicker();
}
public void InitializeMediaPicker()
{
Intent = new Intent();
Intent.SetType("image/*");
Intent.SetAction(Intent.ActionGetContent);
StartActivityForResult(Intent.CreateChooser(Intent, "Select Picture"), 1000);
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
if ((requestCode != 1000) || (resultCode != Result.Ok) || (data == null)) {
return;
}
string imagePath = null;
var uri = data.Data;
try {
imagePath = GetPathToImage(uri);
} catch (Exception ex) {
// Failed for some reason.
}
_imagePickerCallback (imagePath != null, imagePath);
}
private string GetPathToImage(Android.Net.Uri uri)
{
string doc_id = "";
using (var c1 = ContentResolver.Query (uri, null, null, null, null)) {
c1.MoveToFirst ();
String document_id = c1.GetString (0);
doc_id = document_id.Substring (document_id.LastIndexOf (":") + 1);
}
string path = null;
// The projection contains the columns we want to return in our query.
string selection = Android.Provider.MediaStore.Images.Media.InterfaceConsts.Id + " =? ";
using (var cursor = ManagedQuery(Android.Provider.MediaStore.Images.Media.ExternalContentUri, null, selection, new string[] {doc_id}, null))
{
if (cursor == null) return path;
var columnIndex = cursor.GetColumnIndexOrThrow(Android.Provider.MediaStore.Images.Media.InterfaceConsts.Data);
cursor.MoveToFirst();
path = cursor.GetString(columnIndex);
}
return path;
}
Example Usage:
Button button = FindViewById<Button> (Resource.Id.myButton);
button.Click += delegate {
GetImage(((b, p) => {
Toast.MakeText(this, "Found path: " + p, ToastLength.Long).Show();
}));
};
I've used a callback instead of returning the path for GetImage as the calling method would finish executing before OnActivityResult is called so the path returned would never be valid.
I changed the GetPathToImage method from the Xamarin recipe to the code below and now it works!
private string GetPathToImage(Android.Net.Uri uri)
{
ICursor cursor = this.ContentResolver.Query(uri, null, null, null, null);
cursor.MoveToFirst();
string document_id = cursor.GetString(0);
document_id = document_id.Split(':')[1];
cursor.Close();
cursor = ContentResolver.Query(
Android.Provider.MediaStore.Images.Media.ExternalContentUri,
null, MediaStore.Images.Media.InterfaceConsts.Id + " = ? ", new String[] { document_id }, null);
cursor.MoveToFirst();
string path = cursor.GetString(cursor.GetColumnIndex(MediaStore.Images.Media.InterfaceConsts.Data));
cursor.Close();
return path;
}

how to access phone book contacts?

I am using an Edittext and a button . On press of a button , phone book gets open and then user will select a contact from it and the selected phonenumber will get display on the edittext.
I followed many tutorials and but the methods that they are showing are already depreciated.
I have declared this permission: READ_CONTACTS in manifest
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contact_picker);
// this opens the activity. note the Intent.ACTION_GET_CONTENT
// and the intent.setType
((Button)findViewById(R.id.pick_person)).setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
// user BoD suggests using Intent.ACTION_PICK instead of .ACTION_GET_CONTENT to avoid the chooser
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, 1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
int type = c.getInt(1);
showSelectedNumber(type, number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
public void showSelectedNumber(int type, String number) {
Toast.makeText(this, type + ": " + number, Toast.LENGTH_LONG).show();
}
Answer provided by Digvesh Patel is correct. He has used "type" of contact, which returns number. so I have used his code and made some changes which i used in my application. it maybe helpful to someone
public int REQUESTCODE=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button select = (Button) findViewById(R.id.select);
select.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, REQUESTCODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Uri uri = data.getData();
Log.i("data", uri.toString());
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);
if (c != null && c.moveToFirst()) {
String name = c.getString(0);
String number = c.getString(1);
int type = c.getInt(2);
showSelectedNumber(name, number,type);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
public void showSelectedNumber(String name, String number, int type){
TextView usernumber = (TextView) findViewById(R.id.textView1);
String typelabel = (String) ContactsContract.CommonDataKinds.Phone.getTypeLabel(getResources(), type, "");
usernumber.setText(name+": "+number+" "+typelabel);
}

Categories

Resources