Я пытался получить чтение, редактирование, управление хранилищем в Android Java, но разрешение на вывод было отклонено иJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Я пытался получить чтение, редактирование, управление хранилищем в Android Java, но разрешение на вывод было отклонено и

Сообщение Anonymous »

Я разработал приложение, которое может читать все документы, такие как PDF, а также офисные PowerPoint, Excel, Word
и основное действие, которое я хочу показать список всех документов, доступных на устройстве, чтобы пользователь мог открыть любой документ внутри приложения, а не только просматриваю файлы из хранилища.
Я пробовал этот код, но он не работал, пробовал еще несколько решений в stackoverflow и на других веб-сайтах, но в конце ничего не получилось.
мой код
mainactivity
перед созданием

Код: Выделить всё

private static final int PDF_SELECTION_CODE = 200;
private static final int PERMISSION_REQUEST_CODE = 100;
private RecyclerView recyclerView;
private DocumentAdapter documentAdapter;
private ArrayList documentList;
внутри при создании

Код: Выделить всё

recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
loadDocuments();
} else {
loadDocuments();
}

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
// Scoped Storage
loadDocumentsWithScopedStorage();
} else {
// Legacy Storage
loadDocumentsWithScopedStorage();
}

loadDocumentsWithMediaStore();

после создания

Код: Выделить всё

private void getDocuments(@NonNull File dir) {
File[] files = dir.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
getDocuments(file);
} else if (file.getName().endsWith(".pdf") ||
file.getName().endsWith(".doc") ||
file.getName().endsWith(".docx") ||
file.getName().endsWith(".txt")) {
documentList.add(file);
}
}
}
}

private void loadDocumentsWithScopedStorage() {
documentList = new ArrayList();
Uri collection = MediaStore.Files.getContentUri("external");

String[] projection = {
MediaStore.Files.FileColumns.DATA,
MediaStore.Files.FileColumns.DISPLAY_NAME
};

// Filter for specific document types
String selection = MediaStore.Files.FileColumns.MIME_TYPE + " IN (?, ?, ?, ?)";
String[] selectionArgs = new String[]{
"application/pdf",
"application/msword",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"text/plain"
};

Cursor cursor = getContentResolver().query(collection, projection, selection, selectionArgs, null);

if (cursor != null) {
int dataIndex = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);

while (cursor.moveToNext()) {
String filePath = cursor.getString(dataIndex);
File file = new File(filePath);
documentList.add(file);
}
cursor.close();
}

documentAdapter = new DocumentAdapter(documentList, file -> {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(android.net.Uri.fromFile(file), "*/*");
startActivity(intent);
});
recyclerView.setAdapter(documentAdapter);
}

private void loadDocumentsWithMediaStore() {
documentList = new ArrayList();
Uri collection = MediaStore.Files.getContentUri("external");

String[] projection = {
MediaStore.Files.FileColumns.DATA,
MediaStore.Files.FileColumns.DISPLAY_NAME
};

String selection = MediaStore.Files.FileColumns.MIME_TYPE + "  IN (?, ?, ?, ?)";
String[] selectionArgs = new String[]{
"application/pdf",
"application/msword",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"text/plain"
};

try (Cursor cursor = getContentResolver().query(collection, projection, selection, selectionArgs, null)) {
if (cursor != null) {
int dataIndex = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);

while (cursor.moveToNext()) {
String filePath = cursor.getString(dataIndex);
File file = new File(filePath);
documentList.add(file);
}
}
}

documentAdapter = new DocumentAdapter(documentList, file -> {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(android.net.Uri.fromFile(file), "*/*");
startActivity(intent);
});
recyclerView.setAdapter(documentAdapter);
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
loadDocuments();
} else {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
}
}
}

Адаптер документа

Код: Выделить всё

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

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

public class DocumentAdapter extends RecyclerView.Adapter {

private final ArrayList documentList;
private final OnDocumentClickListener listener;

public DocumentAdapter(ArrayList documentList, OnDocumentClickListener listener) {
this.documentList = documentList;
this.listener = listener;
}

@NonNull
@Override
public DocumentViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
return new DocumentViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull DocumentViewHolder holder, int position) {
File document = documentList.get(position);
holder.textView.setText(document.getName());
holder.itemView.setOnClickListener(v -> listener.onDocumentClick(document));
}

@Override
public int getItemCount() {
return documentList.size();
}

public interface OnDocumentClickListener {
void onDocumentClick(File file);
}

static class DocumentViewHolder extends RecyclerView.ViewHolder {
TextView textView;

public DocumentViewHolder(@NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(android.R.id.text1);
}
}
}
Я испробовал все решения: просмотр вопросов stackoverflow, поиск в Google и запрос Gemini и Chatgpt.
Код не работает и не показывает список файлов документов.
Ошибка кода не отображается, и когда я запускаю приложение, выводится только всплывающее сообщение «Разрешение отклонено».

Подробнее здесь: https://stackoverflow.com/questions/793 ... mission-de
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»