Example usage for android.os Environment getDataDirectory

List of usage examples for android.os Environment getDataDirectory

Introduction

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

Prototype

public static File getDataDirectory() 

Source Link

Document

Return the user data directory.

Usage

From source file:Main.java

public static void saveDBInSdcard(Context pContext, String pDatabaseName) {
    try {/*from   w w  w. j a v a2 s  .  com*/
        File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();

        if (sd.canWrite()) {
            String currentDBPath = "//data//" + pContext.getPackageName() + "//databases//" + pDatabaseName;
            String backupDBPath = pDatabaseName;
            File currentDB = new File(data, currentDBPath);
            File backupDB = new File(sd, backupDBPath);

            FileChannel src = new FileInputStream(currentDB).getChannel();
            FileChannel dst = new FileOutputStream(backupDB).getChannel();
            dst.transferFrom(src, 0, src.size());
            src.close();
            dst.close();
            Toast.makeText(pContext, backupDB.toString(), Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        Toast.makeText(pContext, e.toString(), Toast.LENGTH_LONG).show();
    }
}

From source file:Main.java

@Deprecated
public static boolean checkRomSpaceEnough(long limitSize) {
    long allSize;
    long availableSize = 0;
    try {// w w  w  .  j a v  a  2 s .  com
        File data = Environment.getDataDirectory();
        StatFs sf = new StatFs(data.getPath());
        availableSize = (long) sf.getAvailableBlocks() * (long) sf.getBlockSize();
        allSize = (long) sf.getBlockCount() * (long) sf.getBlockSize();
    } catch (Exception e) {
        allSize = 0;
    }

    if (allSize != 0 && availableSize > limitSize) {
        return true;
    }
    return false;
}

From source file:Main.java

public static void backupDb(File currentDB) {
    try {/*from w  ww.  j a  va2  s.com*/

        File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();

        if (sd.canWrite()) {
            File f = new File(sd.getAbsolutePath() + "/AccountManagement");
            if (!f.exists()) {
                f.mkdir();
            }
            Date currentDate = new Date();
            String currentDateStr = newFormat1.format(currentDate);

            currentDateStr = currentDateStr.trim();
            System.out.println(
                    "---------------------------------------------------------------" + currentDateStr);
            String backupDBPath = "AccountManagement/backup_" + currentDateStr + ".db";
            File backupDB = new File(sd, backupDBPath);

            if (currentDB.exists()) {
                FileChannel src = new FileInputStream(currentDB).getChannel();
                FileChannel dst = new FileOutputStream(backupDB).getChannel();
                dst.transferFrom(src, 0, src.size());
                src.close();
                dst.close();
            }
        }
    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:com.handlerexploit.news.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final String defaultInternalCacheDirectory = Environment.getDataDirectory().getPath() + "/data/"
            + getPackageName() + "/databases/";

    ArticlesProvider.init(defaultInternalCacheDirectory);
    WeatherProvider.init(defaultInternalCacheDirectory);

    // TODO//from  w  ww .  ja  va2s.co  m
    new Thread(new Runnable() {
        public void run() {
            clearFolder(new File(defaultInternalCacheDirectory), 1);
            runOnUiThread(new Runnable() {
                public void run() {
                    setupViews();
                }
            });
        }
    }).start();
}

From source file:com.gigathinking.simpleapplock.SetupGestureLock.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    changeLock = getIntent().getBooleanExtra(AppLockApplication.CHANGELOCK, false);
    String message = changeLock ? getString(R.string.change_gesture) : getString(R.string.create_gesture);
    setContentView(R.layout.layout_unlockwithgesture);
    File gestureFile = new File(Environment.getDataDirectory() + "/data/" + getPackageName(),
            AppLockApplication.GESTUREFILE);
    GestureOverlayView gestureOverlayView = (GestureOverlayView) findViewById(R.id.gestureOverlayView);
    gestureOverlayView.addOnGestureListener(new GestureProcessor());
    findViewById(R.id.id_ll_icon).setVisibility(View.GONE);
    findViewById(R.id.id_btn_forgot_gesture).setVisibility(View.GONE);
    ((TextView) findViewById(R.id.tv_unlock_message)).setText(message);
    first = true;//from w ww .j  a va 2s .  c om
    library = GestureLibraries.fromFile(gestureFile);
}

From source file:com.gigathinking.simpleapplock.UnlockWithGesture.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_unlockwithgesture);
    GestureOverlayView view = (GestureOverlayView) findViewById(R.id.gestureOverlayView);
    view.addOnGestureListener(new GestureProcessor());
    File gestureFile = new File(Environment.getDataDirectory() + "/data/" + getPackageName(),
            AppLockApplication.GESTUREFILE);
    library = GestureLibraries.fromFile(gestureFile);
    Bundle bundle = getIntent().getExtras();
    mPackage = bundle.getString(Intent.EXTRA_TEXT);
    unlockSelf = bundle.getBoolean(AppLockApplication.UNLOCK_SELF);
    changeLock = false;/*from  w  ww. j a v a 2  s  .  c o  m*/
    changeLock = bundle.getBoolean(AppLockApplication.CHANGELOCK);
}

