如何在Android中处理加载大量数据

huangapple go评论104阅读模式
英文:

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 = &quot;FileListFragment&quot;;
    RecyclerView fileListRecyclerView,currentPathRecyclerView;
    TextView currentPathTextView;

    ArrayList&lt;FileObject&gt; fileObjects = new ArrayList&lt;&gt;();
    ArrayList&lt;FileObject&gt; currentFolders = new ArrayList&lt;&gt;();
    static ArrayList&lt;FileObject&gt; selectedFiles = new ArrayList&lt;&gt;();

    String currentPath = &quot;&quot;;
    String initialPath = &quot;&quot;;
    String pathToShow = &quot;/&quot;;

    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 &lt; 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(&quot;Android&quot;)[0];
            initialPath = currentPath;

            FileObject fileObject = new FileObject(&quot;/&quot;,initialPath,null,true,&quot;none&quot;,&quot;0&quot;,false);

            currentFolders.add(fileObject);
            setupCurrentPathRecyclerView();

            readFiles();

            Log.d(TAG, &quot;init: &quot; + 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, &quot;onRequestPermissionsResult: Called&quot;);
        if (requestCode == PERMISSION_CODE){
            Log.d(TAG, &quot;onRequestPermissionsResult: Codes matched&quot;);
            if (grantResults.length &gt; 0 &amp;&amp; grantResults[0] == PackageManager.PERMISSION_GRANTED){
                Log.d(TAG, &quot;onRequestPermissionsResult: Permission Granted&quot;);
                grantPermissionContainer.setVisibility(View.GONE);
                fileListRecyclerView.setVisibility(View.VISIBLE);
                FileObject fileObject = new FileObject(&quot;/&quot;,initialPath,null,true,&quot;none&quot;,&quot;0&quot;,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, &quot;pathFolderClicked: Called&quot;);
        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&lt;&gt;(currentFolders.subList(0,index));
                    Log.d(TAG, &quot;pathFolderClicked: Number of item &quot; + (size - index) + &quot; Index: &quot; + index);
//                    currentPathRecyclerView.getAdapter().notifyItemRangeRemoved(index,size - index);
                    setupCurrentPathRecyclerView();
                    currentPath = currentFolders.get(currentFolders.size() - 1).getPath();
                    readFiles();
                    Log.d(TAG, &quot;pathFolderClicked: Notified&quot;);
                }
            }
            Log.d(TAG, &quot;pathFolderClicked: &quot; + Arrays.toString(currentFolders.toArray()));
        }

    }

    @Override
    public void fileSelected(FileObject fileObject) {
        selectedFiles.add(fileObject);
        dataSelectedManager.dataSelected();
    }

    @Override
    public void fileDeselected(FileObject fileObject) {
        ArrayList&lt;FileObject&gt; filesToRemove = new ArrayList&lt;&gt;();
        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&lt;App&gt; apps = new ArrayList&lt;&gt;();
    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(&quot;Select All (&quot; + apps.size() + &quot;)&quot;);
    }




    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&lt;App&gt; selectedApps = new ArrayList&lt;&gt;();
        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 = &quot;ContactListFragment&quot;;
    static ArrayList&lt;Contact&gt; contacts = new ArrayList&lt;&gt;();

    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(&quot;Select All (&quot; + contacts.size() + &quot;)&quot;);

    }

    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, &quot;onRequestPermissionsResult: Called&quot;);
        if (requestCode == PERMISSION_CODE){
            Log.d(TAG, &quot;onRequestPermissionsResult: Codes matched&quot;);
            if (grantResults.length &gt; 0 &amp;&amp; grantResults[0] == PackageManager.PERMISSION_GRANTED){
                Log.d(TAG, &quot;onRequestPermissionsResult: Permission Granted&quot;);
                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&lt;Contact&gt; selectedContacts = new ArrayList&lt;&gt;();

        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&lt;App&gt; getInstalledApps(){
        PackageManager packageManager = this.packageManager;

        ArrayList&lt;App&gt; apps = new ArrayList&lt;&gt;();
        List&lt;PackageInfo&gt; packs = packageManager.getInstalledPackages(0);

        for (int i = 0; i &lt; packs.size(); i++){
            PackageInfo packageInfo = packs.get(i);

            if ((!isSystemApp(packageInfo)) &amp;&amp; !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 &amp; ApplicationInfo.FLAG_SYSTEM) != 0;
    }
}

ContactsManager.java

public class ContactsManager{



    ContentResolver contentResolver;

    public ContactsManager(ContentResolver contentResolver) {
        this.contentResolver = contentResolver;
    }

    public ArrayList&lt;Contact&gt; getContacts(){
        ContentResolver cr = contentResolver;

        ArrayList&lt;Contact&gt; contacts = new ArrayList&lt;&gt;();

        Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI,null,null,null,ContactsContract.Contacts.DISPLAY_NAME + &quot; ASC&quot;);

        if (cursor.getCount() &gt; 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 = &quot;&quot;;
                if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) &gt; 0){
                    Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID +&quot; = ?&quot;,
                            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 = &quot;FileManager&quot;;

    Context context;

    public FileManager(Context context) {
        this.context = context;
    }

    public ArrayList&lt;FileObject&gt; readFiles(String path, ArrayList&lt;FileObject&gt; selectedFiles){
        ArrayList&lt;FileObject&gt; filesList = new ArrayList&lt;&gt;();

        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 = &quot;&quot;;

            if (isDirectory){
                int count = file1.listFiles().length;
                if (count &gt; 0){
                    fileSize = count + &quot;&quot;;
                }

            }
            else{
                long fileSizeInBytes = file1.length();
                long fileSizeInKB = fileSizeInBytes / 1024;
                long fileSizeInMB = fileSizeInKB / 1024;
                if (fileSizeInMB &gt;= 1){
                    fileSize = fileSizeInMB + &quot; MB&quot;;

                }
                else{
                    fileSize = fileSizeInKB + &quot; KB&quot;;

                }
            }

            boolean selected = isSelected(filePath,selectedFiles);
            String extension = &quot;&quot;;
            if (isDirectory){
                extension = &quot;none&quot;;
            }
            else{
                Log.d(TAG, &quot;readFiles: &quot; + filePath);
                String[] splitArray = filePath.split(&quot;\\.&quot;);
                Log.d(TAG, &quot;readFiles: &quot; + 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 &quot;pdf&quot;:
                        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&lt;FileObject&gt; 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.

huangapple
  • 本文由 发表于 2020年8月2日 17:29:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/63214392.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定