2016-09-19 60 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" /> 

如果你已經使用,確保如果路徑正確與否。