Example usage for android.os Environment getExternalStoragePublicDirectory

List of usage examples for android.os Environment getExternalStoragePublicDirectory

Introduction

In this page you can find the example usage for android.os Environment getExternalStoragePublicDirectory.

Prototype

public static File getExternalStoragePublicDirectory(String type) 

Source Link

Document

Get a top-level shared/external storage directory for placing files of a particular type.

Usage

From source file:com.example.zf_android.trade.ApplyDetailActivity.java

private void setupItem(LinearLayout item, int itemType, final String key, final String value) {
    switch (itemType) {
    case ITEM_EDIT: {
        TextView tvKey = (TextView) item.findViewById(R.id.apply_detail_key);
        EditText etValue = (EditText) item.findViewById(R.id.apply_detail_value);

        if (!TextUtils.isEmpty(key))
            tvKey.setText(key);//from   w  ww. ja v  a2s.  c o m
        if (!TextUtils.isEmpty(value))
            etValue.setText(value);
        break;
    }
    case ITEM_CHOOSE: {
        TextView tvKey = (TextView) item.findViewById(R.id.apply_detail_key);
        TextView tvValue = (TextView) item.findViewById(R.id.apply_detail_value);

        if (!TextUtils.isEmpty(key))
            tvKey.setText(key);
        if (!TextUtils.isEmpty(value))
            tvValue.setText(value);
        break;
    }
    case ITEM_UPLOAD: {
        TextView tvKey = (TextView) item.findViewById(R.id.apply_detail_key);
        final TextView tvValue = (TextView) item.findViewById(R.id.apply_detail_value);

        if (!TextUtils.isEmpty(key))
            tvKey.setText(key);
        tvValue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                uploadingTextView = tvValue;
                AlertDialog.Builder builder = new AlertDialog.Builder(ApplyDetailActivity.this);
                final String[] items = getResources().getStringArray(R.array.apply_detail_upload);
                builder.setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                        case 0: {
                            Intent intent = new Intent();
                            intent.setType("image/*");
                            intent.setAction(Intent.ACTION_GET_CONTENT);
                            startActivityForResult(intent, REQUEST_UPLOAD_IMAGE);
                            break;
                        }
                        case 1: {
                            String state = Environment.getExternalStorageState();
                            if (state.equals(Environment.MEDIA_MOUNTED)) {
                                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                File outDir = Environment
                                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
                                if (!outDir.exists()) {
                                    outDir.mkdirs();
                                }
                                File outFile = new File(outDir, System.currentTimeMillis() + ".jpg");
                                photoPath = outFile.getAbsolutePath();
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outFile));
                                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                                startActivityForResult(intent, REQUEST_TAKE_PHOTO);
                            } else {
                                CommonUtil.toastShort(ApplyDetailActivity.this,
                                        getString(R.string.toast_no_sdcard));
                            }
                            break;
                        }
                        }
                    }
                });
                builder.show();

            }
        });
        break;
    }
    case ITEM_VIEW: {
        TextView tvKey = (TextView) item.findViewById(R.id.apply_detail_key);
        ImageButton ibView = (ImageButton) item.findViewById(R.id.apply_detail_view);

        if (!TextUtils.isEmpty(key))
            tvKey.setText(key);
        ibView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(ApplyDetailActivity.this, ImageViewer.class);
                i.putExtra("url", value);
                i.putExtra("justviewer", true);
                startActivity(i);
            }
        });
    }
    }
}

From source file:com.creativeongreen.imageeffects.MainActivity.java

