I’m making an app that creates new files, there’s no problem when I name the files like this:
private String FILENAME = "myFilename";
but when I use a method to name the file, the compiler jumps straight to this line:
String lineSep = System.getProperty("line.separator");
then to my class declaration:
public class AddUser extends Activity
And the application crashes.
This is what the log file says:
12-03 16:26:12.814: E/AndroidRuntime(20307): FATAL EXCEPTION: main
12-03 16:26:12.814: E/AndroidRuntime(20307): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myapp.app/com.myapp.app.ProfileSaved}: java.lang.NullPointerException
12-03 16:26:12.814: E/AndroidRuntime(20307): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
12-03 16:26:12.814: E/AndroidRuntime(20307): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
12-03 16:26:12.814: E/AndroidRuntime(20307): at android.app.ActivityThread.access$600(ActivityThread.java:130)
This is my file naming method:
int firstArray;
int nextArray;
private String fileNamer(){
File dataDirectory = Environment.getDataDirectory();
File fileDir = new File(dataDirectory, "data/com.myapp.app/files");
String[] filenameArray = fileDir.list();
Arrays.sort(filenameArray);
if (filenameArray.length == 0){
return "0";
}
if (filenameArray.length == 2500){
return "too_many_items";
}
if (!filenameArray[0].equals("0")){
return "0";
}
int arrayLength = filenameArray.length;
int i;
for(i=0; i<arrayLength-1;){
firstArray = Integer.parseInt(filenameArray[i]);
nextArray = Integer.parseInt(filenameArray[i+1]);
if (firstArray+1 == nextArray){
i++;
}
}
return Integer.toString(nextArray+1);
}
The method seems to be working fine but I just can’t see why would it affect the rest of the program since all it does is to return a String?
Ok guys thanks for your input.
I believe I finally got it right. First of all the method indeed was buggy but that wasn’t really the issue, a good answer would’ve been something like:
“There IS a difference between a
Stringand invoking a method that returns aStringthat is assigned to a variable, because in order to use the invokedStringin another Class you’ll probably need to set the variable asstatic. That’s why theStringis working and the ‘method invoked’Stringnot.”About the bugs in the code just in case someone is ever interested, the
ifinneeds the
elsein case there is an empty space between filenames, like1, 3, 4so the next file gets named2.The other bug was that I was comparing filenames as
Stringsso when I sorted them, they were sorted as1, 10, 2, 3, 4, 5, 6, 7, 8, 9.The solution I used was to add zeros to the beginning of the filenames like
0001, 0002,and so on.