Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import android.content.Context;
import android.content.CursorLoader;
import android.database.Cursor;

import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

public class Main {
    public static String getDataDirectoryLocation() {
        return (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath());
    }

    /**
     * Using code from this link: http://hmkcode.com/android-display-selected-image-and-its-real-path/
     * This method will return the absolute path Android.net.Uri.
     * NOTE!!! THIS DOES NOT SUPPORT API 10 OR BELOW!!! IF YOU NEED TO WORK WITH THAT, CHECK LINK ABOVE
     * @param context Context
     * @param uri Uri to check
     * @return String for the absolute path
     */
    public static String getAbsolutePath(Context context, android.net.Uri uri) {
        if (Build.VERSION.SDK_INT >= 19) {
            try {
                String filePath = "";
                String wholeID = DocumentsContract.getDocumentId(uri);

                // Split at colon, use second item in the array
                String id = wholeID.split(":")[1];

                String[] column = { MediaStore.Images.Media.DATA };

                // where id is equal to
                String sel = MediaStore.Images.Media._ID + "=?";

                Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        column, sel, new String[] { id }, null);

                int columnIndex = cursor.getColumnIndex(column[0]);

                if (cursor.moveToFirst()) {
                    filePath = cursor.getString(columnIndex);
                }
                cursor.close();
                return filePath;

            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        } else {
            try {
                String[] proj = { MediaStore.Images.Media.DATA };
                String result = null;

                CursorLoader cursorLoader = new CursorLoader(context, uri, proj, null, null, null);
                Cursor cursor = cursorLoader.loadInBackground();

                if (cursor != null) {
                    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    cursor.moveToFirst();
                    result = cursor.getString(column_index);
                }
                return result;

            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    }
}