Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import android.content.ContentResolver;

import android.database.Cursor;

import android.net.Uri;

import java.io.File;

import java.util.ArrayList;

public class Main {
    public static String getSdCardPath(ContentResolver cr, Uri uri, String defaultPath) {
        ArrayList files = new ArrayList();
        if (uri != null) {
            Cursor mCursor = cr.query(uri, null, null, null, null);
            if (mCursor != null) {
                while (mCursor.moveToNext()) {
                    String path = mCursor.getString(mCursor.getColumnIndexOrThrow("_data"));
                    if (!path.contains(defaultPath)) {
                        String parentFolder = (new File(path)).getParent();
                        if (!files.contains(parentFolder)) {
                            files.add(parentFolder);
                        }
                    }
                }
            }
        }

        return getCommonSubStringFromList(files);
    }

    private static String getCommonSubStringFromList(ArrayList<String> list) {
        if (list != null && list.size() > 0) {
            String[] tokens = ((String) list.get(0)).split("/");
            String path = null;
            String temp = "";

            for (int i = 0; i < tokens.length; ++i) {
                if (!tokens[i].trim().isEmpty()) {
                    temp = temp + "/" + tokens[i];
                    if (isValidSubString(list, temp)) {
                        path = temp;
                    }
                }
            }

            return path;
        } else {
            return null;
        }
    }

    private static boolean isValidSubString(ArrayList<String> list, String token) {
        if (list != null) {
            for (int i = 0; i < list.size(); ++i) {
                if (!((String) list.get(i)).startsWith(token)) {
                    return false;
                }
            }

            return true;
        } else {
            return false;
        }
    }
}