private static Bitmap getBitmapFromExternalStorage(OnItemClickListener onItemClickListener, String file) {
    Bitmap bitmap = null;//ww w  .jav a  2s  .  co m

    String fullPathFile = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
            .getAbsolutePath().toString() + File.separator + DIR_STORAGE_IMAGE + File.separator + file;

    // take action to prevent OutOfMemoryError: bitmap sized VM budget
    // when executing BitmapFactory
    // Runtime.getRuntime().gc(); // not work on this
    // solution: down size sampling
    BitmapFactory.Options bmFactoryOptions = new BitmapFactory.Options();
    bmFactoryOptions.inJustDecodeBounds = true; // the decoder will return null (no bitmap)
    bitmap = BitmapFactory.decodeFile(fullPathFile, bmFactoryOptions);

    // calculate the down size scale factor
    int inSampleSize = 1;
    int targetWidth = 360;
    int targetHeight = 480;

    if (bmFactoryOptions.outHeight > targetHeight || bmFactoryOptions.outWidth > targetWidth) {

        // Calculate ratios of height and width to requested height and
        // width
        final int heightRatio = Math.round((float) bmFactoryOptions.outHeight / (float) targetHeight);
        final int widthRatio = Math.round((float) bmFactoryOptions.outWidth / (float) targetWidth);

        // Choose the smallest ratio as inSampleSize value, this will
        // guarantee
        // a final image with both dimensions larger than or equal to the
        // requested height and width.
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
    }

    // configure scale size
    bmFactoryOptions = new BitmapFactory.Options();
    bmFactoryOptions.inJustDecodeBounds = false; // the decoder will return bitmap
    bmFactoryOptions.inSampleSize = inSampleSize;
    bitmap = BitmapFactory.decodeFile(fullPathFile, bmFactoryOptions);

    return bitmap;
}

From source file:us.theparamountgroup.android.inventory.EditorActivity.java

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
            "Camera");
    File image = File.createTempFile(imageFileName, /* prefix */
            ".jpg", /* suffix */
            storageDir /* directory */
    );/*from www.  ja va  2 s.  c o m*/

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = "file:" + image.getAbsolutePath();
    Log.i(LOG_TAG, "in createImageFile mCurrentPhotoPath: " + mCurrentPhotoPath);
    return image;
}

From source file:org.awesomeapp.messenger.MainActivity.java

void startPhotoTaker() {

    // create Intent to take a picture and return control to the calling application
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    File photo = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
            "cs_" + new Date().getTime() + ".jpg");
    mLastPhoto = Uri.fromFile(photo);/*from   w  w w  . j  a va  2  s  .c  o m*/
    intent.putExtra(MediaStore.EXTRA_OUTPUT, mLastPhoto);

    // start the image capture Intent
    startActivityForResult(intent, ConversationDetailActivity.REQUEST_TAKE_PICTURE);
}

From source file:gov.cdc.epiinfo.RecordList.java

private void CreateDefaultsFile() {
    try {/*from   w  w  w . j a v  a 2s. c  om*/
        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        path.mkdirs();
        File file = new File(path, "/EpiInfo/defaults.xml");
        FileWriter fileWriter = new FileWriter(file);
        BufferedWriter out = new BufferedWriter(fileWriter);
        out.write("<Defaults Form=\"" + viewName + "\" Layout=\"-1\" />");
        out.close();
        Alert("Please restart the application for this action to take effect.");
        mnuSetDefault.setVisible(false);
        mnuExitDefault.setVisible(true);
    } catch (Exception ex) {

    }
}

From source file:com.affectiva.affdexme.MainActivity.java

