Android loading files into array NullPointerException - java

Hi I am trying load a set of "list" into a String array, and the list are simply .txt documents and I want to use the names of the files as the list name on my display, therefore I need to get all of the files in the folder that I had created named "Lists" and then display them into an arrayadapter.
private String[] getListNames() {
//generates the file containing the list names
File file = new File(this.getFilesDir() +File.separator +"Lists");
System.out.println(file.getAbsolutePath());
File lists[] = file.listFiles();
String names[] = {};
if(lists.length >0){
for(int i = 0; i < lists.length; i ++){
names[i] = lists[i].getName();
}
}else{
names[0] = "Create New List";
}
line of code in question according to the stacktrace (line 108)
if(lists.length >0){
StackTrace
03-25 04:37:16.981: E/AndroidRuntime(2099): Caused by: java.lang.NullPointerException
03-25 04:37:16.981: E/AndroidRuntime(2099): at dev.shaw.MyShoppingPlanner.List_Activity.getListNames(List_Activity.java:108)

private List<String> myList = new ArrayList<String>();
String root_sd = Environment.getExternalStorageDirectory().toString();
file = new File( root_sd + "/Lists" ) ;
File list[] = file.listFiles();
for( int i=0; i< list.length; i++)
{
myList.add( list[i].getName() );
}

You need to log if files.getFileList() is really returning anything or not:
also
change this:
File lists[] = file.listFiles();
String names[] = {};
if(lists.length >0){
for(int i = 0; i < lists.length; i ++){
names[i] = lists[i].getName();
}
}else{
names[0] = "Create New List";
}
to
File lists[] = file.listFiles();
String names[] = {};
if(lists != null && lists.length >0){
for(int i = 0; i < lists.length; i ++){
names[i] = lists[i].getName();
}
}else{
names[0] = "Create New List";
}
P.S: You cannot get the length if the lists array is null in the first place.!

try this one.
//use two boolean variables.
File file;
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
//check if the sdcard is enable or disable in your device
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
private String[] getListNames() {
if (mExternalStorageAvailable) {
File path = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
if (!path.exists()) {
path.mkdirs();
}
file=path.getAbsolutePath();
}
else {
//use ContextWrapper it a onw way to access internal storage.
ContextWrapper cw = new ContextWrapper(getApplicationContext());
(or)
//generates the file containing the list names
file = new File(this.getFilesDir() +File.separator +"Lists");
if (!file.exists()) {
file.mkdirs();
}
System.out.println(file.getAbsolutePath());
}
File lists[] = file.listFiles();
String names[] = {};
try{
if (lists.length==0)
{
System.out.print("There is no files in the Directory");
}
else{
if(lists.length >0){
for(int i = 0; i < lists.length; i ++){
names[i] = lists[i].getName();
}
}else{
names[0] = "Create New List";
}
catch(Exception e)
{
e.printStackTrace();
}
}

Related

Importing a .csv file data into java table showing incomplete information

I'm trying to import a .csv file to display in my Java Table. But it shows incomplete data after reaching a certain point.
When I change the data to previous ones it displays just fine
My csv file looks fine too..
Finally this is how I read the file into the table from a menu item in my interface
File file = new File("C:\\Users\\User\\Desktop\\Emerging Coursework\\12_book_list_csv.csv");
try{
Scanner inputStream = new Scanner(file);
inputStream.nextLine();
while (inputStream.hasNextLine()) {
String data = inputStream.nextLine();
String[] values = data.split(",");
for(int i = 0; i < values.length; i++){
System.out.println(values[i]);
}
int rowCount = browseTable.getRowCount();
System.out.println("rowCount: " + rowCount);
int columnCount = browseTable.getColumnCount();
System.out.println("columnCount: " + columnCount);
int nextRow = 0;
boolean emptyRowFlag = false;
String testValue;
do {
testValue = (String) browseTable.getValueAt(nextRow, 0);
if (testValue != null && testValue.length()!=0) {
System.out.println("testvalue:" + testValue);
System.out.println("testValue.length" + testValue.length());
nextRow++;
} else{
emptyRowFlag = true;
}
} while(nextRow < rowCount && !emptyRowFlag);
for (int i = 0; i < columnCount; i++){
browseTable.setValueAt(values[i], nextRow, i);
}
}
} catch(Exception e){
}

Android Directory creation failing on internal storage

I want to create a new folder/directory called lists but it just keeps on failing, if anyone had any suggestions that would be greatly appreciated. Thank you.
File file = new File(this.getFilesDir() +File.separator +"Lists");
if(file.mkdirs()){
System.out.println("Directory success");
}else{
System.out.println("Directory failed!");
}
System.out.println(file.getAbsolutePath());
if(file.isDirectory()){
System.out.println("File is a directory");
File lists[] = file.listFiles();
String names[] = new String[lists.length];
if(lists.length >0){
for(int i = 0; i < lists.length; i ++){
names[i] = lists[i].getName();
}
}else{
names[0] = "Create New List";
}
}else{
System.out.println("File is not a directory");
}
My first answer is completely incorrect (my apologies for that)! I believe this one is correct.
I think problem lies with the following lines:
File lists[] = file.listFiles();
String names[] = new String[lists.length];
if(lists.length > 0){
for(int i = 0; i < lists.length; i ++){
names[i] = lists[i].getName();
}
}else{
names[0] = "Create New List";
}
You had just created the folder so there will be no files in it so lists[] won't have any size, but in your else statement you are adding an item to the names array even though it doesn't have a size. Removing names[0] = "Create New List"; from the else statement should work.

How can one get a file's path from an ftp server?

This code gets the file name, but I want to get the file path:
private List <String> checkFiles(FTPClient clients){
List <String> it = new ArrayList <String>();
try {
FTPFile[] ftpFiles = clients.listFiles();
int length = ftpFiles.length;
for (int i = 0; i < length; i++) {
String name = ftpFiles[i].getName();
Calendar date = ftpFiles[i].getTimestamp();
Log.v("aasd", name );
it.add (name);
}
} catch(Exception e) {
e.printStackTrace();
}
return it ;
}
The path is in the client, not the files.
String path = clients.printWorkingDirectory()
if you want specific path
client.changeWorkingDirectory(PathName) eg client.changeWorkingDirectory(folder1/folder2) where folder 2 is inside folder 1
System.out.println(client.printWorkingDirectory)
printWorkingDirectory gives the current path
Below code finds that all files path in any folder on ftp server.
ftpPath is likes that "ftpserver/folder". List contains paths of all files in folder.
public List<string> GetFilesPath(string ftpPath)
{
FtpWebRequest request;
string FtpServerPath = ftpPath;
List<string> filePathList=new List<string>();
try
{
request = WebRequest.Create(new Uri(FtpServerPath)) as FtpWebRequest;
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
request.UseBinary = true;
request.UsePassive = true;
request.KeepAlive = true;
request.Credentials = new NetworkCredential("ftpuser", "ftpPassword");
request.ConnectionGroupName = "group";
Stream rs = (Stream)request.GetResponse().GetResponseStream();
StreamReader sr = new StreamReader(rs);
string strList = sr.ReadToEnd();
string[] lines = null;
if (strList.Contains("\r\n"))
{
lines = strList.Split(new string[] { "\r\n" }, StringSplitOptions.None);
}
else if (strList.Contains("\n"))
{
lines = strList.Split(new string[] { "\n" }, StringSplitOptions.None);
}
if (lines == null || lines.Length == 0)
return null;
else{
foreach (string line in lines)
{
if (line.Length == 0)
continue;
int x=line.LastIndexOf(' ');
int len = line.Length;
var str = line.Substring( (x+1), (len - x - 1));
var filePath = FtpServerPath+"/"+str;
filePathList.Add(filePath);
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}

Using opencsv - java.lang.OutOfMemoryError: Java heap space

I am using opencsv to parse two csv files. I only copy some values from the two files.
I have a seperate function which processes the CDax.csv. Which looks like that:
public HashMap<String,String> readCDax() throws Exception {
String csvDaxFile = "C:\\Users\\CDAX.csv";
CSVReader reader = new CSVReader(new FileReader(csvDaxFile), ';');
String [] line;
HashMap<String, String> cdaxMap = new HashMap<String, String>();
while ((line = reader.readNext()) != null) {
cdaxMap.put(line[0], line[7]);
}
System.out.println("Process CDax File!");
reader.close();
return cdaxMap;
}
My main method is run() which I execute in my main method:
public void run() throws Exception {
while ((firstLine = reader.readNext()) != null && (secondLine = reader.readNext()) != null && i<10) {
//fileName of the String
fileName = firstLine[0];
writerPath = "C:\\Users\\" + fileName + ".csv";
//write csv file
CSVWriter writer = new CSVWriter(new FileWriter(writerPath), ';');
//write Header
//String[] entries = "Name;Date;TotalReturn;Currency".split(";");
String [] entries = {"Name","Date", "TotalReturn", "Currency"};
writer.writeNext(entries);
//create Content
//companyName of the String
companyName = secondLine[1];
//currency
currency = secondLine[2];
//dates
dateList = new ArrayList<String>();
for(int p = 3; p < firstLine.length; p++) {
dateList.add(firstLine[p]);
}
//total returns
returnList = new ArrayList<String>();
for(int j = 3; j < secondLine.length; j++) {
returnList.add(secondLine[j]);
}
// cDaxList
cDaxList = new ArrayList<String>();
for(int j = 1; j <dateList.size(); j++) {
if(cDaxMethodValuesMap.containsKey(dateList.get(j))){
cDaxList.add(cDaxMethodValuesMap.get(dateList.get(j)));
} else{
dateList.add("na"); // I get the error here!
}
}
if(dateList.size()!=returnList.size()) {
System.out.println("Dates and Returns do not have the same length!");
}
int minSize = Math.min(dateList.size(), returnList.size());
//"Name;Date;TotalReturn;Currency"
List<String[]> data = new ArrayList<String[]>();
for(int m = 0; m < minSize; m++) {
data.add(new String[] {companyName, dateList.get(m), returnList.get(m), currency, cDaxList.get(m)});
}
writer.writeAll(data);
//close Writer
writer.close();
i++;
System.out.println(fileName + " parsed successfully!");
}
System.out.println("Done");
}
However when I run my program I get:
Process CDax File!
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:2760)
at java.util.Arrays.copyOf(Arrays.java:2734)
at java.util.ArrayList.ensureCapacity(ArrayList.java:167)
at java.util.ArrayList.add(ArrayList.java:351)
at com.TransformCSV.main.ParseCSV.run(ParseCSV.java:109)
at com.TransformCSV.main.ParseCSV.main(ParseCSV.java:21)
I am getting the error in this method:
cDaxList = new ArrayList<String>();
for(int j = 1; j <dateList.size(); j++) {
if(cDaxMethodValuesMap.containsKey(dateList.get(j))){
cDaxList.add(cDaxMethodValuesMap.get(dateList.get(j)));
} else{
dateList.add("na"); //I get the error here!!!
}
}
I tried to put up the heapsize via the vm settings, however I do not think that this should be done because I only read in both csv files only 3000 values.
I appreciate your reply!
Your loop:
for(int j = 1; j <dateList.size(); j++) {
is looping through dateList but in that loop you are adding to dateList:
dateList.add("na"); //I get the error here!!!
so dateList will get bigger and bigger until you run out of memory. dateList.size() is evaluated every time through the loop, not once at the beginning.

Readin from /data/dalvik-cache JavaNullPointer

I'm trying to list all files in /data/dalvik-cache folder but i keep getting NullPointerException
List<String> dalvikFiles = new ArrayList<String>();
for (String dir : dalvikPath) {
File folder = new File(dir);
File list[] = folder.listFiles();
for( int i=0; i< list.length; i++)
{
dalvikFiles.add( list[i].getName() );
}
}
The array dalvikPath contains /data/dalvik-cache
I request su before trying to list and I think i have all the permissions in my manifest.
I think you need to check directory is exist or not . then you can get list of files
File folder = new File(dir);
if(folder.exists()){
File list[] = folder.listFiles();
if(list.length>0{
for( int i=0; i< list.length; i++){
}
}
}else{
}
Ok so i've modified my code and now i don't have javanullpointer but i don't "find" an files in the folders...
List<String> dalvikFiles = new ArrayList<String>();
for (String dir : dalvikPath) {
log.append("Reading " + dir + "\n");
File folder = new File(dir);
if (folder.exists() && folder.isDirectory()){
try{
File list[] = folder.listFiles();
for( int i=0; i< list.length; i++)
{
dalvikFiles.add( list[i].getName().toString() );
log.append(list[i].getName().toString() +"\n");
}
}
catch ( Exception e) {
}
}
else {
log.append("Folder " + dir + "doesn't exist.\n");
}

Categories