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:ch.uzh.supersede.feedbacklibrary.utils.Utils.java

@NonNull
private static String captureScreenshot(final Activity activity) {
    // Create the 'Screenshots' folder if it does not already exist
    File screenshotDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            SCREENSHOTS_DIR_NAME);//from w  w w  .j  ava 2 s .  co m
    screenshotDir.mkdirs();

    // Image name 'Screenshot_YearMonthDay-HourMinuteSecondMillisecond.png'
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    String imageName = "Screenshot_" + calendar.get(Calendar.YEAR) + (calendar.get(Calendar.MONTH) + 1)
            + calendar.get(Calendar.DAY_OF_MONTH);
    imageName += "-" + calendar.get(Calendar.HOUR_OF_DAY) + calendar.get(Calendar.MINUTE)
            + calendar.get(Calendar.SECOND) + calendar.get(Calendar.MILLISECOND) + ".png";
    File screenshotFile = new File(screenshotDir, imageName);

    // Create the screenshot file
    try {
        if (screenshotFile.exists()) {
            screenshotFile.delete();
        }
        screenshotFile.createNewFile();
    } catch (IOException e) {
        Log.e(TAG, "Failed to create a new file", e);
    }

    // Capture the current screen
    View rootView = activity.getWindow().getDecorView().getRootView();
    rootView.setDrawingCacheEnabled(true);
    Bitmap imageBitmap = Bitmap.createBitmap(rootView.getDrawingCache());
    rootView.setDrawingCacheEnabled(false);

    FileOutputStream fos;
    try {
        fos = new FileOutputStream(screenshotFile);
        imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
        fos.flush();
        fos.close();
    } catch (Exception e) {
        Log.e(TAG, "Failed to write the bitmap to the file", e);
    }

    // Add the screenshot image to the Media Provider's database
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    Uri contentUri = Uri.fromFile(screenshotFile);
    mediaScanIntent.setData(contentUri);
    activity.sendBroadcast(mediaScanIntent);

    return screenshotFile.getAbsolutePath();
}

From source file:com.exercise.AndroidClient.RecvFrom.java

private Uri getDestFileUri() throws IOException {

    // map "music" to Environment.DIRECTORY_MUSIC 
    String destDir = destDirTypes.get(destinationType);
    if (destDir == null)
        throw new IllegalArgumentException("Invalid destination dir type : " + destinationType);

    // get the public 'standard directory', ie Download, Music etc
    File dir = Environment.getExternalStoragePublicDirectory(destDir);

    // add any subdir asked by caller & create dir struct upto the subdir if required
    dir = new File(dir, subDir);
    if (!dir.exists() || !dir.isDirectory()) {
        if (!dir.mkdirs())
            throw new IOException("Failed to create directories : " + dir.toString());
    }/*  ww w  .j a va 2 s . co  m*/

    // the full path to the file
    File path = new File(dir, filename);
    return Uri.fromFile(path);
}

From source file:com.example.locationproject.wifidirect.WiFiDirectActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);//from  ww  w .java  2  s .  c  om

    // add necessary intent values to be matched.

    intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);

    manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
    channel = manager.initialize(this, getMainLooper(), null);
    Log.d(TAG, "Deleting healthplus folder at slave");
    File f = new File(
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath()
                    + "/location");
    if (f.exists()) {
        try {
            FileUtils.deleteDirectory(f);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        Log.d("WifiDirectActivity", "downloads folder for slave is empty");
    }
    Log.d("WifiDirectACtivity", "calling FileLocatoe service");
    Intent i = new Intent(this, FileLocator.class);
    // Add extras to the bundle
    //i.putExtra("foo", "bar");
    // Start the service
    startService(i);
}

From source file:com.giovanniterlingen.windesheim.controllers.DownloadController.java