private void processScreenshot(Bitmap drawingViewBitmap, boolean alsoSaveRaw) {
    if (mostRecentFrame == null) {
        Toast.makeText(getApplicationContext(), "No frame detected, aborting screenshot", Toast.LENGTH_SHORT)
                .show();/*from ww  w.  j  ava 2 s  . c  om*/
        return;
    }

    if (!storagePermissionsAvailable) {
        checkForStoragePermissions();
        return;
    }

    Bitmap faceBitmap = ImageHelper.getBitmapFromFrame(mostRecentFrame);

    if (faceBitmap == null) {
        Log.e(LOG_TAG, "Unable to generate bitmap for frame, aborting screenshot");
        return;
    }

    metricViewLayout.setDrawingCacheEnabled(true);
    Bitmap metricsBitmap = Bitmap.createBitmap(metricViewLayout.getDrawingCache());
    metricViewLayout.setDrawingCacheEnabled(false);

    Bitmap finalScreenshot = Bitmap.createBitmap(faceBitmap.getWidth(), faceBitmap.getHeight(),
            Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(finalScreenshot);
    Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG);

    canvas.drawBitmap(faceBitmap, 0, 0, paint);

    float scaleFactor = ((float) faceBitmap.getWidth()) / ((float) drawingViewBitmap.getWidth());
    int scaledHeight = Math.round(drawingViewBitmap.getHeight() * scaleFactor);
    canvas.drawBitmap(drawingViewBitmap, null, new Rect(0, 0, faceBitmap.getWidth(), scaledHeight), paint);

    scaleFactor = ((float) faceBitmap.getWidth()) / ((float) metricsBitmap.getWidth());
    scaledHeight = Math.round(metricsBitmap.getHeight() * scaleFactor);
    canvas.drawBitmap(metricsBitmap, null, new Rect(0, 0, faceBitmap.getWidth(), scaledHeight), paint);

    metricsBitmap.recycle();
    drawingViewBitmap.recycle();

    Date now = new Date();
    String timestamp = DateFormat.format("yyyy-MM-dd_hh-mm-ss", now).toString();
    File pictureFolder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            "AffdexMe");
    if (!pictureFolder.exists()) {
        if (!pictureFolder.mkdir()) {
            Log.e(LOG_TAG, "Unable to create directory: " + pictureFolder.getAbsolutePath());
            return;
        }
    }

    String screenshotFileName = timestamp + ".png";
    File screenshotFile = new File(pictureFolder, screenshotFileName);

    try {
        ImageHelper.saveBitmapToFileAsPng(finalScreenshot, screenshotFile);
    } catch (IOException e) {
        String msg = "Unable to save screenshot";
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
        Log.e(LOG_TAG, msg, e);
        return;
    }
    ImageHelper.addPngToGallery(getApplicationContext(), screenshotFile);

    if (alsoSaveRaw) {
        String rawScreenshotFileName = timestamp + "_raw.png";
        File rawScreenshotFile = new File(pictureFolder, rawScreenshotFileName);

        try {
            ImageHelper.saveBitmapToFileAsPng(faceBitmap, rawScreenshotFile);
        } catch (IOException e) {
            String msg = "Unable to save screenshot";
            Log.e(LOG_TAG, msg, e);
        }
        ImageHelper.addPngToGallery(getApplicationContext(), rawScreenshotFile);
    }

    faceBitmap.recycle();
    finalScreenshot.recycle();

    String fileSavedMessage = "Screenshot saved to: " + screenshotFile.getPath();
    Toast.makeText(getApplicationContext(), fileSavedMessage, Toast.LENGTH_SHORT).show();
    Log.d(LOG_TAG, fileSavedMessage);
}

From source file:gov.cdc.epiinfo.RecordList.java

private void DeleteDefaultsFile() {
    try {/*from  w ww  . jav a2  s.  c o  m*/
        File file1 = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                + "/EpiInfo/defaults.xml");
        file1.delete();
        Alert("Please restart the application for this action to take effect.");
        mnuSetDefault.setVisible(true);
        mnuExitDefault.setVisible(false);
    } catch (Exception ex) {

    }
}

From source file:com.gelakinetic.selfr.CameraActivity.java

/**
 * Create a File for saving an image/*from w ww . j a va 2  s .  c  o  m*/
 */
@Nullable
private File getOutputImageFile() {
    /* Make sure the external storage is mounted first */
    if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        return null;
    }

    /* Make a Selfr folder in the DCIM directory */
    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
            getString(R.string.app_name));

    /* Create the storage directory if it does not exist */
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            /* Can't make the folder */
            return null;
        }
    }

    /* Create a media file name */
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
    return new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
}

From source file:com.juce.JuceAppActivity.java

private static final String getFileLocation (String type)
{
    return Environment.getExternalStoragePublicDirectory (type).getAbsolutePath();
}

From source file:fiskinfoo.no.sintef.fiskinfoo.MapFragment.java

