Example usage for android.content Intent EXTRA_STREAM

List of usage examples for android.content Intent EXTRA_STREAM

Introduction

In this page you can find the example usage for android.content Intent EXTRA_STREAM.

Prototype

String EXTRA_STREAM

To view the source code for android.content Intent EXTRA_STREAM.

Click Source Link

Document

A content: URI holding a stream of data associated with the Intent, used with #ACTION_SEND to supply the data being sent.

Usage

From source file:eu.intermodalics.tango_ros_streamer.activities.RunningActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.settings:
        if (mParameterNode != null) {
            try {
                mParameterNode.setPreferencesFromParameterServer();
            } catch (RuntimeException e) {
                e.printStackTrace();/*w ww. ja v a  2 s  .c o m*/
            }
        }
        Intent settingsActivityIntent = new Intent(this, SettingsActivity.class);
        settingsActivityIntent.putExtra(getString(R.string.uuids_names_map), mUuidsNamesHashMap);
        startActivityForResult(settingsActivityIntent, StartSettingsActivityRequest.STANDARD_RUN);
        return true;
    case R.id.share:
        mLogger.saveLogToFile();
        Intent shareFileIntent = new Intent(Intent.ACTION_SEND);
        shareFileIntent.setType("text/plain");
        shareFileIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(mLogger.getLogFile()));
        startActivity(shareFileIntent);
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:org.andstatus.app.TimelineActivity.java

private void parseNewIntent(Intent intentNew) {
    mRateLimitText = "";
    mListParametersNew.setTimelineType(TimelineTypeEnum.UNKNOWN);
    mListParametersNew.myAccountUserId = MyContextHolder.get().persistentAccounts().getCurrentAccountUserId();
    mListParametersNew.mSelectedUserId = 0;
    parseAppSearchData(intentNew);//from w  w  w. j a va 2 s.co m
    if (mListParametersNew.getTimelineType() == TimelineTypeEnum.UNKNOWN) {
        mListParametersNew.parseIntentData(intentNew);
    }
    if (mListParametersNew.getTimelineType() == TimelineTypeEnum.UNKNOWN) {
        /* Set default values */
        mListParametersNew.setTimelineType(TimelineTypeEnum.HOME);
        mListParametersNew.mSearchQuery = "";
    }
    if (mListParametersNew.getTimelineType() == TimelineTypeEnum.USER) {
        if (mListParametersNew.mSelectedUserId == 0) {
            mListParametersNew.mSelectedUserId = mListParametersNew.myAccountUserId;
        }
    } else {
        mListParametersNew.mSelectedUserId = 0;
    }

    if (Intent.ACTION_SEND.equals(intentNew.getAction())) {
        shareViaThisApplication(intentNew.getStringExtra(Intent.EXTRA_SUBJECT),
                intentNew.getStringExtra(Intent.EXTRA_TEXT),
                (Uri) intentNew.getParcelableExtra(Intent.EXTRA_STREAM));
    }
}

From source file:com.googlecode.android_scripting.facade.AndroidFacade.java

@Rpc(description = "Launches an activity that sends an e-mail message to a given recipient.")
public void sendEmail(
        @RpcParameter(name = "to", description = "A comma separated list of recipients.") final String to,
        @RpcParameter(name = "subject") final String subject, @RpcParameter(name = "body") final String body,
        @RpcParameter(name = "attachmentUri") @RpcOptional final String attachmentUri) {
    final Intent intent = new Intent(android.content.Intent.ACTION_SEND);
    intent.setType("plain/text");
    intent.putExtra(android.content.Intent.EXTRA_EMAIL, to.split(","));
    intent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
    intent.putExtra(android.content.Intent.EXTRA_TEXT, body);
    if (attachmentUri != null) {
        intent.putExtra(android.content.Intent.EXTRA_STREAM, Uri.parse(attachmentUri));
    }/* ww  w  . j ava 2s .  com*/
    startActivity(intent);
}

From source file:com.wikitude.virtualhome.AugmentedActivity.java