@Override
protected String doInBackground(final String... strings) {
    try {/*from w w  w.j  ava 2s. c  om*/
        activeDownloads.put(contentId, new Download());
        int lastSlash = url.lastIndexOf('/');
        String fileName = url.substring(lastSlash + 1);

        File directory = Environment.getExternalStoragePublicDirectory(
                ApplicationLoader.applicationContext.getResources().getString(R.string.app_name));
        if (!directory.exists()) {
            directory.mkdirs();
        }

        final String encodedUrl = new URI("https", "elo.windesheim.nl", url, null).toString();

        downloadManager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(encodedUrl));
        request.addRequestHeader("Cookie", new CookieController().getNatSchoolCookie()).setTitle(fileName)
                .setDescription(activity.getResources().getString(R.string.downloading))
                .setDestinationInExternalPublicDir(File.separator
                        + ApplicationLoader.applicationContext.getResources().getString(R.string.app_name),
                        fileName);

        currentDownloadId = downloadManager.enqueue(request);
        while (true) {
            if (isCancelled()) {
                return "cancelled";
            }
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(currentDownloadId);
            Cursor cursor = downloadManager.query(query);
            if (cursor.getCount() == 0) {
                return "cancelled";
            }
            cursor.moveToFirst();
            int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
            if (status == DownloadManager.STATUS_SUCCESSFUL || status == DownloadManager.STATUS_FAILED) {
                break;
            }
            if (status == DownloadManager.STATUS_PAUSED || status == DownloadManager.STATUS_PENDING) {
                // paused, reset download state to pending
                activeDownloads.put(contentId, new Download());
                NotificationCenter.getInstance().postNotificationName(NotificationCenter.downloadPending,
                        studyRouteId, adapterPosition, contentId);
                Thread.sleep(100);
                continue;
            }
            long downloaded = cursor
                    .getLong(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
            long total = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
            cursor.close();
            if (total > 0 && downloaded > 0) {
                int progress = (int) (downloaded * 100 / total);
                String s = Formatter.formatFileSize(activity, downloaded) + "/"
                        + Formatter.formatFileSize(activity, total);
                activeDownloads.get(contentId).setProgress(progress);
                activeDownloads.get(contentId).setProgressString(s);
                publishProgress(progress, s);
            }
            Thread.sleep(100);
        }
        return new File(directory, fileName).getAbsolutePath();
    } catch (SecurityException e) {
        return "permission";
    } catch (Exception e) {
        return null;
    }
}

From source file:ru.gkpromtech.exhibition.media.FullImageActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_full_image);

    Bundle extras = getIntent().getExtras();
    items = (List<Media>) extras.getSerializable("items");
    files = (List<String>) extras.getSerializable("files");
    int index = extras.getInt("index");

    if (items != null)
        mode = SHOW_ITEMS_MODE;//from   www  .j  av  a  2 s .  c  o  m
    else if (files != null)
        mode = SHOW_FILES_MODE;

    final View controlsView = findViewById(R.id.fullscreen_content_controls);
    final ViewPager pager = (ViewPager) findViewById(R.id.pager);

    appDirectoryName = getResources().getString(R.string.app_name);
    imageRoot = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            appDirectoryName);

    // ViewPager and its adapters use support library
    // fragments, so use getSupportFragmentManager.
    pager.setAdapter(new FullImagePagerAdapter(getSupportFragmentManager()));
    pager.setCurrentItem(index);
    if (mode == SHOW_ITEMS_MODE)
        setTitle(items.get(index).name);
    else if (mode == SHOW_FILES_MODE)
        setTitle(new File(files.get(index)).getName());
    else
        setTitle("Photo");

    // Set up an instance of SystemUiHider to control the system UI for
    // this activity.
    mSystemUiHider = SystemUiHider.getInstance(this, pager, HIDER_FLAGS);
    mSystemUiHider.setup();
    mSystemUiHider.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
        // Cached values.
        int mControlsHeight;
        int mShortAnimTime;

        @Override
        public void onVisibilityChange(boolean visible) {
            // If the ViewPropertyAnimator API is available
            // (Honeycomb MR2 and later), use it to animate the
            // in-layout UI controls at the bottom of the
            // screen.
            if (mControlsHeight == 0) {
                mControlsHeight = controlsView.getHeight();
            }
            if (mShortAnimTime == 0) {
                mShortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
            }
            controlsView.animate().translationY(visible ? 0 : mControlsHeight).setDuration(mShortAnimTime);

            if (visible && AUTO_HIDE) {
                // Schedule a hide().
                delayedHide(AUTO_HIDE_DELAY_MILLIS);
            }
        }
    });

    pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int i, float v, int i2) {
        }

        @Override
        public void onPageSelected(int index) {
            if (mode == SHOW_ITEMS_MODE)
                setTitle(items.get(index).name);
            else if (mode == SHOW_FILES_MODE)
                setTitle(new File(files.get(index)).getName());
            else
                setTitle("Photo");
        }

        @Override
        public void onPageScrollStateChanged(int i) {
        }
    });

    // Upon interacting with UI controls, delay any scheduled hide()
    // operations to prevent the jarring behavior of controls going away
    // while interacting with the UI.
    pager.setOnTouchListener(mDelayHideTouchListener);
}

