1

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"));
    }
});
Andrew T.
  • 4,637
  • 8
  • 40
  • 60
Uday
  • 275
  • 1
  • 4
  • 15

1 Answers1

-1

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.

Amar Ilindra
  • 843
  • 2
  • 11
  • 26
  • That `RealPathUtil` is awful and will fail for hundreds of millions of devices and apps. – CommonsWare Mar 26 '18 at 18:42
  • @CommonsWare At the time of writing, RealPathUtil worked for me and I used it in production. If you have any better solution, please post it in a separate answer. – Amar Ilindra Sep 13 '18 at 13:20
  • 1
    See [this](https://stackoverflow.com/questions/48510584/onactivityresults-intent-getpath-doesnt-give-me-the-correct-filename) and [this](https://stackoverflow.com/questions/49221312/android-get-real-path-of-a-txt-file-selected-from-the-file-explorer) and [this](https://stackoverflow.com/questions/35870825/getting-the-absolute-file-path-from-content-uri-for-searched-images). – CommonsWare Sep 13 '18 at 20:12