public void shareSnapShot() {

    Log.e(this.getClass().getName(), " VIRTUALHOME: calling captureSnapShot method");

    architectView.captureScreen(ArchitectView.CaptureScreenCallback.CAPTURE_MODE_CAM_AND_WEBVIEW,
            new ArchitectView.CaptureScreenCallback() {

                @Override/*from w ww. ja  v  a 2 s  . c om*/
                public void onScreenCaptured(final Bitmap screenCapture) {

                    // store screenCapture into external cache directory
                    final File screenCaptureFile = new File(
                            Environment.getExternalStorageDirectory().toString(),
                            "screenCapture_" + System.currentTimeMillis() + ".jpg");

                    // 1. Save bitmap to file & compress to jpeg. You may use PNG too
                    try {
                        final FileOutputStream out = new FileOutputStream(screenCaptureFile);
                        screenCapture.compress(Bitmap.CompressFormat.JPEG, 90, out);
                        out.flush();
                        out.close();

                        // 2. create send intent
                        final Intent share = new Intent(Intent.ACTION_SEND);
                        share.setType("image/jpg");
                        share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(screenCaptureFile));

                        // 3. launch intent-chooser
                        final String chooserTitle = "Share Snapshot";
                        startActivity(Intent.createChooser(share, chooserTitle));

                    } catch (final Exception e) {
                        // should not occur when all permissions are set
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                Log.e(this.getClass().getName(), " VIRTUALHOME: Share Snapshot failed ");
                                // show toast message in case something went wrong
                                //Toast.makeText(this, " Unexpected error", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            });
}

From source file:com.shollmann.igcparser.ui.activity.FlightPreviewActivity.java

private void launchShareFile(String tempIgcFilePath) {
    try {//from  w w w.j  a  v  a  2  s .  co  m
        TrackerHelper.trackShareFlight();
        Intent intentEmail = new Intent(Intent.ACTION_SEND);
        intentEmail.setType(Constants.App.TEXT_HTML);
        intentEmail.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(FlightPreviewActivity.this,
                Constants.App.FILE_PROVIDER, new File(tempIgcFilePath)));
        intentEmail.putExtra(Intent.EXTRA_SUBJECT, String.format(getString(R.string.share_email_subject),
                Uri.parse(tempIgcFilePath).getLastPathSegment()));
        startActivity(Intent.createChooser(intentEmail, getString(R.string.share)));
    } catch (Throwable t) {
        Toast.makeText(this, R.string.sorry_error_happen, Toast.LENGTH_SHORT).show();
    }
}

From source file:com.saphion.stencilweather.activities.MainActivity.java

public void share(String packageName, String className) {
    Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);

    String name = drawerItems.get(navSpinner.getSelectedItemPosition()).getName();
    if (name.contains(",")) {
        name = name.split(",")[0];
    }/*from w w  w. j  a  va 2 s . c  o m*/

    try {

        shareContainer.setDrawingCacheEnabled(true);
        shareContainer.buildDrawingCache();
        Bitmap icon = shareContainer.getDrawingCache();
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        icon.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        File f = new File(getExternalCacheDir() + File.separator + "shared" + File.separator + name
                + "_weather_" + System.currentTimeMillis() + ".jpg");
        try {
            f.getParentFile().mkdirs();
            f.createNewFile();
            FileOutputStream fo = new FileOutputStream(f);
            fo.write(bytes.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
        sendIntent.putExtra(Intent.EXTRA_TEXT, name + " Weather shared by Stencil Weather");

        Log.d("Stencil Weather", "tmp file URI " + f.getAbsolutePath());
        sendIntent.setComponent(new ComponentName(packageName, className));
        sendIntent.setType("image/jpeg");
        startActivity(sendIntent);
        shareContainer = null;
        mShareDialog.dismiss();
        mShareDialog = null;
    } catch (Exception ignored) {
    }

}

From source file:eu.basicairdata.graziano.gpslogger.FragmentTracklist.java

@Subscribe
public void onEvent(EventBusMSGNormal msg) {
    if (msg.MSGType == EventBusMSG.TRACKLIST_SELECTION) {
        final long selID = msg.id;
        if (selID >= 0) {
            getActivity().runOnUiThread(new Runnable() {
                @Override//w ww.ja va  2  s.c  o  m
                public void run() {
                    selectedtrackID = selID;
                    registerForContextMenu(view);
                    getActivity().openContextMenu(view);
                    unregisterForContextMenu(view);
                }
            });
        }
    }
    if (msg.MSGType == EventBusMSG.INTENT_SEND) {
        final long trackid = msg.id;
        if (trackid > 0) {
            Track track = GPSApplication.getInstance().GPSDataBase.getTrack(trackid);

            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_SEND_MULTIPLE);
            //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra(Intent.EXTRA_SUBJECT, "GPS Logger - Track " + track.getName());

            PhysicalDataFormatter phdformatter = new PhysicalDataFormatter();
            PhysicalData phdDuration;
            PhysicalData phdSpeedMax;
            PhysicalData phdSpeedAvg;
            PhysicalData phdDistance;
            PhysicalData phdAltitudeGap;
            PhysicalData phdOverallDirection;
            phdDuration = phdformatter.format(track.getPrefTime(), PhysicalDataFormatter.FORMAT_DURATION);
            phdSpeedMax = phdformatter.format(track.getSpeedMax(), PhysicalDataFormatter.FORMAT_SPEED);
            phdSpeedAvg = phdformatter.format(track.getPrefSpeedAverage(),
                    PhysicalDataFormatter.FORMAT_SPEED_AVG);
            phdDistance = phdformatter.format(track.getEstimatedDistance(),
                    PhysicalDataFormatter.FORMAT_DISTANCE);
            phdAltitudeGap = phdformatter.format(
                    track.getEstimatedAltitudeGap(
                            GPSApplication.getInstance().getPrefEGM96AltitudeCorrection()),
                    PhysicalDataFormatter.FORMAT_ALTITUDE);
            phdOverallDirection = phdformatter.format(track.getBearing(), PhysicalDataFormatter.FORMAT_BEARING);
            if (track.getNumberOfLocations() <= 1) {
                intent.putExtra(Intent.EXTRA_TEXT,
                        (CharSequence) ("GPS Logger - Track " + track.getName() + "\n"
                                + track.getNumberOfLocations() + " " + getString(R.string.trackpoints) + "\n"
                                + track.getNumberOfPlacemarks() + " " + getString(R.string.placemarks)));
            } else {
                intent.putExtra(Intent.EXTRA_TEXT,
                        (CharSequence) ("GPS Logger - Track " + track.getName() + "\n"
                                + track.getNumberOfLocations() + " " + getString(R.string.trackpoints) + "\n"
                                + track.getNumberOfPlacemarks() + " " + getString(R.string.placemarks) + "\n"
                                + "\n" + getString(R.string.pref_track_stats) + " "
                                + (GPSApplication.getInstance().getPrefShowTrackStatsType() == 0
                                        ? getString(R.string.pref_track_stats_totaltime)
                                        : getString(R.string.pref_track_stats_movingtime))
                                + ":" + "\n" + getString(R.string.distance) + " = " + phdDistance.Value + " "
                                + phdDistance.UM + "\n" + getString(R.string.duration) + " = "
                                + phdDuration.Value + "\n" + getString(R.string.altitude_gap) + " = "
                                + phdAltitudeGap.Value + " " + phdAltitudeGap.UM + "\n"
                                + getString(R.string.max_speed) + " = " + phdSpeedMax.Value + " "
                                + phdSpeedMax.UM + "\n" + getString(R.string.average_speed) + " = "
                                + phdSpeedAvg.Value + " " + phdSpeedAvg.UM + "\n"
                                + getString(R.string.overall_direction) + " = " + phdOverallDirection.Value
                                + " " + phdOverallDirection.UM));
            }
            intent.setType("text/xml");

            ArrayList<Uri> files = new ArrayList<>();
            String fname = track.getName() + ".kml";
            File file = new File(Environment.getExternalStorageDirectory() + "/GPSLogger/AppData/", fname);
            if (file.exists() && GPSApplication.getInstance().getPrefExportKML()) {
                Uri uri = Uri.fromFile(file);
                files.add(uri);
            }
            fname = track.getName() + ".gpx";
            file = new File(Environment.getExternalStorageDirectory() + "/GPSLogger/AppData/", fname);
            if (file.exists() && GPSApplication.getInstance().getPrefExportGPX()) {
                Uri uri = Uri.fromFile(file);
                files.add(uri);
            }
            fname = track.getName() + ".txt";
            file = new File(Environment.getExternalStorageDirectory() + "/GPSLogger/AppData/", fname);
            if (file.exists() && GPSApplication.getInstance().getPrefExportTXT()) {
                Uri uri = Uri.fromFile(file);
                files.add(uri);
            }

            intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, files);

            String title = getString(R.string.card_menu_share);
            // Create intent to show chooser
            Intent chooser = Intent.createChooser(intent, title);

            // Verify the intent will resolve to at least one activity
            if ((intent.resolveActivity(getContext().getPackageManager()) != null) && (!files.isEmpty())) {
                startActivity(chooser);
            }
        }
    }
}

From source file:de.bahnhoefe.deutschlands.bahnhofsfotos.DetailsActivity.java

private Intent createFotoSendIntent() {
    Intent sendIntent = new Intent(Intent.ACTION_SEND);
    File file = getStoredMediaFile();
    if (file != null && file.canRead()) {
        sendIntent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(DetailsActivity.this,
                "de.bahnhoefe.deutschlands.bahnhofsfotos.fileprovider", file));
    } else if (publicBitmap != null) {
        File imagePath = new File(getApplicationContext().getCacheDir(), "images");
        imagePath.mkdirs();/*ww  w  . j  av a2  s.c  o m*/
        File newFile = new File(imagePath, bahnhof.getId() + ".jpg");
        try {
            saveScaledBitmap(newFile, publicBitmap);
            sendIntent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(DetailsActivity.this,
                    "de.bahnhoefe.deutschlands.bahnhofsfotos.fileprovider", newFile));
        } catch (FileNotFoundException e) {
            Log.e(TAG, "Error saving cached bitmap", e);
        }
    }
    return sendIntent;
}