From source file:com.example.healthplus.wifidirect.WiFiDirectActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);//  w w  w . j a  va2s .  c om

    // add necessary intent values to be matched.

    intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);

    manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
    channel = manager.initialize(this, getMainLooper(), null);
    Log.d(TAG, "Deleting healthplus folder at slave");
    File f = new File(
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath()
                    + "/healthplus");
    if (f.exists()) {
        try {
            FileUtils.deleteDirectory(f);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        Log.d("WifiDirectActivity", "downloads folder for slave is empty");
    }
    Intent i = new Intent(this, FileLocator.class);
    // Add extras to the bundle
    //i.putExtra("foo", "bar");
    // Start the service
    startService(i);
}

From source file:org.benetech.secureapp.activities.BulletinToMbaFileExporter.java

@Override
public void onZipped(Bulletin bulletin, AsyncTaskResult<File> zippedTaskResult) {
    if (zippedTaskResult.getException() != null) {
        indeterminateDialog.dismissAllowingStateLoss();
        setResult(Activity.RESULT_CANCELED);

        return;/*w  w w  .  ja  va 2  s . co m*/
    }

    try {
        final File externalStoragePublicDirectory = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
        final String fileName = getApplicationName() + "_" + bulletin.toFileName() + MBA_FILE_EXTENSION;
        final File destinationFile = new File(externalStoragePublicDirectory, fileName);
        FileUtils.copyFile(zippedTaskResult.getResult(), destinationFile);

        ZipFile zipFile = new ZipFile(zippedTaskResult.getResult());
        BulletinZipUtilities.validateIntegrityOfZipFilePackets(store.getAccountId(), zipFile, getSecurity());
    } catch (Exception e) {
        Log.e(TAG, getString(R.string.error_message_error_verifying_zip_file), e);
        indeterminateDialog.dismissAllowingStateLoss();
        Toast.makeText(this, getString(R.string.failure_zipping_bulletin), Toast.LENGTH_SHORT).show();
        setResult(Activity.RESULT_CANCELED);
        finish();
        return;
    }

    indeterminateDialog.dismissAllowingStateLoss();
    if (zippedTaskResult.getResult() == null) {
        setResult(Activity.RESULT_CANCELED);
        Toast.makeText(this, getString(R.string.failure_zipping_bulletin), Toast.LENGTH_SHORT).show();
        return;
    }

    setResult(Activity.RESULT_OK);
    finish();
}

From source file:no.digipost.android.utilities.FileUtilities.java

public static File getDownloadsStorageDir(String fileName) throws Exception {
    File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
            fileName);//from  w w  w .j  av  a2  s  . c  om
    try {
        file.createNewFile();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return file;
}