private void createSearchDialog() {
    final Dialog dialog = dialogInterface.getDialog(getActivity(), R.layout.dialog_search_tools,
            R.string.search_tools_title);

    final ScrollView scrollView = (ScrollView) dialog.findViewById(R.id.search_tools_dialog_scroll_view);
    final AutoCompleteTextView inputField = (AutoCompleteTextView) dialog
            .findViewById(R.id.search_tools_input_field);
    final LinearLayout rowsContainer = (LinearLayout) dialog.findViewById(R.id.search_tools_row_container);
    final Button viewInMapButton = (Button) dialog.findViewById(R.id.search_tools_view_in_map_button);
    final Button jumpToBottomButton = (Button) dialog.findViewById(R.id.search_tools_jump_to_bottom_button);
    Button dismissButton = (Button) dialog.findViewById(R.id.search_tools_dismiss_button);

    List<PropertyDescription> subscribables;
    PropertyDescription newestSubscribable = null;
    final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss",
            Locale.getDefault());
    Date cachedUpdateDateTime;//from  w ww .  j av a2s .  c  om
    Date newestUpdateDateTime;
    SubscriptionEntry cachedEntry;
    Response response;
    final JSONArray toolsArray;
    ArrayAdapter<String> adapter;
    String format = "JSON";
    String downloadPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
            .toString() + "/FiskInfo/Offline/";
    final JSONObject tools;
    final List<String> vesselNames;
    final Map<String, List<Integer>> toolIdMap = new HashMap<>();
    byte[] data = new byte[0];

    cachedEntry = user.getSubscriptionCacheEntry(getString(R.string.fishing_facility_api_name));

    if (fiskInfoUtility.isNetworkAvailable(getActivity())) {
        subscribables = barentswatchApi.getApi().getSubscribable();
        for (PropertyDescription subscribable : subscribables) {
            if (subscribable.ApiName.equals(getString(R.string.fishing_facility_api_name))) {
                newestSubscribable = subscribable;
                break;
            }
        }
    } else if (cachedEntry == null) {
        Dialog infoDialog = dialogInterface.getAlertDialog(getActivity(), R.string.tools_search_no_data_title,
                R.string.tools_search_no_data, -1);

        infoDialog.show();
        return;
    }

    if (cachedEntry != null) {
        try {
            cachedUpdateDateTime = simpleDateFormat
                    .parse(cachedEntry.mLastUpdated.equals(getActivity().getString(R.string.abbreviation_na))
                            ? "2000-00-00T00:00:00"
                            : cachedEntry.mLastUpdated);
            newestUpdateDateTime = simpleDateFormat
                    .parse(newestSubscribable != null ? newestSubscribable.LastUpdated : "2000-00-00T00:00:00");

            if (cachedUpdateDateTime.getTime() - newestUpdateDateTime.getTime() < 0) {
                response = barentswatchApi.getApi().geoDataDownload(newestSubscribable.ApiName, format);
                try {
                    data = FiskInfoUtility.toByteArray(response.getBody().in());
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (new FiskInfoUtility().writeMapLayerToExternalStorage(getActivity(), data,
                        newestSubscribable.Name.replace(",", "").replace(" ", "_"), format, downloadPath,
                        false)) {
                    SubscriptionEntry entry = new SubscriptionEntry(newestSubscribable, true);
                    entry.mLastUpdated = newestSubscribable.LastUpdated;
                    user.setSubscriptionCacheEntry(newestSubscribable.ApiName, entry);
                    user.writeToSharedPref(getActivity());
                }
            } else {
                String directoryFilePath = Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()
                        + "/FiskInfo/Offline/";

                File file = new File(directoryFilePath + newestSubscribable.Name + ".JSON");
                StringBuilder jsonString = new StringBuilder();
                BufferedReader bufferReader = null;

                try {
                    bufferReader = new BufferedReader(new FileReader(file));
                    String line;

                    while ((line = bufferReader.readLine()) != null) {
                        jsonString.append(line);
                        jsonString.append('\n');
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (bufferReader != null) {
                        try {
                            bufferReader.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                data = jsonString.toString().getBytes();
            }

        } catch (ParseException e) {
            e.printStackTrace();
            Log.e(TAG, "Invalid datetime provided");
        }
    } else {
        response = barentswatchApi.getApi().geoDataDownload(newestSubscribable.ApiName, format);
        try {
            data = FiskInfoUtility.toByteArray(response.getBody().in());
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (new FiskInfoUtility().writeMapLayerToExternalStorage(getActivity(), data,
                newestSubscribable.Name.replace(",", "").replace(" ", "_"), format, downloadPath, false)) {
            SubscriptionEntry entry = new SubscriptionEntry(newestSubscribable, true);
            entry.mLastUpdated = newestSubscribable.LastUpdated;
            user.setSubscriptionCacheEntry(newestSubscribable.ApiName, entry);
        }
    }

    try {
        tools = new JSONObject(new String(data));
        toolsArray = tools.getJSONArray("features");
        vesselNames = new ArrayList<>();
        adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_dropdown_item_1line, vesselNames);

        for (int i = 0; i < toolsArray.length(); i++) {
            JSONObject feature = toolsArray.getJSONObject(i);
            String vesselName = (feature.getJSONObject("properties").getString("vesselname") != null
                    && !feature.getJSONObject("properties").getString("vesselname").equals("null"))
                            ? feature.getJSONObject("properties").getString("vesselname")
                            : getString(R.string.vessel_name_unknown);
            List<Integer> toolsIdList = toolIdMap.get(vesselName) != null ? toolIdMap.get(vesselName)
                    : new ArrayList<Integer>();

            if (vesselName != null && !vesselNames.contains(vesselName)) {
                vesselNames.add(vesselName);
            }

            toolsIdList.add(i);
            toolIdMap.put(vesselName, toolsIdList);
        }

        inputField.setAdapter(adapter);
    } catch (JSONException e) {
        dialogInterface.getAlertDialog(getActivity(), R.string.search_tools_init_error,
                R.string.search_tools_init_info, -1).show();
        Log.e(TAG, "JSON parse error");
        e.printStackTrace();

        return;
    }

    if (searchToolsButton.getTag() != null) {
        inputField.requestFocus();
        inputField.setText(searchToolsButton.getTag().toString());
        inputField.selectAll();
    }

    inputField.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String selectedVesselName = ((TextView) view).getText().toString();
            List<Integer> selectedTools = toolIdMap.get(selectedVesselName);
            Gson gson = new Gson();
            String toolSetDateString;
            Date toolSetDate;

            rowsContainer.removeAllViews();

            for (int toolId : selectedTools) {
                JSONObject feature;
                Feature toolFeature;

                try {
                    feature = toolsArray.getJSONObject(toolId);

                    if (feature.getJSONObject("geometry").getString("type").equals("LineString")) {
                        toolFeature = gson.fromJson(feature.toString(), LineFeature.class);
                    } else {
                        toolFeature = gson.fromJson(feature.toString(), PointFeature.class);
                    }

                    toolSetDateString = toolFeature.properties.setupdatetime != null
                            ? toolFeature.properties.setupdatetime
                            : "2038-00-00T00:00:00";
                    toolSetDate = simpleDateFormat.parse(toolSetDateString);

                } catch (JSONException | ParseException e) {
                    dialogInterface.getAlertDialog(getActivity(), R.string.search_tools_init_error,
                            R.string.search_tools_init_info, -1).show();
                    e.printStackTrace();

                    return;
                }

                ToolSearchResultRow row = rowsInterface.getToolSearchResultRow(getActivity(),
                        R.drawable.ikon_kystfiske, toolFeature);
                long toolTime = System.currentTimeMillis() - toolSetDate.getTime();
                long highlightCutoff = ((long) getResources().getInteger(R.integer.milliseconds_in_a_day))
                        * ((long) getResources().getInteger(R.integer.days_to_highlight_active_tool));

                if (toolTime > highlightCutoff) {
                    int colorId = ContextCompat.getColor(getActivity(), R.color.error_red);
                    row.setDateTextViewTextColor(colorId);
                }

                rowsContainer.addView(row.getView());
            }

            viewInMapButton.setEnabled(true);
            inputField.setTag(selectedVesselName);
            searchToolsButton.setTag(selectedVesselName);
            jumpToBottomButton.setVisibility(View.VISIBLE);
            jumpToBottomButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new Handler().post(new Runnable() {
                        @Override
                        public void run() {
                            scrollView.scrollTo(0, rowsContainer.getBottom());
                        }
                    });
                }
            });

        }
    });

    viewInMapButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String vesselName = inputField.getTag().toString();
            highlightToolsInMap(vesselName);

            dialog.dismiss();
        }
    });

    dismissButton.setOnClickListener(onClickListenerInterface.getDismissDialogListener(dialog));
    dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
    dialog.show();
}