From source file:dev.dworks.apps.anexplorer.fragment.DirectoryFragment.java

private void onShareDocuments(ArrayList<DocumentInfo> docs) {
    Intent intent;//from  w  w w  .  j ava  2  s  .c  o  m
    if (docs.size() == 1) {
        final DocumentInfo doc = docs.get(0);

        intent = new Intent(Intent.ACTION_SEND);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        // intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.setType(doc.mimeType);
        intent.putExtra(Intent.EXTRA_STREAM, doc.derivedUri);

    } else if (docs.size() > 1) {
        intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        // intent.addCategory(Intent.CATEGORY_DEFAULT);

        final ArrayList<String> mimeTypes = Lists.newArrayList();
        final ArrayList<Uri> uris = Lists.newArrayList();
        for (DocumentInfo doc : docs) {
            mimeTypes.add(doc.mimeType);
            uris.add(doc.derivedUri);
        }

        intent.setType(findCommonMimeType(mimeTypes));
        intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);

    } else {
        return;
    }

    intent = Intent.createChooser(intent, getActivity().getText(R.string.share_via));
    startActivity(intent);
}

From source file:com.ibuildapp.romanblack.CataloguePlugin.ProductDetails.java

/**
 * Initializing user interface//from  w  w w  . j  a v  a2s  . co  m
 */
