Sharing files with social-media via ShareActionProvider

0

My code takes a JSON file, turns it into a QR Code and saves that file. The next thing I want to do is to use the ShareActivity mechanism to let the user share that file via email, facebook, etc.

I made a bunch of mistakes, which is why I've kept updating this question. At this point, I think I've got everything set up as best I can tell it is supposed to be setup. Unfortunately, the sharing icon is dark. I have no idea why.

I'm pretty sure I'm doing something stupid, so I'm just looking for someone to point me in the right direction.

First the menu XML

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/menu_item_share"
        android:icon="@android:drawable/ic_menu_share"
        android:title="@string/mnu_share"
        app:showAsAction="always"
        app:actionProviderClass="android.support.v7.widget.ShareActionProvider" />

</menu>

Next the Activity code (I've included everything in case I'm misjudging what is relevant.):

public class CreateDineQRCode extends AppCompatActivity {

    public final static int WHITE = 0xFFFFFFFF;
    public final static int BLACK = 0xFF000000;
    public final static int WIDTH = 500;
    public final static int HEIGHT = 500;

    private final static int MAX_TAG_LEN = 23;
    private final static String TAG = "CreateDineQRCode";
    //private final static String DINEQRCODE_DIRECTORY = "dineQRCode";

    private ShareActionProvider mShareActionProvider;
    private String bitmapFilePath = "";

    private final static int MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE = 1; // Used for permission callback

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_dine_qrcode);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);

        testJSONCreation();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        final String tag = TAG + ".onCreatedOptions";
        // Inflate menu resource file
        getMenuInflater().inflate(R.menu.create_dineqr_code_menu, menu);

        // Locate MenuItem with ShareActionProvider
        MenuItem shareItem = menu.findItem(R.id.menu_item_share);
        // Fetch and store ShareActionProvider
        Log.d(tag.substring(tag.length() - MAX_TAG_LEN), "fetch and store action provider.");
        mShareActionProvider = new ShareActionProvider(this);
        MenuItemCompat.setActionProvider(shareItem, mShareActionProvider);

        return super.onCreateOptionsMenu(menu);
    } // onCreateOptionsMenu()

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        String tag = TAG + ".onOptionsItemSelected";
        switch (item.getItemId()) {
            case R.id.menu_item_share:
                //Uri uriToImage = Uri.fromFile(new File(bitmapFilePath));
                Intent shareIntent = new Intent();
                shareIntent.setAction(Intent.ACTION_SEND);
                shareIntent.setType("text/plain");
                shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject here");
                shareIntent.putExtra(Intent.EXTRA_TEXT, "Testing Testing Testing");
                Log.d(tag.substring(tag.length() - MAX_TAG_LEN), "Sharing:: Test Text");
                startActivity(Intent.createChooser(shareIntent, "Sharing Option"));
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }

    }

    void testJSONCreation() {
        final String tag = TAG + ".testJSONCreation";
        NutritionRecord rec = NutritionRecord.createTestNutritionRecord();
        String jsonText = rec.toJSON();

        // find interface elements
        TextView jsonTextView = findViewById(R.id.json_code);
        ImageView qrCodeView = findViewById(R.id.qr_code_view);

        jsonTextView.setText(jsonText);
        try {
            Bitmap bm = encodeAsBitmap(jsonText);
            if (null != bm) {
                qrCodeView.setImageBitmap(bm);
                if (getPermission()) {
                    bitmapFilePath = saveImage(bm);
                } else {
                    Log.d(tag.substring(tag.length() - MAX_TAG_LEN),"Unable to get permission");
                }
            } else {
                Log.e(tag.substring(tag.length() - MAX_TAG_LEN), "Error creating bitmap.");
                bitmapFilePath = null;
            }
        } catch (WriterException e) {
            e.printStackTrace();
        }
    } // testJSONCreation()

    Bitmap encodeAsBitmap(String str) throws WriterException {
        BitMatrix result;
        try {
            result = new MultiFormatWriter().encode(str,
                    BarcodeFormat.QR_CODE, WIDTH, HEIGHT, null);
        } catch (IllegalArgumentException iae) {
            // Unsupported format
            return null;
        }
        int w = result.getWidth();
        int h = result.getHeight();
        int[] pixels = new int[w * h];
        for (int y = 0; y < h; y++) {
            int offset = y * w;
            for (int x = 0; x < w; x++) {
                pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
            }
        }
        Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, WIDTH, 0, 0, w, h);
        return bitmap;
    } // encodeAsBitmap()


    private String saveImage(Bitmap myBitmap) {
        final String tag = TAG + ".saveImage";
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
        File qrCodeDirectory; // + "/" + DINEQRCODE_DIRECTORY);
        qrCodeDirectory = Environment.getExternalStorageDirectory();

        if (!qrCodeDirectory.exists()) {
            Log.d(tag.substring(tag.length() - MAX_TAG_LEN), "Directory does not exist. " + qrCodeDirectory.mkdirs());
            if (!qrCodeDirectory.mkdirs()) {
                Log.e(tag.substring(tag.length() - MAX_TAG_LEN), "Unable to create directory:" + qrCodeDirectory.getAbsolutePath());
                return "";
            }
        }

        try {
            File f = new File(qrCodeDirectory, "DineQRCode" + Calendar.getInstance()
                    .getTimeInMillis() + ".jpg");
            if (!f.createNewFile()) { //give read write permission
                Log.e(tag.substring(tag.length() - MAX_TAG_LEN), "Unable to create file. It already exists.");
                return "";
            }

            FileOutputStream fo = new FileOutputStream(f);
            fo.write(bytes.toByteArray());
            MediaScannerConnection.scanFile(this,
                    new String[]{f.getPath()},
                    new String[]{"image/jpeg"}, null);
            fo.close();
            Log.d(tag.substring(tag.length() - MAX_TAG_LEN), "File Saved::--->" + f.getAbsolutePath());

            return f.getAbsolutePath();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return "";

    } // end saveImage()

    private boolean getPermission() {
        String tag = TAG + ".getPermission";
        boolean result = false;

        Log.d(tag.substring(tag.length() - MAX_TAG_LEN), "Entered.");

        // First Check to see we have permission
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // Permission is not granted
            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
                Log.d(tag.substring(tag.length() - MAX_TAG_LEN), "Explain why we need permission.");
                Snackbar.make(findViewById(R.id.create_dine_qrcode_coord_layout), R.string.write_external_permission_explanation, Snackbar.LENGTH_INDEFINITE).show();
            } else {
                // No explanation needed; request the permission
                Log.d(tag.substring(tag.length() - MAX_TAG_LEN), "Request WRITE_EXTERNAL_STORAGE permission");
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE);
            }
        } else {
            Log.d(tag.substring(tag.length() - MAX_TAG_LEN), "WRITE_EXTERNAL_STORAGE: Permission granted.");
            result = true;
        }
        return result;
    } // end getPermission()


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        String tag = TAG + ".onRequestPermissionsResult";
        Log.d(tag.substring(tag.length() - MAX_TAG_LEN),"entered.");
        switch (requestCode) {
            case MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.
                    Log.d(tag.substring(tag.length() - MAX_TAG_LEN), "Permission granted");
                } else {
                    Log.d(tag.substring(tag.length() - MAX_TAG_LEN), "Permission NOT granted.");
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request.
        }
    } // end onRequestPermissionResult()
}
android
share
social-media
appcompatactivity
shareactionprovider
asked on Stack Overflow Oct 13, 2018 by Rben • edited Oct 14, 2018 by Rben

