2016-09-19 81 views
1

我试过下面的代码。找不到文件夹中的文件夹

public class MainActivity extends GlobalActivity implements CompetitionListAdapter.OnOperationSelectedListener { 

    private String path = ""; 
    private RecyclerView recyclerView; 
    private boolean isOnBackPressed = false; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     initLogger("MainActivity"); 
     recyclerView = (RecyclerView) findViewById(R.id.listRecyclerView); 
     recyclerView.setLayoutManager(new LinearLayoutManager(this)); 
     recyclerView.setHasFixedSize(true);   
     String path = Environment.getExternalStorageDirectory().getAbsolutePath(); 
     //path = "/storage/emulated/0/Download/pictures"; //When I pass this, then I can get the list of files in this folder. 
     loadFolders(path); 
    } 

    private void loadFolders(String path) { 
     if (this.path.isEmpty()) { 
      this.path = path; 
     } else if (!isOnBackPressed) { 
      this.path += "/" + path; //But when I make same the path dynamically from here file2 is always null. 
     } 
     writeLog(this.path); 
     File f = new File(path); 
     File file2[] = f.listFiles(); 
     ArrayList<String> folders = new ArrayList<>(); 
     if (file2 != null) { 
      for (File file1 : file2) { 
       folders.add(file1.getName()); 
      } 
     } else { 
      writeLog("fList is empty"); 
     } 
     recyclerView.setAdapter(new CompetitionListAdapter(folders, this)); 
    } 

    @Override 
    public void onOperationSelected(CompetitionListAdapter.Operation operation, String name) { 
     isOnBackPressed = false; 
     loadFolders(name); 
    } 

    @Override 
    public void onBackPressed() { 
     String paths[] = this.path.split("/"); 
     if (path.length() > 1) { 
      path = ""; 
      for (int i = 1; i < paths.length - 1; i++) { 
       path += "/" + paths[i]; 
      } 
      isOnBackPressed = true; 
      loadFolders(path); 
      return; 
     } 
     super.onBackPressed(); 
    } 
} 

所以上面的代码工作在启动应用程序......如果我从列表中选择任意文件夹,然后让我在loadFolders动态路径,但这返回null始终。

任何帮助将不胜感激。

+0

你在哪里在你的ada中调用'CompetitionListAdapter.OnOperationSelectedListener' PTER? –

回答

1

你在你的适配器就是为什么你在

@Override 
    public void onOperationSelected(CompetitionListAdapter.Operation operation, String name) { 
     isOnBackPressed = false; 
     loadFolders(name); 
    } 

得到文件夹名称例如FOLDER_PATH的过路文件夹名称列表替换

folders.add(file1.getName()); 

folders.add(file1.getAbsolutePath());

0

每次需要更新数据时,请不要创建新的CompetitionListAdapter。 我不知道你的适配器是如何工作的,但你应该做一个方法来更新里面的列表/添加项目,然后你调用notifyDataSetChanged来更新视图。

+0

不,这不是问题...我得到'fList是空'作为logcat输出。 – Gunaseelan

0

请确保您有使用以下权限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 

如果你已经使用,确保如果路径正确与否。