powered by simpleCommunicator - 2.0.49     © 2025 Programmizd 02
Форумы / Android [игнор отключен] [закрыт для гостей] / реальный путь к файлу
12 сообщений из 12, страница 1 из 1
реальный путь к файлу
    #39936570
Romantiktj
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
пытаюсь взять полный путь из к папке (folder) с помощью Intent.ACTION_OPEN_DOCUMENT_TREE , ошибка в context:this

Кто сталкивался?

Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
     
                Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
                //intent.setType("file/*");
                startActivityForResult(intent, READ_REQUEST_CODE);
              Uri uri = intent.getData();

                Uri uri1 = intent.getData();
                Uri docUri = null;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                    docUri = DocumentsContract.buildDocumentUriUsingTree(uri1,DocumentsContract.getTreeDocumentId(uri));
                    String path = getPath.getPath([color=red]this[/color], docUri);
                    folder_path.setText(path);
                }
...
Рейтинг: 0 / 0
реальный путь к файлу
    #39936580
Romantiktj
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Romantiktj,

Получилось взять вот это :

content://com.android.externalstorage.documents/tree/13E4-440C%3ADCIM



Теперь мне нужно взять из этого реальный путь к папке DCIM , как быть дальше?

Так правильно ли? : com.android.externalstorage.documents/tree/13E4-440C%3ADCIM

Или ещё как то?
...
Рейтинг: 0 / 0
реальный путь к файлу
    #39936590
Фотография wadman
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Если нужно выбрать картинку, то проще/надежнее использовать встроенные средства:

https://stackoverflow.com/questions/5309190/android-pick-images-from-gallery

Или нужна любая выбранная пользователем папка?
...
Рейтинг: 0 / 0
реальный путь к файлу
    #39936606
chpasha
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
какой ужас. у меня такое впечатление, что поймали на улице человека и усадили за комп программировать. что ни тема - волосы дыбом.
...
Рейтинг: 0 / 0
реальный путь к файлу
    #39936628
Romantiktj
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
wadman,
Угадали, нужна выбранная пользователем папка!
...
Рейтинг: 0 / 0
реальный путь к файлу
    #39936646
Romantiktj
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Romantiktj,
То есть нужен путь к папке в String формате для дальнейшего высчитывания из него файлов
...
Рейтинг: 0 / 0
реальный путь к файлу
    #39936650
Фотография wadman
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Romantiktj,

это и есть полноценный путь к файлам. Или хочется чего-нибудь более привычного?
Uri.parse https://developer.android.com/reference/android/net/Uri#parse(java.lang.String)
...
Рейтинг: 0 / 0
реальный путь к файлу
    #39936710
Romantiktj
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
wadman,
Короче надобно из Intenta взять

Код: java
1.
  Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);



и конвертировать в таком виде:

/storage/emulated/0/1.txt

Так как пришлось протестировать через:

Код: java
1.
InputStream file = new FileInputStream(new File("/storage/emulated/0/1.txt"));  //- это работает
...
Рейтинг: 0 / 0
реальный путь к файлу
    #39936727
Romantiktj
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Romantiktj,

Нашел решение , но не могу найти причину ошибки: String path = FileUtil.getFullPathFromTreeUri(treeUri,this);

This will give you the actual path of the selected folder (assuming the selected folder resides in external storage or external sd card)

Код: java
1.
2.
Uri treeUri = data.getData();
String path = FileUtil.getFullPathFromTreeUri(treeUri,this); 



where FileUtil is the following class

Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
public final class FileUtil {
    static String TAG="TAG";
    private static final String PRIMARY_VOLUME_NAME = "primary";

    @Nullable
    public static String getFullPathFromTreeUri(@Nullable final Uri treeUri, Context con) {
        if (treeUri == null) return null;
        String volumePath = getVolumePath(getVolumeIdFromTreeUri(treeUri),con);
        if (volumePath == null) return File.separator;
        if (volumePath.endsWith(File.separator))
            volumePath = volumePath.substring(0, volumePath.length() - 1);

        String documentPath = getDocumentPathFromTreeUri(treeUri);
        if (documentPath.endsWith(File.separator))
            documentPath = documentPath.substring(0, documentPath.length() - 1);

        if (documentPath.length() > 0) {
            if (documentPath.startsWith(File.separator))
                return volumePath + documentPath;
            else
                return volumePath + File.separator + documentPath;
        }
        else return volumePath;
    }