private void initializeUI() {
    setContentView(R.layout.details_layout);
    hideTopBar();

    navBarHolder = (RelativeLayout) findViewById(R.id.navbar_holder);
    List<String> imageUrls = new ArrayList<>();
    imageUrls.add(product.imageURL);
    imageUrls.addAll(product.imageUrls);

    final float density = getResources().getDisplayMetrics().density;
    int topBarHeight = (int) (TOP_BAR_HEIGHT * density);
    TextView apply_button = (TextView) findViewById(R.id.apply_button);
    View basket = findViewById(R.id.basket);
    View bottomSeparator = findViewById(R.id.bottom_separator);
    quantity = (EditText) findViewById(R.id.quantity);

    roundsList = (RecyclerView) findViewById(R.id.details_recyclerview);
    if (imageUrls.size() <= 1)
        roundsList.setVisibility(View.GONE);

    LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);

    roundsList.setLayoutManager(layoutManager);
    pager = (ViewPager) findViewById(R.id.viewpager);

    if (!"".equals(imageUrls.get(0))) {

        final RoundAdapter rAdapter = new RoundAdapter(this, imageUrls);
        roundsList.setAdapter(rAdapter);

        float width = getResources().getDisplayMetrics().widthPixels;
        float height = getResources().getDisplayMetrics().heightPixels;
        height -= 2 * topBarHeight;
        height -= com.ibuildapp.romanblack.CataloguePlugin.utils.Utils.getStatusBarHeight(this);
        pager.getLayoutParams().width = (int) width;
        pager.getLayoutParams().height = (int) height;
        newCurrentItem = 0;
        pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                oldCurrentItem = newCurrentItem;
                newCurrentItem = position;

                rAdapter.setCurrentItem(newCurrentItem);
                rAdapter.notifyItemChanged(newCurrentItem);

                if (oldCurrentItem != -1)
                    rAdapter.notifyItemChanged(oldCurrentItem);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        pager.setPageTransformer(true, new InnerPageTransformer());
        adapter = new DetailsViewPagerAdapter(getSupportFragmentManager(), imageUrls);
        roundsList.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                int totalWidth = (int) (adapter.getCount() * 21 * density);
                int screenWidth = getResources().getDisplayMetrics().widthPixels;
                int position = parent.getChildAdapterPosition(view);

                if ((totalWidth < screenWidth) && position == 0)
                    outRect.left = (screenWidth - totalWidth) / 2;
            }
        });

        pager.setAdapter(adapter);
    } else {
        roundsList.setVisibility(View.GONE);
        pager.setVisibility(View.GONE);
    }
    buyLayout = (RelativeLayout) findViewById(R.id.details_buy_layout);

    if (product.itemType.equals(ProductItemType.EXTERNAL))
        quantity.setVisibility(View.GONE);
    else
        quantity.setVisibility(View.VISIBLE);

    if (Statics.isBasket) {
        buyLayout.setVisibility(View.VISIBLE);
        onShoppingCartItemAdded();
        apply_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hideKeyboard();
                quantity.setText(StringUtils.isBlank(quantity.getText().toString()) ? "1"
                        : quantity.getText().toString());
                quantity.clearFocus();

                String message = "";
                int quant = Integer.valueOf(quantity.getText().toString());
                List<ShoppingCart.Product> products = ShoppingCart.getProducts();
                int count = 0;

                for (ShoppingCart.Product product : products)
                    count += product.getQuantity();

                try {
                    message = new PluralResources(getResources()).getQuantityString(R.plurals.items_to_cart,
                            count + quant, count + quant);
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }

                int index = products.indexOf(new ShoppingCart.Product.Builder().setId(product.id).build());
                ShoppingCart.insertProduct(new ShoppingCart.Product.Builder().setId(product.id)
                        .setQuantity((index == -1 ? 0 : products.get(index).getQuantity()) + quant).build());
                onShoppingCartItemAdded();
                com.ibuildapp.romanblack.CataloguePlugin.utils.Utils.showDialog(ProductDetails.this,
                        R.string.shopping_cart_dialog_title, message, R.string.shopping_cart_dialog_continue,
                        R.string.shopping_cart_dialog_view_cart,
                        new com.ibuildapp.romanblack.CataloguePlugin.utils.Utils.OnDialogButtonClickListener() {
                            @Override
                            public void onPositiveClick(DialogInterface dialog) {
                                dialog.dismiss();
                            }

                            @Override
                            public void onNegativeClick(DialogInterface dialog) {
                                Intent intent = new Intent(ProductDetails.this, ShoppingCartPage.class);
                                ProductDetails.this.startActivity(intent);
                            }
                        });
            }
        });
        if (product.itemType.equals(ProductItemType.EXTERNAL)) {
            basket.setVisibility(View.GONE);
            apply_button.setText(product.itemButtonText);
            apply_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(ProductDetails.this, ExternalProductDetailsActivity.class);
                    intent.putExtra("itemUrl", product.itemUrl);
                    startActivity(intent);
                }
            });
        } else {
            basket.setVisibility(View.VISIBLE);
            apply_button.setText(R.string.shopping_cart_add_to_cart);
        }
    } else {
        if (product.itemType.equals(ProductItemType.EXTERNAL))
            buyLayout.setVisibility(View.VISIBLE);
        else
            buyLayout.setVisibility(View.GONE);

        apply_button.setText(R.string.buy_now);
        basket.setVisibility(View.GONE);
        findViewById(R.id.cart_items).setVisibility(View.GONE);
        /*apply_button_padding_left = 0;
        apply_button.setGravity(Gravity.CENTER);
        apply_button.setPadding(apply_button_padding_left, 0, 0, 0);*/

        if (TextUtils.isEmpty(Statics.PAYPAL_CLIENT_ID) || product.price == 0) {
            bottomSeparator.setVisibility(View.GONE);
            apply_button.setVisibility(View.GONE);
            basket.setVisibility(View.GONE);

        } else {
            apply_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    payer.singlePayment(new Payer.Item.Builder().setPrice(product.price)
                            .setCurrencyCode(Payer.CurrencyCode.valueOf(Statics.uiConfig.currency))
                            .setName(product.name).setEndpoint(Statics.ENDPOINT).setAppId(Statics.appId)
                            .setWidgetId(Statics.widgetId).setItemId(product.item_id).build());
                }
            });
        }

        if (product.itemType.equals(ProductItemType.EXTERNAL)) {
            basket.setVisibility(View.GONE);
            apply_button.setText(product.itemButtonText);
            apply_button.setVisibility(View.VISIBLE);
            apply_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(ProductDetails.this, ExternalProductDetailsActivity.class);
                    intent.putExtra("itemUrl", product.itemUrl);
                    startActivity(intent);
                }
            });
        }
    }

    backBtn = (LinearLayout) findViewById(R.id.back_btn);
    backBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });
    title = (TextView) findViewById(R.id.title_text);
    title.setMaxWidth((int) (screenWidth * 0.55));
    if (category != null && !TextUtils.isEmpty(category.name))
        title.setText(category.name);

    View basketBtn = findViewById(R.id.basket_view_btn);
    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(ProductDetails.this, ShoppingCartPage.class);
            startActivity(intent);
        }
    };
    basketBtn.setOnClickListener(listener);
    View hamburgerView = findViewById(R.id.hamburger_view_btn);
    hamburgerView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            animateRootContainer();
        }
    });
    if (!showSideBar) {
        hamburgerView.setVisibility(View.GONE);
        basketBtn.setVisibility(View.VISIBLE);
        basketBtn.setVisibility(Statics.isBasket ? View.VISIBLE : View.GONE);
        findViewById(R.id.cart_items).setVisibility(View.VISIBLE);
    } else {
        hamburgerView.setVisibility(View.VISIBLE);
        findViewById(R.id.cart_items).setVisibility(View.INVISIBLE);
        basketBtn.setVisibility(View.GONE);
        if (Statics.isBasket)
            shopingCartIndex = setTopBarRightButton(basketBtn, getResources().getString(R.string.shopping_cart),
                    listener);
    }

    productTitle = (TextView) findViewById(R.id.product_title);
    productTitle.setText(product.name);

    product_sku = (TextView) findViewById(R.id.product_sku);

    if (TextUtils.isEmpty(product.sku)) {
        product_sku.setVisibility(View.GONE);
        product_sku.setText("");
    } else {
        product_sku.setVisibility(View.VISIBLE);
        product_sku.setText(getString(R.string.item_sku) + " " + product.sku);
    }

    productDescription = (WebView) findViewById(R.id.product_description);
    productDescription.getSettings().setJavaScriptEnabled(true);
    productDescription.getSettings().setDomStorageEnabled(true);
    productDescription.setWebChromeClient(new WebChromeClient());
    productDescription.setWebViewClient(new WebViewClient() {
        @Override
        public void onLoadResource(WebView view, String url) {
            if (!alreadyLoaded
                    && (url.startsWith("http://www.youtube.com/get_video_info?")
                            || url.startsWith("https://www.youtube.com/get_video_info?"))
                    && Build.VERSION.SDK_INT <= 11) {
                try {
                    String path = url.contains("https://www.youtube.com/get_video_info?")
                            ? url.replace("https://www.youtube.com/get_video_info?", "")
                            : url.replace("http://www.youtube.com/get_video_info?", "");

                    String[] parqamValuePairs = path.split("&");

                    String videoId = null;

                    for (String pair : parqamValuePairs) {
                        if (pair.startsWith("video_id")) {
                            videoId = pair.split("=")[1];
                            break;
                        }
                    }

                    if (videoId != null) {
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com"))
                                .setData(Uri.parse("http://www.youtube.com/watch?v=" + videoId)));

                        alreadyLoaded = !alreadyLoaded;
                    }
                } catch (Exception ex) {
                }
            } else {
                super.onLoadResource(view, url);
            }
        }

        @Override
        public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(ProductDetails.this);
            builder.setMessage(R.string.catalog_notification_error_ssl_cert_invalid);
            builder.setPositiveButton(ProductDetails.this.getResources().getString(R.string.catalog_continue),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            handler.proceed();
                        }
                    });
            builder.setNegativeButton(ProductDetails.this.getResources().getString(R.string.catalog_cancel),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            handler.cancel();
                        }
                    });
            final AlertDialog dialog = builder.create();
            dialog.show();
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            if (url.contains("youtube.com/embed")) {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com"))
                        .setData(Uri.parse(url)));
            }
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith("tel:")) {
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
                startActivity(intent);

                return true;
            } else if (url.startsWith("mailto:")) {
                Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse(url));
                startActivity(intent);

                return true;
            } else if (url.contains("youtube.com")) {
                try {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com"))
                            .setData(Uri.parse(url)));

                    return true;
                } catch (Exception ex) {
                    return false;
                }
            } else if (url.contains("goo.gl") || url.contains("maps") || url.contains("maps.yandex")
                    || url.contains("livegpstracks")) {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)).setData(Uri.parse(url)));
                return true;
            } else {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)).setData(Uri.parse(url)));
                return true;
            }
        }
    });
    productDescription.loadDataWithBaseURL(null, product.description, "text/html", "UTF-8", null);

    productPrice = (TextView) findViewById(R.id.product_price);
    productPrice.setVisibility(
            "0.00".equals(String.format(Locale.US, "%.2f", product.price)) ? View.GONE : View.VISIBLE);
    String result = com.ibuildapp.romanblack.CataloguePlugin.utils.Utils
            .currencyToPosition(Statics.uiConfig.currency, product.price);
    if (result.contains(getResources().getString(R.string.rest_number_pattern)))
        result = result.replace(getResources().getString(R.string.rest_number_pattern), "");
    productPrice.setText(result);

    likeCount = (TextView) findViewById(R.id.like_count);
    likeImage = (ImageView) findViewById(R.id.like_image);

    if (!TextUtils.isEmpty(product.imageURL)) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String token = FacebookAuthorizationActivity.getFbToken(
                        com.appbuilder.sdk.android.Statics.FACEBOOK_APP_ID,
                        com.appbuilder.sdk.android.Statics.FACEBOOK_APP_SECRET);
                if (TextUtils.isEmpty(token))
                    return;

                List<String> urls = new ArrayList<String>();
                urls.add(product.imageURL);
                final Map<String, String> res = FacebookAuthorizationActivity.getLikesForUrls(urls, token);
                if (res != null) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            likeCount.setText(res.get(product.imageURL));
                        }
                    });
                }
                Log.e("", "");
            }
        }).start();
    }

    shareBtn = (LinearLayout) findViewById(R.id.share_button);
    if (Statics.uiConfig.showShareButton)
        shareBtn.setVisibility(View.VISIBLE);
    else
        shareBtn.setVisibility(View.GONE);

    shareBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            showDialogSharing(new DialogSharing.Configuration.Builder()
                    .setFacebookSharingClickListener(new DialogSharing.Item.OnClickListener() {
                        @Override
                        public void onClick() {
                            // checking Internet connection
                            if (!Utils.networkAvailable(ProductDetails.this))
                                Toast.makeText(ProductDetails.this,
                                        getResources().getString(R.string.alert_no_internet),
                                        Toast.LENGTH_SHORT).show();
                            else {
                                if (Authorization
                                        .getAuthorizedUser(Authorization.AUTHORIZATION_TYPE_FACEBOOK) != null) {
                                    shareFacebook();
                                } else {
                                    Authorization.authorize(ProductDetails.this,
                                            FACEBOOK_AUTHORIZATION_ACTIVITY,
                                            Authorization.AUTHORIZATION_TYPE_FACEBOOK);
                                }
                            }
                        }
                    }).setTwitterSharingClickListener(new DialogSharing.Item.OnClickListener() {
                        @Override
                        public void onClick() {
                            // checking Internet connection
                            if (!Utils.networkAvailable(ProductDetails.this))
                                Toast.makeText(ProductDetails.this,
                                        getResources().getString(R.string.alert_no_internet),
                                        Toast.LENGTH_SHORT).show();
                            else {
                                if (Authorization
                                        .getAuthorizedUser(Authorization.AUTHORIZATION_TYPE_TWITTER) != null) {
                                    shareTwitter();
                                } else {
                                    Authorization.authorize(ProductDetails.this, TWITTER_AUTHORIZATION_ACTIVITY,
                                            Authorization.AUTHORIZATION_TYPE_TWITTER);
                                }
                            }
                        }
                    }).setEmailSharingClickListener(new DialogSharing.Item.OnClickListener() {
                        @Override
                        public void onClick() {
                            Intent intent = chooseEmailClient();
                            intent.setType("text/html");

                            // *************************************************************************************************
                            // preparing sharing message
                            String downloadThe = getString(R.string.directoryplugin_email_download_this);
                            String androidIphoneApp = getString(
                                    R.string.directoryplugin_email_android_iphone_app);
                            String postedVia = getString(R.string.directoryplugin_email_posted_via);
                            String foundThis = getString(R.string.directoryplugin_email_found_this);

                            // prepare content
                            String downloadAppUrl = String.format(
                                    "http://%s/projects.php?action=info&projectid=%s",
                                    com.appbuilder.sdk.android.Statics.BASE_DOMEN, Statics.appId);

                            String adPart = String.format(
                                    downloadThe + " %s " + androidIphoneApp + ": <a href=\"%s\">%s</a><br>%s",
                                    Statics.appName, downloadAppUrl, downloadAppUrl,
                                    postedVia + " <a href=\"http://ibuildapp.com\">www.ibuildapp.com</a>");

                            // content part
                            String contentPath = String.format(
                                    "<!DOCTYPE html><html><body><b>%s</b><br><br>%s<br><br>%s</body></html>",
                                    product.name, product.description,
                                    com.ibuildapp.romanblack.CataloguePlugin.Statics.hasAd ? adPart : "");

                            contentPath = contentPath.replaceAll("\\<img.*?>", "");

                            // prepare image to attach
                            // FROM ASSETS
                            InputStream stream = null;
                            try {
                                if (!TextUtils.isEmpty(product.imageRes)) {
                                    stream = manager.open(product.imageRes);

                                    String fileName = inputStreamToFile(stream);
                                    File copyTo = new File(fileName);
                                    intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(copyTo));
                                }
                            } catch (IOException e) {
                                // from cache
                                File copyTo = new File(product.imagePath);
                                if (copyTo.exists()) {
                                    intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(copyTo));
                                }
                            }

                            intent.putExtra(Intent.EXTRA_SUBJECT, product.name);
                            intent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(contentPath));
                            startActivity(intent);
                        }
                    }).build());

            //                openOptionsMenu();
        }
    });

    likeBtn = (LinearLayout) findViewById(R.id.like_button);
    if (Statics.uiConfig.showLikeButton)
        likeBtn.setVisibility(View.VISIBLE);
    else
        likeBtn.setVisibility(View.GONE);

    likeBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (Utils.networkAvailable(ProductDetails.this)) {
                if (!TextUtils.isEmpty(product.imageURL)) {
                    if (Authorization.isAuthorized(Authorization.AUTHORIZATION_TYPE_FACEBOOK)) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {

                                List<String> userLikes = null;
                                try {
                                    userLikes = FacebookAuthorizationActivity.getUserOgLikes();
                                    for (String likeUrl : userLikes) {
                                        if (likeUrl.compareToIgnoreCase(product.imageURL) == 0) {
                                            likedbyMe = true;
                                            break;
                                        }
                                    }

                                    if (!likedbyMe) {
                                        if (FacebookAuthorizationActivity.like(product.imageURL)) {
                                            String likeCountStr = likeCount.getText().toString();
                                            try {
                                                final int res = Integer.parseInt(likeCountStr);

                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        likeCount.setText(Integer.toString(res + 1));
                                                        enableLikeButton(false);
                                                        Toast.makeText(ProductDetails.this,
                                                                getString(R.string.like_success),
                                                                Toast.LENGTH_SHORT).show();
                                                    }
                                                });
                                            } catch (NumberFormatException e) {
                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        Toast.makeText(ProductDetails.this,
                                                                getString(R.string.like_error),
                                                                Toast.LENGTH_SHORT).show();
                                                    }
                                                });
                                            }
                                        }
                                    } else {
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                enableLikeButton(false);
                                                Toast.makeText(ProductDetails.this,
                                                        getString(R.string.already_liked), Toast.LENGTH_SHORT)
                                                        .show();
                                            }
                                        });
                                    }
                                } catch (FacebookAuthorizationActivity.FacebookNotAuthorizedException e) {
                                    if (!Utils.networkAvailable(ProductDetails.this)) {
                                        Toast.makeText(ProductDetails.this,
                                                getString(R.string.alert_no_internet), Toast.LENGTH_SHORT)
                                                .show();
                                        return;
                                    }
                                    Authorization.authorize(ProductDetails.this, AUTHORIZATION_FB,
                                            Authorization.AUTHORIZATION_TYPE_FACEBOOK);
                                } catch (FacebookAuthorizationActivity.FacebookAlreadyLiked facebookAlreadyLiked) {
                                    facebookAlreadyLiked.printStackTrace();
                                }

                            }
                        }).start();
                    } else {
                        if (!Utils.networkAvailable(ProductDetails.this)) {
                            Toast.makeText(ProductDetails.this, getString(R.string.alert_no_internet),
                                    Toast.LENGTH_SHORT).show();
                            return;
                        }
                        Authorization.authorize(ProductDetails.this, AUTHORIZATION_FB,
                                Authorization.AUTHORIZATION_TYPE_FACEBOOK);
                    }
                } else
                    Toast.makeText(ProductDetails.this, getString(R.string.nothing_to_like), Toast.LENGTH_SHORT)
                            .show();
            } else
                Toast.makeText(ProductDetails.this, getString(R.string.alert_no_internet), Toast.LENGTH_SHORT)
                        .show();
        }
    });

    if (TextUtils.isEmpty(product.imageURL)) {
        enableLikeButton(false);
    } else {
        if (Authorization.isAuthorized(Authorization.AUTHORIZATION_TYPE_FACEBOOK)) {
            new Thread(new Runnable() {
                @Override
                public void run() {

                    List<String> userLikes = null;
                    try {
                        userLikes = FacebookAuthorizationActivity.getUserOgLikes();
                        for (String likeUrl : userLikes) {
                            if (likeUrl.compareToIgnoreCase(product.imageURL) == 0) {
                                likedbyMe = true;
                                break;
                            }
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                enableLikeButton(!likedbyMe);
                            }
                        });
                    } catch (FacebookAuthorizationActivity.FacebookNotAuthorizedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

    // product bitmap rendering
    image = (AlphaImageView) findViewById(R.id.product_image);
    image.setVisibility(View.GONE);
    if (!TextUtils.isEmpty(product.imageRes)) {
        try {
            InputStream input = manager.open(product.imageRes);
            Bitmap btm = BitmapFactory.decodeStream(input);
            if (btm != null) {
                int ratio = btm.getWidth() / btm.getHeight();
                image.setLayoutParams(new LinearLayout.LayoutParams(screenWidth, screenWidth / ratio));

                image.setImageBitmapWithAlpha(btm);
                //image.setImageBitmap(btm);
                return;
            }
        } catch (IOException e) {
        }
    }

    if (!TextUtils.isEmpty(product.imagePath)) {
        Bitmap btm = BitmapFactory.decodeFile(product.imagePath);
        if (btm != null) {
            if (btm.getWidth() != 0 && btm.getHeight() != 0) {
                float ratio = (float) btm.getWidth() / (float) btm.getHeight();
                image.setLayoutParams(new LinearLayout.LayoutParams(screenWidth, (int) (screenWidth / ratio)));
                image.setImageBitmapWithAlpha(btm);
                image.setVisibility(View.GONE);
                return;
            }
        }
    }

    if (!TextUtils.isEmpty(product.imageURL)) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                product.imagePath = com.ibuildapp.romanblack.CataloguePlugin.utils.Utils
                        .downloadFile(product.imageURL);
                if (!TextUtils.isEmpty(product.imagePath)) {
                    SqlAdapter.updateProduct(product);
                    final Bitmap btm = BitmapFactory.decodeFile(product.imagePath);

                    if (btm != null) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (btm.getWidth() != 0 && btm.getHeight() != 0) {
                                    float ratio = (float) btm.getWidth() / (float) btm.getHeight();
                                    image.setLayoutParams(new LinearLayout.LayoutParams(screenWidth,
                                            (int) (screenWidth / ratio)));
                                    image.setImageBitmapWithAlpha(btm);
                                    image.setVisibility(View.GONE);
                                }
                            }
                        });
                    }
                }
            }
        }).start();
    }

    image.setVisibility(View.GONE);
}