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.annotation.SuppressLint;

import android.content.Context;

import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

public class Main {
    @SuppressLint("NewApi")
    public static String uriToPath(Context activity, Uri uri) {
        if (null == uri) {
            return null;
        }
        String urlStr = uri.toString();
        if (urlStr.startsWith("file://")) {
            return uri.getPath();
        }
        Cursor cursor = null;
        String idWhere;
        String id;
        String[] columns = { MediaStore.Images.Media.DATA };
        try {
            if (Build.VERSION.SDK_INT == 19 && DocumentsContract.isDocumentUri(activity, uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                id = split[1];
                idWhere = MediaStore.Images.Media._ID + "=?";
                cursor = activity.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,
                        idWhere, new String[] { id }, null);
            } else {
                cursor = activity.getContentResolver().query(uri, columns, null, null, null);
            }
            if (cursor != null) {
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                if (cursor.moveToFirst()) {
                    return cursor.getString(column_index);
                }
            }
        } catch (Exception e) {
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return null;
    }
}