    @SuppressLint("ObsoleteSdkInt")
    private static String getVolumePath(final String volumeId, Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) return null;
        try {
            StorageManager mStorageManager =
                    (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
            Class<?> storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
            Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
            Method getUuid = storageVolumeClazz.getMethod("getUuid");
            Method getPath = storageVolumeClazz.getMethod("getPath");
            Method isPrimary = storageVolumeClazz.getMethod("isPrimary");
            Object result = getVolumeList.invoke(mStorageManager);

            final int length = Array.getLength(result);
            for (int i = 0; i < length; i++) {
                Object storageVolumeElement = Array.get(result, i);
                String uuid = (String) getUuid.invoke(storageVolumeElement);
                Boolean primary = (Boolean) isPrimary.invoke(storageVolumeElement);

                // primary volume?
                if (primary && PRIMARY_VOLUME_NAME.equals(volumeId))
                    return (String) getPath.invoke(storageVolumeElement);

                // other volumes?
                if (uuid != null && uuid.equals(volumeId))
                    return (String) getPath.invoke(storageVolumeElement);
            }
            // not found.
            return null;
        } catch (Exception ex) {
            return null;
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private static String getVolumeIdFromTreeUri(final Uri treeUri) {
        final String docId = DocumentsContract.getTreeDocumentId(treeUri);
        final String[] split = docId.split(":");
        if (split.length > 0) return split[0];
        else return null;
    }


    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private static String getDocumentPathFromTreeUri(final Uri treeUri) {
        final String docId = DocumentsContract.getTreeDocumentId(treeUri);
        final String[] split = docId.split(":");
        if ((split.length >= 2) && (split[1] != null)) return split[1];
        else return File.separator;
    }
}
...
Рейтинг: 0 / 0
реальный путь к файлу
    #39936892
Romantiktj
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Romantiktj,

Нашёл решение:

Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
    private int REQUEST_OPEN_DOCUMENT_TREE = 1;

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void openDocumentTree() {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
        //intent.putExtra("android.content.extra.SHOW_ADVANCED", true);
        startActivityForResult(intent, REQUEST_OPEN_DOCUMENT_TREE);
    }


   @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        if (requestCode == REQUEST_OPEN_DOCUMENT_TREE) {
            Uri folderUri = data.getData();

            if (folderUri != null) {
                Log.d(TAG, "folderUri -> " + folderUri.toString());
                String path = GetPathUtils.getDirectoryPathFromUri(this, folderUri);

                Log.d(TAG, "path -> " + path);

                if (!TextUtils.isEmpty(path)) {
                    folder_path.setText(path);   ////Полный реальный путь!
                } else {
                    folder_path.setText("Path null! ");
                }
            }
        }




    }



И сам класс преобразования в реальный путь:


Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.
183.
184.
185.
186.
187.
188.
189.
190.
191.
192.
193.
194.
195.
196.
197.
198.
199.
200.
201.
202.
203.
204.
205.
206.
207.
208.
209.
210.
211.
212.
213.
214.
215.
216.
217.
218.
219.
220.
221.
222.
223.
224.
225.
226.
227.
228.
229.
230.
231.
232.
233.
234.
235.
236.
237.
238.
239.
240.
241.
242.
243.
244.
245.
246.
247.
248.
249.
package qonun;

import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Kimcy929 on 13/03/2018.
 */


@SuppressWarnings("WeakerAccess")
public class GetPathUtils {

    private static final String PATH_TREE = "tree";
    private static final String PRIMARY_TYPE = "primary";
    private static final String RAW_TYPE = "raw";