From source file:fr.eoit.activity.EOITActivity.java

/**
 * Called when the activity is first created.
 *//*  www  .  j av  a  2s .  c  o m*/
@Override
public void onCreate(Bundle savedInstanceState) {

    loadParametersOnCreate = false;

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    disableConnectionReuseIfNecessary();
    enableHttpResponseCache();

    bar = (ProgressBar) findViewById(R.id.progressBar);
    bar.setIndeterminate(true);
    infoTextView = (TextView) findViewById(R.id.textView);

    File path = Environment.getDataDirectory();
    StatFs stat = new StatFs(path.getPath());
    long blockSize = stat.getBlockSize();
    long availableBlocks = stat.getAvailableBlocks();

    if (blockSize * availableBlocks > EOITConst.APPLICATION_SIZE) {
        new LoadItemsAsyncTask().execute(this);
    } else {
        new AlertDialog.Builder(this).setCancelable(false).setTitle(R.string.database_no_space)
                .setMessage(getResources().getString(R.string.database_no_space_message,
                        EOITConst.APPLICATION_SIZE / (1024 * 1024)))
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setNegativeButton(R.string.database_locked_close_button_message,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int whichButton) {
                                finish();
                            }
                        })
                .create().show();
    }
}

From source file:nl.creativeskills.cordova.imageresize.ImageResize.java

