Issue
I tried the following code to share an image to WhatsApp. For now, I manually added the image path.
I want to open the gallery when the user clicks a button in my application and he must be able to select an image to share in WhatsApp.
How can I do that?
PS: I need to set the image path dynamically
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Testing Button", Toast.LENGTH_SHORT).show();
File f=new File("/sdcard/Download/myimage.jpg");
Uri uri = Uri.parse("file://"+f.getAbsolutePath());
Intent share = new Intent(Intent.ACTION_SEND);
share.setPackage("com.whatsapp");
share.putExtra(Intent.EXTRA_STREAM, uri);
share.setType("image/*");
share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
v.getContext().startActivity(Intent.createChooser(share, "Share image File"));
}
});
Solution
You can use the below code to dynamically get the image Uri. It will work on all versions of Android.
MainActivity
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
@Override
protected void onActivityResult(int reqCode, int resCode, Intent data) {
if(resCode == Activity.RESULT_OK && data != null){
String realPath;
if (Build.VERSION.SDK_INT < 11)
realPath = RealPathUtil.getRealPathFromURI_BelowAPI11(this, data.getData());
else if (Build.VERSION.SDK_INT < 19)
realPath = RealPathUtil.getRealPathFromURI_API11to18(this, data.getData());
else
realPath = RealPathUtil.getRealPathFromURI_API19(this, data.getData());
getImageInfo(Build.VERSION.SDK_INT, data.getData().getPath(),realPath);
}
}
private void getImageInfo(int sdk, String uriPath,String realPath){
Uri uriFromPath = Uri.fromFile(new File(realPath));
Log.d("Log", "Build.VERSION.SDK_INT:"+sdk);
Log.d("Log", "URI Path:"+uriPath);
Log.d("Log", "Real Path: "+realPath);
}
}
RealPathUtil.java
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.CursorLoader;
import android.database.Cursor;
import android.net.Uri;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
public class RealPathUtil {
@SuppressLint("NewApi")
public static String getRealPathFromURI_API19(Context context, Uri uri){
String filePath = "";
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = { MediaStore.Images.Media.DATA };
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = context.getContentResolver().query(MediaStore.Images.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;
}
@SuppressLint("NewApi")
public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
String result = null;
CursorLoader cursorLoader = new CursorLoader(
context,
contentUri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
if(cursor != null){
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
result = cursor.getString(column_index);
}
return result;
}
public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri){
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index
= cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
Add this Permission to Manifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
In Android 6+, You need to request the Permission during RunTime.
Answered By - Amar Ilindra
Answer Checked By - Senaida (JavaFixing Volunteer)