1 Answer

0

The problem appears to be that I didn't have the Intent setup before I left onCreateOptionsMenu().

It's kludgy and will be redone, but the following worked.

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        final String tag = TAG + ".onCreatedOptions";
        // Inflate menu resource file
        getMenuInflater().inflate(R.menu.create_dineqr_code_menu, menu);

        // Locate MenuItem with ShareActionProvider
        MenuItem shareItem = menu.findItem(R.id.menu_item_share);
        // Fetch and store ShareActionProvider
        Log.d(tag.substring(tag.length() - MAX_TAG_LEN), "fetch and store action provider.");
        mShareActionProvider = new ShareActionProvider(this);
        mShareIntent = new Intent();
        updateShareIntent();
        mShareActionProvider.setShareIntent(mShareIntent);
        MenuItemCompat.setActionProvider(shareItem, mShareActionProvider);
        shareItem.setEnabled(true);
        if (shareItem.isEnabled()) {
            Log.d(tag.substring(tag.length() - MAX_TAG_LEN), "shareItem is enabled.");
        }

        return super.onCreateOptionsMenu(menu);
    } // onCreateOptionsMenu()

    void updateShareIntent() {
        mShareIntent.setAction(Intent.ACTION_SEND);
        mShareIntent.setType("text/plain");
        mShareIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject here");
        mShareIntent.putExtra(Intent.EXTRA_TEXT, "Testing Testing Testing");
    }

One problem that remains is the icon is still dark. I'm sure I'll figure that out.

answered on Stack Overflow Oct 14, 2018 by Rben

User contributions licensed under CC BY-SA 3.0