英文:
How to handle loading large amounts of data in android
问题
以下是代码片段的翻译部分:
FileListFragment.java:
public class FileListFragment extends Fragment implements FilesStateManager {
// ... (省略部分代码) ...
private void init(){
fileManager = new FileManager(getContext());
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
grantPermissionContainer.setVisibility(View.VISIBLE);
fileListRecyclerView.setVisibility(View.GONE);
}
// ... (省略部分代码) ...
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// ... (省略部分代码) ...
}
private void readFiles(){
fileObjects = fileManager.readFiles(currentPath, selectedFiles);
setupRecyclerView();
}
// ... (省略部分代码) ...
}
AppListFragment.java:
public class AppListFragment extends Fragment implements AppsStateManager {
// ... (省略部分代码) ...
private void getInstalledApps(){
apps = appsManager.getInstalledApps();
selectAllTextView.setText("Select All (" + apps.size() + ")");
}
// ... (省略部分代码) ...
}
ContactListFragment.java:
public class ContactListFragment extends Fragment implements ContactsStateManager {
// ... (省略部分代码) ...
private void readContacts(){
contacts = contactsManager.getContacts();
selectAllTextView.setText("Select All (" + contacts.size() + ")");
}
// ... (省略部分代码) ...
}
AppsManager.java:
public class AppsManager {
// ... (省略部分代码) ...
public ArrayList<App> getInstalledApps(){
PackageManager packageManager = this.packageManager;
ArrayList<App> apps = new ArrayList<>();
// ... (省略部分代码) ...
return apps;
}
// ... (省略部分代码) ...
}
ContactsManager.java:
public class ContactsManager {
// ... (省略部分代码) ...
public ArrayList<Contact> getContacts(){
ContentResolver cr = contentResolver;
ArrayList<Contact> contacts = new ArrayList<>();
// ... (省略部分代码) ...
return contacts;
}
// ... (省略部分代码) ...
}
FileManager.java:
public class FileManager {
// ... (省略部分代码) ...
public ArrayList<FileObject> readFiles(String path, ArrayList<FileObject> selectedFiles){
ArrayList<FileObject> filesList = new ArrayList<>();
// ... (省略部分代码) ...
return filesList;
}
// ... (省略部分代码) ...
}
请注意,以上翻译仅涵盖了代码的部分片段,未被省略的部分仍然保持原文不变。如果您需要完整的翻译,请使用机器翻译工具或在线翻译服务。
英文:
I have an activity with a button upon clicking which opens a new activity with 3 fragments with tab layout, The first fragment loads files from the internal storage in recyclerview, 2nd one loads installed apps in recyclerview and the 3rd loads contacts in a recyclerview, But the problem I'm facing is that when I click the button to launch the activity it takes 2-3 seconds to launch the activity & I tested it on a device which contained a lot of apps and contacts it crashed the app and didn't opened the activity, I think this is because it is taking time to load all the data at once, How can I solve this problem?
This is the code from the fragments
FileListFragment.java
public class FileListFragment extends Fragment implements FilesStateManager {
private static final String TAG = "FileListFragment";
RecyclerView fileListRecyclerView,currentPathRecyclerView;
TextView currentPathTextView;
ArrayList<FileObject> fileObjects = new ArrayList<>();
ArrayList<FileObject> currentFolders = new ArrayList<>();
static ArrayList<FileObject> selectedFiles = new ArrayList<>();
String currentPath = "";
String initialPath = "";
String pathToShow = "/";
RelativeLayout grantPermissionContainer;
Button grantPermissionButton;
FileManager fileManager;
static DataSelectedManager dataSelectedManager;
public FileListFragment(DataSelectedManager dataSelectedManager) {
this.dataSelectedManager = dataSelectedManager;
}
private final int PERMISSION_CODE = 100;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_file_list,container,false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
currentPathRecyclerView = view.findViewById(R.id.current_folder_recyclerview);
fileListRecyclerView = view.findViewById(R.id.folder_list_recyclerview);
grantPermissionContainer = view.findViewById(R.id.grant_permission_container);
grantPermissionButton = view.findViewById(R.id.grant_permission_button);
init();
}
private void init(){
fileManager = new FileManager(getContext());
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
grantPermissionContainer.setVisibility(View.VISIBLE);
fileListRecyclerView.setVisibility(View.GONE);
}
grantPermissionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (Build.VERSION.SDK_INT < 16) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},PERMISSION_CODE);
} else {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE},PERMISSION_CODE);
}
}
});
try{
String path = getActivity().getExternalFilesDir(null).getPath();
currentPath = path.split("Android")[0];
initialPath = currentPath;
FileObject fileObject = new FileObject("/",initialPath,null,true,"none","0",false);
currentFolders.add(fileObject);
setupCurrentPathRecyclerView();
readFiles();
Log.d(TAG, "init: " + path);
}
catch (Exception e){
e.printStackTrace();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
Log.d(TAG, "onRequestPermissionsResult: Called");
if (requestCode == PERMISSION_CODE){
Log.d(TAG, "onRequestPermissionsResult: Codes matched");
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Log.d(TAG, "onRequestPermissionsResult: Permission Granted");
grantPermissionContainer.setVisibility(View.GONE);
fileListRecyclerView.setVisibility(View.VISIBLE);
FileObject fileObject = new FileObject("/",initialPath,null,true,"none","0",false);
currentFolders.add(fileObject);
setupCurrentPathRecyclerView();
readFiles();
}
}
}
private void readFiles(){
fileObjects = fileManager.readFiles(currentPath,selectedFiles);
setupRecyclerView();
}
private void setupRecyclerView(){
FileListAdapter fileListAdapter = new FileListAdapter(fileObjects,selectedFiles,getContext(),this);
fileListRecyclerView.setAdapter(fileListAdapter);
fileListRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
}
private void setupCurrentPathRecyclerView(){
FolderPathAdapter folderPathAdapter = new FolderPathAdapter(currentFolders,getContext(),this);
currentPathRecyclerView.setAdapter(folderPathAdapter);
currentPathRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL,false));
currentPathRecyclerView.smoothScrollToPosition(currentFolders.size());
}
@Override
public void folderClicked(FileObject fileObject) {
currentPath = fileObject.getPath();
currentFolders.add(fileObject);
currentPathRecyclerView.getAdapter().notifyItemInserted(currentFolders.size() - 1);
currentPathRecyclerView.smoothScrollToPosition(currentFolders.size());
readFiles();
}
@Override
public void pathFolderClicked(FileObject fileObject) {
Log.d(TAG, "pathFolderClicked: Called");
if (!fileObject.getPath().equals(currentFolders.get(currentFolders.size() - 1).getPath())){
for (FileObject folder : currentFolders){
if (folder.getPath().equals(fileObject.getPath())){
int index = currentFolders.indexOf(folder) + 1;
int size = currentFolders.size();
currentFolders = new ArrayList<>(currentFolders.subList(0,index));
Log.d(TAG, "pathFolderClicked: Number of item " + (size - index) + " Index: " + index);
// currentPathRecyclerView.getAdapter().notifyItemRangeRemoved(index,size - index);
setupCurrentPathRecyclerView();
currentPath = currentFolders.get(currentFolders.size() - 1).getPath();
readFiles();
Log.d(TAG, "pathFolderClicked: Notified");
}
}
Log.d(TAG, "pathFolderClicked: " + Arrays.toString(currentFolders.toArray()));
}
}
@Override
public void fileSelected(FileObject fileObject) {
selectedFiles.add(fileObject);
dataSelectedManager.dataSelected();
}
@Override
public void fileDeselected(FileObject fileObject) {
ArrayList<FileObject> filesToRemove = new ArrayList<>();
for (FileObject fileObject1 : selectedFiles){
if (fileObject.getPath().equals(fileObject1.getPath())){
filesToRemove.add(fileObject1);
}
}
dataSelectedManager.dataDeSelected();
selectedFiles.removeAll(filesToRemove);
}
public static void triggerDataTransfer(){
dataSelectedManager.sendSelectedFiles(selectedFiles);
}
}
AppListFragment.java
public class AppListFragment extends Fragment implements AppsStateManager {
RecyclerView appListRecyclerView;
TextView selectAllTextView;
CheckBox selectAllCheckBox;
static ArrayList<App> apps = new ArrayList<>();
AppsManager appsManager;
static DataSelectedManager dataSelectedManager;
public AppListFragment(DataSelectedManager dataSelectedManager) {
this.dataSelectedManager = dataSelectedManager;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_app_list,container,false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
appListRecyclerView = view.findViewById(R.id.app_recycler_view);
selectAllTextView = view.findViewById(R.id.select_all_text_view);
selectAllCheckBox = view.findViewById(R.id.select_all_checkbox);
appsManager = new AppsManager(getActivity().getPackageManager(),getActivity().getApplicationContext().getPackageName());
getInstalledApps();
setupRecyclerView();
selectAllCheckBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!selectAllCheckBox.isChecked()){
for (App app : apps){
if (app.isSelected()){
app.setSelected(false);
dataSelectedManager.dataDeSelected();
}
}
}
else {
for (App app : apps){
if (!app.isSelected()){
app.setSelected(true);
dataSelectedManager.dataSelected();
}
}
}
appListRecyclerView.getAdapter().notifyDataSetChanged();
}
});
}
private void getInstalledApps(){
apps = appsManager.getInstalledApps();
selectAllTextView.setText("Select All (" + apps.size() + ")");
}
private void setupRecyclerView(){
AppListAdapter appListAdapter = new AppListAdapter(apps,getContext(),this);
appListRecyclerView.setAdapter(appListAdapter);
appListRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
}
@Override
public void deSelected() {
selectAllCheckBox.setChecked(false);
dataSelectedManager.dataDeSelected();
}
@Override
public void selected() {
dataSelectedManager.dataSelected();
}
public static void triggerDataTransfer(){
ArrayList<App> selectedApps = new ArrayList<>();
for (App app : apps){
if (app.isSelected()){
selectedApps.add(app);
}
}
dataSelectedManager.sendSelectedApps(selectedApps);
}
}
ContactListFragment.java
public class ContactListFragment extends Fragment implements ContactsStateManager {
private static final String TAG = "ContactListFragment";
static ArrayList<Contact> contacts = new ArrayList<>();
TextView selectAllTextView;
CheckBox selectAllRadioButton;
Button grantPermissionButton;
RelativeLayout grantPermissionLayout;
RecyclerView contactsRecyclerView;
ContactsManager contactsManager;
static DataSelectedManager dataSelectedManager;
public ContactListFragment(DataSelectedManager dataSelectedManager) {
this.dataSelectedManager = dataSelectedManager;
}
private final int PERMISSION_CODE = 101;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_contact_list,container,false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
contactsRecyclerView = view.findViewById(R.id.contacts_recycler_view);
selectAllTextView = view.findViewById(R.id.select_all_text_view);
selectAllRadioButton = view.findViewById(R.id.select_all_checkbox);
grantPermissionLayout = view.findViewById(R.id.grant_permission_container);
grantPermissionButton = view.findViewById(R.id.grant_permission_button);
contactsManager = new ContactsManager(getActivity().getContentResolver());
selectAllRadioButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!selectAllRadioButton.isChecked()){
for (Contact contact: contacts){
if (contact.isSelected()){
contact.setSelected(false);
dataSelectedManager.dataDeSelected();
}
}
}
else{
for (Contact contact: contacts){
if (!contact.isSelected()){
contact.setSelected(true);
dataSelectedManager.dataSelected();
}
}
}
contactsRecyclerView.getAdapter().notifyDataSetChanged();
}
});
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED){
grantPermissionLayout.setVisibility(View.VISIBLE);
contactsRecyclerView.setVisibility(View.GONE);
}
else{
readContacts();
setupRecyclerView();
}
grantPermissionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS},PERMISSION_CODE);
}
});
}
private void readContacts(){
contacts = contactsManager.getContacts();
selectAllTextView.setText("Select All (" + contacts.size() + ")");
}
private void setupRecyclerView(){
ContactListAdapter contactListAdapter = new ContactListAdapter(contacts,getContext(),this);
contactsRecyclerView.setAdapter(contactListAdapter);
contactsRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
Log.d(TAG, "onRequestPermissionsResult: Called");
if (requestCode == PERMISSION_CODE){
Log.d(TAG, "onRequestPermissionsResult: Codes matched");
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Log.d(TAG, "onRequestPermissionsResult: Permission Granted");
grantPermissionLayout.setVisibility(View.GONE);
readContacts();
contactsRecyclerView.setVisibility(View.VISIBLE);
setupRecyclerView();
}
}
}
@Override
public void deSelected() {
selectAllRadioButton.setChecked(false);
dataSelectedManager.dataDeSelected();
}
@Override
public void selected() {
dataSelectedManager.dataSelected();
}
public static void triggerDataTransfer(){
ArrayList<Contact> selectedContacts = new ArrayList<>();
for(Contact contact : contacts){
if (contact.isSelected()){
selectedContacts.add(contact);
}
}
dataSelectedManager.sendSelectedContacts(selectedContacts);
}
}
AppsManager.java
public class AppsManager {
PackageManager packageManager;
private String PACKAGE_NAME;
public AppsManager(PackageManager packageManager,String PACKAGE_NAME) {
this.packageManager = packageManager;
this.PACKAGE_NAME = PACKAGE_NAME;
}
public ArrayList<App> getInstalledApps(){
PackageManager packageManager = this.packageManager;
ArrayList<App> apps = new ArrayList<>();
List<PackageInfo> packs = packageManager.getInstalledPackages(0);
for (int i = 0; i < packs.size(); i++){
PackageInfo packageInfo = packs.get(i);
if ((!isSystemApp(packageInfo)) && !packageInfo.packageName.equals(PACKAGE_NAME)){
String appName = packageInfo.applicationInfo.loadLabel(packageManager).toString();
Drawable icon = packageInfo.applicationInfo.loadIcon(packageManager);
String packages = packageInfo.applicationInfo.packageName;
apps.add(new App(appName,icon,packages,false));
}
}
return apps;
}
private boolean isSystemApp(PackageInfo packageInfo){
return (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
}
}
ContactsManager.java
public class ContactsManager{
ContentResolver contentResolver;
public ContactsManager(ContentResolver contentResolver) {
this.contentResolver = contentResolver;
}
public ArrayList<Contact> getContacts(){
ContentResolver cr = contentResolver;
ArrayList<Contact> contacts = new ArrayList<>();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI,null,null,null,ContactsContract.Contacts.DISPLAY_NAME + " ASC");
if (cursor.getCount() > 0){
while (cursor.moveToNext()){
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String phone = "";
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0){
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
phone = pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
pCur.close();
}
Contact contact = new Contact(name,id,phone,false);
contacts.add(contact);
}
}
return contacts;
}
}
FileManager.java
public class FileManager {
private static final String TAG = "FileManager";
Context context;
public FileManager(Context context) {
this.context = context;
}
public ArrayList<FileObject> readFiles(String path, ArrayList<FileObject> selectedFiles){
ArrayList<FileObject> filesList = new ArrayList<>();
File file = new File(path);
File[] files = file.listFiles();
for (File file1 : files){
String name = file1.getName();
String filePath = file1.getAbsolutePath();
boolean isDirectory = file1.isDirectory();
String fileSize = "";
if (isDirectory){
int count = file1.listFiles().length;
if (count > 0){
fileSize = count + "";
}
}
else{
long fileSizeInBytes = file1.length();
long fileSizeInKB = fileSizeInBytes / 1024;
long fileSizeInMB = fileSizeInKB / 1024;
if (fileSizeInMB >= 1){
fileSize = fileSizeInMB + " MB";
}
else{
fileSize = fileSizeInKB + " KB";
}
}
boolean selected = isSelected(filePath,selectedFiles);
String extension = "";
if (isDirectory){
extension = "none";
}
else{
Log.d(TAG, "readFiles: " + filePath);
String[] splitArray = filePath.split("\\.");
Log.d(TAG, "readFiles: " + splitArray.length);
extension = splitArray[splitArray.length - 1];
}
Drawable icon;
if (isDirectory){
icon = context.getResources().getDrawable(R.drawable.ic_folder_skin_24dp);
}
else{
switch (extension){
case "pdf":
icon = context.getResources().getDrawable(R.drawable.ic_picture_as_pdf_red_24dp);
break;
default:
icon = context.getResources().getDrawable(R.drawable.ic_insert_drive_file_skin_24dp);
break;
}
}
FileObject fileObject = new FileObject(name,filePath,icon,isDirectory,extension,fileSize,selected);
filesList.add(fileObject);
}
return filesList;
}
boolean isSelected(String path, ArrayList<FileObject> selectedFiles){
boolean isSelected = false;
for (FileObject fileObject : selectedFiles){
if (fileObject.getPath().equals(path)){
isSelected = true;
}
}
return isSelected;
}
}
答案1
得分: 0
在执行繁重操作时,考虑使用线程。
英文:
When you are performing heavy operations consider using Threads.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论