Search code examples
javaandroidcharsequence

dynamically populating data in charsequence


I have a charsequence in which I want to populate data dynamically. when I am hard coding the values its working fine, otherwise not

This one is working

private void getDir(String dirPath){

     File f = new File(dirPath);
     File[] files = f.listFiles(); 
         final CharSequence[] items = {files[0].getPath(), files[1].getPath()};
}

This one is giving a runtime exception

private void getDir(String dirPath){

     File f = new File(dirPath);
     File[] files = f.listFiles(); 
         CharSequence[] items;
         items[0]=files[0].getPath();
     items[1]=files[1].getPath();
}

Please help.


Solution

  • You need to create the items array and specify its size.

    Try something like:

    private void getDir(String dirPath){
    
        File f = new File(dirPath);
        File[] files = f.listFiles();
        CharSequence[] items = new CharSequence[files.length];
        for (int i=0; i< files.length; i++)
            items[i]=files[i].getPath();
    }