@Override
public boolean execute(String action, JSONArray data, CallbackContext callbackContext) {
    PluginResult result = null;/*from  w w w. j ava 2  s  .  co m*/
    LOG.d(TAG, action.toString());
    LOG.d(TAG, TAG + ": " + Environment.getDataDirectory().toString());

    JSONObject params;
    String imageData;
    String imageDataType;
    String format;
    Bitmap bmp;
    try {
        //parameters (forst object of the json array)
        params = data.getJSONObject(0);
        //image data, either base64 or url
        imageData = params.getString("data");
        //which data type is that, defaults to base64
        imageDataType = params.has("imageDataType") ? params.getString("imageDataType")
                : DEFAULT_IMAGE_DATA_TYPE;
        LOG.d(TAG, action.toString() + ".imageDataType: " + imageDataType + ": "
                + params.getString("imageDataType"));
        //which format should be used, defaults to jpg
        format = params.has("format") ? params.getString("format") : DEFAULT_FORMAT;
        //create the Bitmap object, needed for all functions
        bmp = getBitmap(imageData, imageDataType);

    } catch (JSONException e) {
        LOG.d(TAG, action.toString() + ": " + e.getMessage());
        callbackContext.sendPluginResult(new PluginResult(Status.JSON_EXCEPTION, e.getMessage()));
        return false;
    } catch (IOException e) {
        LOG.d(TAG, action.toString() + ": " + e.getMessage());
        callbackContext.sendPluginResult(new PluginResult(Status.ERROR, e.getMessage()));
        return false;
    }
    //resize the image
    if (action.equals("resizeImage")) {
        try {
            LOG.d(TAG, "action.equals(" + action.toString() + ")");
            double widthFactor;
            double heightFactor;

            //compression quality
            int quality = params.getInt("quality");

            //Pixels or Factor resize
            String resizeType = params.getString("resizeType");

            //Get width and height parameters
            double width = params.getDouble("width");
            double height = params.getDouble("height");

            //return object
            JSONObject res = new JSONObject();

            LOG.d(TAG, "action.equals(" + action.toString() + "): params converted");

            if (resizeType.equals(RESIZE_TYPE_PIXEL)) {
                widthFactor = width / ((double) bmp.getWidth());
                heightFactor = height / ((double) bmp.getHeight());
            } else {
                widthFactor = width;
                heightFactor = height;
            }

            LOG.d(TAG, "action.equals(" + action.toString() + "): start resize");

            Bitmap resized = getResizedBitmap(bmp, (float) widthFactor, (float) heightFactor);

            if (imageDataType.equals(IMAGE_DATA_TYPE_BASE64)) {

                ByteArrayOutputStream baos = new ByteArrayOutputStream();

                if (format.equals(FORMAT_PNG)) {
                    resized.compress(Bitmap.CompressFormat.PNG, quality, baos);
                } else {
                    resized.compress(Bitmap.CompressFormat.JPEG, quality, baos);
                }

                byte[] b = baos.toByteArray();
                String returnString = Base64.encodeToString(b, Base64.DEFAULT);

                res.put("imageData", returnString);

                LOG.d(TAG, "action.equals(" + action.toString() + "):base64 encode the resized Image");
            } else {
                // Obligatory Parameters, throw JSONException if not found
                String filename = params.getString("filename");
                //filename = (filename.contains(".")) ? filename : filename + "." + format;
                String directory = params.getString("directory");
                if (directory.startsWith("file:")) {
                    directory = directory.replace("file://", "");
                } else {
                    directory = directory.startsWith("/") ? directory : "/" + directory;
                    directory = Environment.getExternalStorageDirectory().toString() + directory;
                }

                LOG.d(TAG, "action.equals(" + action.toString() + "): resized Image and save to " + directory
                        + filename);

                OutputStream outStream;
                //store the file locally using the external storage directory
                File file = new File(directory, filename);

                try {
                    outStream = new FileOutputStream(file);
                    if (format.equals(FORMAT_PNG)) {
                        bmp.compress(Bitmap.CompressFormat.PNG, quality, outStream);
                    } else {
                        bmp.compress(Bitmap.CompressFormat.JPEG, quality, outStream);
                    }
                    outStream.flush();
                    outStream.close();

                    res.put("url", "file://" + file.getAbsolutePath());
                    res.put("size", file.length());

                } catch (IOException e) {
                    result = new PluginResult(Status.ERROR, e.getMessage());
                    callbackContext.sendPluginResult(result);

                    return false;
                }
            }

            res.put("width", resized.getWidth());
            res.put("height", resized.getHeight());

            LOG.d(TAG, action.toString() + ": Should be successfull");

            result = new PluginResult(Status.OK, res);
            callbackContext.sendPluginResult(result);

            return true;
        } catch (JSONException e) {
            LOG.d(TAG, action.toString() + ": " + e.getMessage());
            result = new PluginResult(Status.JSON_EXCEPTION, e.getMessage());
            callbackContext.sendPluginResult(result);

            return false;
        }
    } else if (action.equals("imageSize")) {
        try {

            JSONObject res = new JSONObject();
            res.put("width", bmp.getWidth());
            res.put("height", bmp.getHeight());

            result = new PluginResult(Status.OK, res);
            callbackContext.sendPluginResult(result);

            return true;
        } catch (JSONException e) {
            result = new PluginResult(Status.JSON_EXCEPTION, e.getMessage());
            callbackContext.sendPluginResult(result);

            return false;
        }
    } else if (action.equals("storeImage")) {
        try {
            // Obligatory Parameters, throw JSONException if not found
            String filename = params.getString("filename");
            filename = (filename.contains(".")) ? filename : filename + "." + format;
            String directory = params.getString("directory");
            directory = directory.startsWith("/") ? directory : "/" + directory;
            int quality = params.getInt("quality");

            OutputStream outStream;
            //store the file locally using the external storage directory
            File file = new File(Environment.getExternalStorageDirectory().toString() + directory, filename);
            try {
                outStream = new FileOutputStream(file);
                if (format.equals(FORMAT_PNG)) {
                    bmp.compress(Bitmap.CompressFormat.PNG, quality, outStream);
                } else {
                    bmp.compress(Bitmap.CompressFormat.JPEG, quality, outStream);
                }
                outStream.flush();
                outStream.close();
                JSONObject res = new JSONObject();
                res.put("url", "file://" + file.getAbsolutePath());
                res.put("size", file.length());

                result = new PluginResult(Status.OK, res);
                callbackContext.sendPluginResult(result);

                return true;
            } catch (IOException e) {
                result = new PluginResult(Status.ERROR, e.getMessage());
                callbackContext.sendPluginResult(result);

                return false;
            }
        } catch (JSONException e) {
            result = new PluginResult(Status.JSON_EXCEPTION, e.getMessage());
            callbackContext.sendPluginResult(result);

            return false;
        }
    } else if (action.equals("storePDF")) {
        try {
            // Obligatory Parameters, throw JSONException if not found
            String filename = params.getString("filename");
            filename = (filename.contains(".")) ? filename : filename + "." + format;
            String directory = params.getString("directory");
            directory = directory.startsWith("/") ? directory : "/" + directory;

            OutputStream outStream;
            //store the file locally using the external storage directory
            File file = new File(Environment.getExternalStorageDirectory().toString() + directory, filename);
            try {
                byte[] pdfAsBytes = Base64.decode(imageData.toString(), 0);
                outStream = new FileOutputStream(file);

                outStream.write(pdfAsBytes);
                outStream.flush();
                outStream.close();
                JSONObject res = new JSONObject();
                res.put("url", "file://" + file.getAbsolutePath());

                result = new PluginResult(Status.OK, res);
                callbackContext.sendPluginResult(result);

                return true;
            } catch (IOException e) {
                result = new PluginResult(Status.ERROR, e.getMessage());
                callbackContext.sendPluginResult(result);

                return false;
            }
        } catch (JSONException e) {
            result = new PluginResult(Status.JSON_EXCEPTION, e.getMessage());
            callbackContext.sendPluginResult(result);

            return false;
        }
    } else {
        callbackContext.sendPluginResult(new PluginResult(Status.ERROR));

        return false;
    }

}

From source file:com.watabou.noosa.Game.java

@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
public static long getAvailableInternalMemorySize() {
    File path = Environment.getDataDirectory();
    StatFs stat = new StatFs(path.getPath());
    long ret;//  w  ww  .jav a  2  s .co m
    if (android.os.Build.VERSION.SDK_INT < 18) {
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        ret = availableBlocks * blockSize;
    } else {
        ret = stat.getAvailableBytes();
    }
    Util.storeEventInAcra("FreeInternalMemorySize", Long.toString(ret));
    return ret;
}

From source file:com.fallahpoor.infocenter.fragments.StorageFragment.java

@SuppressWarnings("deprecation")
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
private String getInternalTotal() {

    long size;/*from w  ww  .j a  v a 2  s  . c om*/
    StatFs internalStatFs = new StatFs(Environment.getDataDirectory().getAbsolutePath());

    if (mIsApiAtLeast18) {
        size = internalStatFs.getTotalBytes();
    } else {
        size = (long) internalStatFs.getBlockCount() * (long) internalStatFs.getBlockSize();
    }

    return Utils.getFormattedSize(size);

}