From source file:org.golang.app.WViewActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Fixed Portrait orientation
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    /*this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
    WindowManager.LayoutParams.FLAG_FULLSCREEN);*/

    setContentView(R.layout.webview);//w w  w  . j  a va 2  s .  c  o m
    WebView webView = (WebView) findViewById(R.id.webView1);

    initWebView(webView);
    webView.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            Log.d("JavaGoWV: ", url);

            final Pattern p = Pattern.compile("dcoinKey&password=(.*)$");
            final Matcher m = p.matcher(url);
            if (m.find()) {
                try {
                    Thread thread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                //File root = android.os.Environment.getExternalStorageDirectory();
                                File dir = Environment
                                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
                                Log.d("JavaGoWV", "dir " + dir);

                                URL keyUrl = new URL(
                                        "http://127.0.0.1:8089/ajax?controllerName=dcoinKey&first=1"); //you can write here any link
                                //URL keyUrl = new URL("http://yandex.ru/"); //you can write here any link
                                File file = new File(dir, "dcoin-key.png");

                                long startTime = System.currentTimeMillis();
                                Log.d("JavaGoWV", "download begining");
                                Log.d("JavaGoWV", "download keyUrl:" + keyUrl);

                                /* Open a connection to that URL. */
                                URLConnection ucon = keyUrl.openConnection();

                                Log.d("JavaGoWV", "0");
                                /*
                                * Define InputStreams to read from the URLConnection.
                                */
                                InputStream is = ucon.getInputStream();

                                Log.d("JavaGoWV", "01");

                                BufferedInputStream bis = new BufferedInputStream(is);

                                Log.d("JavaGoWV", "1");
                                /*
                                * Read bytes to the Buffer until there is nothing more to read(-1).
                                */
                                ByteArrayBuffer baf = new ByteArrayBuffer(5000);
                                int current = 0;
                                while ((current = bis.read()) != -1) {
                                    baf.append((byte) current);
                                }

                                Log.d("JavaGoWV", "2");
                                /* Convert the Bytes read to a String. */
                                FileOutputStream fos = new FileOutputStream(file);
                                fos.write(baf.toByteArray());
                                fos.flush();
                                fos.close();

                                Log.d("JavaGoWV", "3");
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                                    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                                    Uri contentUri = Uri.fromFile(file);
                                    mediaScanIntent.setData(contentUri);
                                    WViewActivity.this.sendBroadcast(mediaScanIntent);
                                } else {
                                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                                            Uri.parse("file://" + Environment.getExternalStorageDirectory())));
                                }

                                Log.d("JavaGoWV", "4");
                            } catch (Exception e) {
                                Log.e("JavaGoWV error 0", e.toString());
                                e.printStackTrace();
                            }
                        }
                    });
                    thread.start();

                } catch (Exception e) {
                    Log.e("JavaGoWV error", e.toString());
                    e.printStackTrace();
                }
            }
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            Log.e("JavaGoWV", "shouldOverrideUrlLoading " + url);

            if (url.endsWith(".mp4")) {
                Intent in = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(in);
                return true;
            } else {
                return false;
            }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            Log.d("JavaGoWV",
                    "failed: " + failingUrl + ", error code: " + errorCode + " [" + description + "]");
        }
    });

    SystemClock.sleep(1500);
    //if (MyService.DcoinStarted(8089)) {
    webView.loadUrl("http://localhost:8089/");
    //}

}