    @TargetApi(Build.VERSION_CODES.KITKAT)
    public static String getFilePathFromUri(final Context context, final Uri uri) {

        // DocumentProvider
        if (DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                //Timber.d("docId -> %s", docId);
                final String[] split = docId.split(":");
                final String type = split[0];

                if (PRIMARY_TYPE.equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                } else {
                    // TODO handle non-primary volumes
                    StringBuilder path = new StringBuilder();
                    String pathSegment[] = docId.split(":");
                    return path.append(getRemovableStorageRootPath(context, pathSegment[0])).append(File.separator).append(pathSegment[1]).toString();
                }
            } else if (isDownloadsDocument(uri)) {  // DownloadsProvider

                final String id = DocumentsContract.getDocumentId(uri);

               // Timber.d("download id -> %s", id);

                if (id.contains("raw:")) {
                    return id.substring(id.indexOf(File.separator));
                } else {
                    Uri contentUri = ContentUris.withAppendedId(
                            Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                    return getDataColumn(context, contentUri, null, null);
                }

            } else if (isMediaDocument(uri)) {  // MediaProvider
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) { // MediaStore (and general)
            return getDataColumn(context, uri, null, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) { // File
            return uri.getPath();
        }

        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {

        Cursor cursor = null;
        final String column = MediaStore.MediaColumns.DATA;
        final String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }

        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri
     * @return file path of Uri
     */
    public static String getDirectoryPathFromUri(Context context, Uri uri) {

        if ("file".equals(uri.getScheme())) {
            return uri.getPath();
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
                && isTreeUri(uri)) {

            String treeId = getTreeDocumentId(uri);

            if (treeId != null) {

                //Timber.d("TreeId -> %s", treeId);

                String[] paths = treeId.split(":");
                String type = paths[0];
                String subPath = paths.length == 2 ? paths[1] : "";

                if (RAW_TYPE.equalsIgnoreCase(type)) {
                    return treeId.substring(treeId.indexOf(File.separator));
                } else if (PRIMARY_TYPE.equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + File.separator + subPath;
                } else {
                    StringBuilder path = new StringBuilder();
                    String[] pathSegment = treeId.split(":");
                    if (pathSegment.length == 1) {
                        path.append(getRemovableStorageRootPath(context, paths[0]));
                    } else {
                        String rootPath = getRemovableStorageRootPath(context, paths[0]);
                        path.append(rootPath).append(File.separator).append(pathSegment[1]);
                    }

                    return path.toString();
                }
            }
        }
        return null;
    }

    private static String getRemovableStorageRootPath(Context context, String storageId) {
        StringBuilder rootPath = new StringBuilder();
        File[] externalFilesDirs = ContextCompat.getExternalFilesDirs(context, null);
        for (File fileDir : externalFilesDirs) {
            if (fileDir.getPath().contains(storageId)) {
                String[] pathSegment = fileDir.getPath().split(File.separator);
                for (String segment : pathSegment) {
                    if (segment.equals(storageId)) {
                        rootPath.append(storageId);
                        break;
                    }
                    rootPath.append(segment).append(File.separator);
                }
                //rootPath.append(fileDir.getPath().split("/Android")[0]); // faster
                break;
            }
        }
        return rootPath.toString();
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public static List<String> getListRemovableStorage(Context context) {

        List<String> paths = new ArrayList<>();

        File[] externalFilesDirs = ContextCompat.getExternalFilesDirs(context, null);
        for (File fileDir : externalFilesDirs) {
            if (Environment.isExternalStorageRemovable(fileDir)) {
                //Timber.d("ext-raw-path -> %s", fileDir.getAbsolutePath());
                String path = fileDir.getPath();
                if (path.contains("/Android")) {
                    paths.add(path.substring(0, path.indexOf("/Android")));
                }
            }
        }

        return paths;
    }

    //https://github.com/rcketscientist/DocumentActivity/blob/master/library/src/main/java/com/anthonymandra/framework/DocumentUtil.java#L56
    /**
     * Extract the via {@link DocumentsContract.Document#COLUMN_DOCUMENT_ID} from the given URI.
     * From {@link DocumentsContract} but return null instead of throw
     */
    public static String getTreeDocumentId(Uri uri) {
        final List<String> paths = uri.getPathSegments();
        if (paths.size() >= 2 && PATH_TREE.equals(paths.get(0))) {
            return paths.get(1);
        }
        return null;
    }

    public static boolean isTreeUri(Uri uri) {
        final List<String> paths = uri.getPathSegments();
        return (paths.size() == 2 && PATH_TREE.equals(paths.get(0)));
    }
}
...
Рейтинг: 0 / 0
реальный путь к файлу
    #39936894
Romantiktj
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Спасибо всем за участие!
...
Рейтинг: 0 / 0
реальный путь к файлу
    #39936895
Фотография wadman
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Romantiktj
String path = FileUtil.getFullPathFromTreeUri(treeUri,this);

Это контекст и всё, что от него наследуется.
https://developer.android.com/reference/android/content/Context

Раскрой по ссылке список Known indirect subclasses
...
Рейтинг: 0 / 0
12 сообщений из 12, страница 1 из 1
Форумы / Android [игнор отключен] [закрыт для гостей] / реальный путь к файлу
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]