0

I am looking for weeks now why I get a Nullpointer and didn't find yet why. Below are the code parts where I read the files and then list them in a ListView.

SplashActivity:

public static void setFolderPath() {
    String dest;
    try {
        dest = pref.getString(FOLDER_DEST_SETTING_KEY, FOLDER_INTERNAL_DEST);
    } catch (Exception e) {
        dest = FOLDER_INTERNAL_DEST;
    }
    if (dest.equals(FOLDER_EXTERNAL_DEST) && hasExternal) {
        folderPath = externalPath;
    } else {
        folderPath = internalPath;
        SharedPreferences.Editor editor = pref.edit();
        editor.putString(FOLDER_DEST_SETTING_KEY, FOLDER_INTERNAL_DEST);
        editor.apply();
    }
}

public static String getFolderPath() {
    setFolderPath();
    return folderPath == null ? internalPath : folderPath;
}

MainActivity:

/**
 * Initialisierung
 */
private void init() {
    initFiles();

    if (listView != null) {
        listView.setAdapter(new CustomSingleSelectAdapter(context, files));
        listView.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                itemClicked(position);
            }
        });
    } else {
        Toast.makeText(context, R.string.init_fehler, Toast.LENGTH_SHORT).show();
        finish();
    }
    ESortBy sort = ESortBy.getSorting(pref.getInt(Constants.SORT_BY_KEY, ESortBy.NOT_SORTED.ordinal()));
    NotizFile.setSort(sort);
    Collections.sort(files);
}

private void initFiles() {
    files = Util.getAllNotices(context);
}

Util:

public static List<NotizFile> getAllNotices(Context context) {
    String folderPath = SplashActivity.getFolderPath();

    File folder = new File(folderPath);
    if (!folder.exists()) {
        if (!folder.mkdirs()) {
            Toast.makeText(context, R.string.ordner_erstellen_fehler, Toast.LENGTH_SHORT).show();
            return new ArrayList<>();
        }
    }

    List<NotizFile> list = new ArrayList<>();
    for (File file : folder.listFiles()) {
        list.add(new NotizFile(file.getAbsolutePath(), false));
    }

    return list;
}

I have this class where I implement the Comparable Interface:

public class NotizFile implements Serializable, Comparable<NotizFile> {
    @Override
    public int compareTo(@NonNull NotizFile otherFile) {
        switch (sortBy) {
          case NAME_ASC:
            return compareName(sortBy, this, otherFile);
          case NAME_DESC:
            return compareName(sortBy, this, otherFile);
          case DATE_ASC:
            return compareDate(sortBy, this, otherFile);
          case DATE_DESC:
            return compareDate(sortBy, this, otherFile);
          case WICHTIG_ASC:
            return compareImportance(sortBy, this, otherFile);
          case WICHTIG_DESC:
            return compareImportance(sortBy, this, otherFile);
          default:
            return 0;
        }
    }
}

The Nullpointerstack is this:

Caused by: java.lang.NullPointerException: 
  at java.util.Collections.sort(Collections.java:1869)
  at daniel.com.notizapp.core.MainActivity.initFiles(MainActivity.java:117)
  at daniel.com.notizapp.core.MainActivity.init(MainActivity.java:75)
  at daniel.com.notizapp.core.MainActivity.onCreate(MainActivity.java:63)
  at android.app.Activity.performCreate(Activity.java:6904)
  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3266)

Is it becaus the List (files) is null? But I am initialising it with the method "getAllNotices()". Then why is it sometimes null?

Extra Information: On my phone it works perfectly, but on the phone of my friend it sometimes throws an Exception (Galaxy A3)

user7174483
  • 73
  • 1
  • 9
  • 1
    Your code in your question does not match your stack trace. Your stack trace shows you calling `Collections.sort()` from `initFiles()`. Your code does not have that call. – CommonsWare May 19 '17 at 14:50
  • Sry, I forgot to redo it. I edit my Code – user7174483 May 19 '17 at 15:46
  • Still missing code. That's not the code for `initFiles`. – m0skit0 May 19 '17 at 15:53
  • That still does not match your stack trace. Your stack trace shows you calling `Collections.sort()` from `initFiles()`. Your `initFiles()` method does not have a call to `sort()`. – CommonsWare May 19 '17 at 15:54
  • I'm calling Collection.sort() at the end of initFiles() and implement the Comparable Interface in NotizFile https://github.com/dfrits/Notizapp/tree/master/app/src/main/java/daniel/com/notizapp – user7174483 May 19 '17 at 16:13
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – EJoshuaS - Stand with Ukraine May 20 '17 at 14:43
  • Don't think so, because I know what it is, but I don't know why.... – user7174483 Jun 05 '17 at 13:44

1 Answers1

0

I am not sure if this answers you question. But I noticed that you don't return if the folder exists and folder cannot make directories, i.e. folder.exists() && !folder.mkdirs() condition is not handled. The reason might be that your application doesn't have enough permissions to read that directory.

Your current logic is - if folder doesn't exist then check folder cannot make directories. That means you are assuming that if folder does exist then I can make directories which may not work in some cases.

The method File.ListFiles() can return a null if the abstract pathname does not denote a directory, or if an I/O error occur and can throw a SecurityException if a security manager exists and its SecurityManager.checkRead(String) method denies read access to the directory.
More on File.ListFiles

Let me know if this helps.

ngoa
  • 720
  • 4
  • 14
  • But then why does it work on some phones and some not? – user7174483 May 19 '17 at 17:13
  • Based on the OS version and the flavour (Samsung, LG, etc have their own version of android os), the behaviour might be different. You need to put some more debug prints and try-catch blocks to actually catch the issue. – ngoa May 26 '17 at 15:06