From source file:com.wallerlab.compcellscope.Image_Gallery.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_image__gallery);
    counter = 0;//  w  w w.  j a  va 2s .c  o m
    final ImageView currPic = new ImageView(this);

    DisplayMetrics metrics = this.getResources().getDisplayMetrics();
    final int screen_width = metrics.widthPixels;

    SharedPreferences settings = getSharedPreferences(Folder_Chooser.PREFS_NAME, 0);
    //SharedPreferences.Editor edit = settings.edit();
    String path = settings.getString(Folder_Chooser.location_name,
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString());

    //Log.d(LOG, "  |  " + path + " |  ");
    TextView text1 = (TextView) findViewById(R.id.text1);
    final TextView text2 = (TextView) findViewById(R.id.text2);

    text1.setText(path);

    File directory = new File(path);

    // get all the files from a directory
    File[] dump_files = directory.listFiles();
    Log.d(LOG, dump_files.length + " ");

    final File[] fList = removeElements(dump_files, "info.json");

    Log.d(LOG, "Filtered Length: " + fList.length);

    Arrays.sort(fList, new Comparator<File>() {
        @Override
        public int compare(File file, File file2) {
            String one = file.toString();
            String two = file2.toString();
            //Log.d(LOG, "one: " + one);
            //Log.d(LOG, "two: " + two);
            int num_one = Integer.parseInt(one.substring(one.lastIndexOf("(") + 1, one.lastIndexOf(")")));
            int num_two = Integer.parseInt(two.substring(two.lastIndexOf("(") + 1, two.lastIndexOf(")")));
            return num_one - num_two;
        }
    });

    try {
        writeJsonFile(fList);
    } catch (JSONException e) {
        Log.d(LOG, "JSON WRITE FAILED");
    }
    //List names programattically
    LinearLayout myLinearLayout = (LinearLayout) findViewById(R.id.linear_table);
    final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT, screen_width + 4);

    myLinearLayout.setOrientation(LinearLayout.VERTICAL);

    if (fList != null) {
        File cur_pic = fList[0];

        BitmapFactory.Options opts = new BitmapFactory.Options();
        Log.d(LOG, "\n File Location: " + cur_pic.getAbsolutePath() + " \n" + " Parent: "
                + cur_pic.getParent().toString() + "\n");

        Bitmap myImage = BitmapFactory.decodeFile(cur_pic.getAbsolutePath(), opts);

        currPic.setLayoutParams(params);
        currPic.setImageBitmap(myImage);
        currPic.setId(View.generateViewId());
        text2.setText(cur_pic.getName());
    }

    myLinearLayout.addView(currPic);

    //Seekbar
    seekBar = (SeekBar) findViewById(R.id.seekBar);
    seekBar.setEnabled(true);
    seekBar.setMax(fList.length - 1);
    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        int progress = 0;
        int length = fList.length;

        @Override
        public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
            setCounter(i);
            if (getCounter() <= fList.length) {
                File cur_pic = fList[getCounter()];
                BitmapFactory.Options opts = new BitmapFactory.Options();
                opts.inJustDecodeBounds = true;
                Bitmap myImage = BitmapFactory.decodeFile(cur_pic.getAbsolutePath(), opts);
                int image_width = opts.outWidth;
                int image_height = opts.outHeight;
                int sampleSize = image_width / screen_width;
                opts.inSampleSize = sampleSize;

                text2.setText(cur_pic.getName());

                opts.inJustDecodeBounds = false;
                myImage = BitmapFactory.decodeFile(cur_pic.getAbsolutePath(), opts);

                currPic.setImageBitmap(myImage);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });

    //Make Button Layout
    LinearLayout buttonLayout = new LinearLayout(this);
    buttonLayout.setOrientation(LinearLayout.HORIZONTAL);

    LinearLayout.LayoutParams LLParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f);
    buttonLayout.setLayoutParams(LLParams);
    buttonLayout.setId(View.generateViewId());

    //Button Layout Params
    LinearLayout.LayoutParams param_button = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);

    //Prev Pic
    Button prevPic = new Button(this);
    prevPic.setText("Previous");
    prevPic.setId(View.generateViewId());
    prevPic.setLayoutParams(param_button);

    prevPic.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (fList != null) {
                decrementCounter();
                if (getCounter() >= 0) {
                    File cur_pic = fList[getCounter()];
                    BitmapFactory.Options opts = new BitmapFactory.Options();
                    opts.inJustDecodeBounds = true;
                    Bitmap myImage = BitmapFactory.decodeFile(cur_pic.getAbsolutePath(), opts);
                    int image_width = opts.outWidth;
                    int image_height = opts.outHeight;
                    int sampleSize = image_width / screen_width;
                    opts.inSampleSize = sampleSize;

                    text2.setText(cur_pic.getName());

                    opts.inJustDecodeBounds = false;
                    myImage = BitmapFactory.decodeFile(cur_pic.getAbsolutePath(), opts);
                    //Log.d(LOG, getCounter() + "");
                    seekBar.setProgress(getCounter());
                    currPic.setImageBitmap(myImage);

                } else {
                    setCounter(0);
                }

            } else {
                Toast.makeText(Image_Gallery.this, "There are no pictures in this folder", Toast.LENGTH_SHORT);
                setCounter(getCounter() - 1);
            }
        }
    });

    buttonLayout.addView(prevPic);

    // Next Picture  Button
    Button nextPic = new Button(this);
    nextPic.setText("Next");
    nextPic.setId(View.generateViewId());
    nextPic.setLayoutParams(param_button);

    buttonLayout.addView(nextPic);
    nextPic.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (fList != null) {
                incrementCounter();
                if (getCounter() < fList.length) {
                    File cur_pic = fList[getCounter()];
                    BitmapFactory.Options opts = new BitmapFactory.Options();
                    opts.inJustDecodeBounds = true;
                    Bitmap myImage = BitmapFactory.decodeFile(cur_pic.getAbsolutePath(), opts);
                    int image_width = opts.outWidth;
                    int image_height = opts.outHeight;
                    int sampleSize = image_width / screen_width;
                    opts.inSampleSize = sampleSize;

                    text2.setText(cur_pic.getName());

                    opts.inJustDecodeBounds = false;
                    myImage = BitmapFactory.decodeFile(cur_pic.getAbsolutePath(), opts);
                    //Log.d(LOG, getCounter() + "");
                    seekBar.setProgress(getCounter());

                    currPic.setImageBitmap(myImage);
                } else {
                    setCounter(getCounter() - 1);
                }

            } else {
                Toast.makeText(Image_Gallery.this, "There are no pictures in this folder", Toast.LENGTH_SHORT);
                setCounter(getCounter() - 1);
            }
        }
    });

    myLinearLayout.addView(buttonLayout);
}