0

I am learning Android but i am not much experienced with java. I write these code to check if there is any data in sharedPreferences (Which i saved before using sharedPreferences.Editor) or not, and if there is any saved data then do something. But the code under if (savedData != null) Statement is always being executed, no matter if there is any value in savedData or not.

But when i use if (!savedData.isEmpty() it is doing what i meant it to do.

But i found on StackOverflow that we should not use isEmpty() with String because if String is null then isEmpty() will not execute.

I just wanted to know why if (savedData != null) is not working but if (!savedData.isEmpty()).

My code: Here Log.d("isRunning : ", "True") under if statement is always executing.

private String saveString = null;
    private ListView listView;
    private static List<String> listArray = new ArrayList<String>();
    private SaveListInSharedPreferences saveListInSharedPreferences = new SaveListInSharedPreferences();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    SharedPreferences settings = getPreferences(MODE_PRIVATE);
    String savedData = settings.getString(saveString, null);
    if (savedData != null){
        listArray = saveListInSharedPreferences.getList(savedData);
        Log.d("isRunning : ", "True" );
    }
Nishant Bhakta
  • 2,897
  • 3
  • 21
  • 24
  • 1
    Clearly it is not null in preferences, otherwise it wouldn't go there. Why do you assume it would be? – Sami Kuhmonen Feb 06 '17 at 06:01
  • I think you should start with Java basics before you face many such issues. Anyways the way to use both the above conditions is to chain them with a && (put the NULL check on LEFT) - `if (savedData != null && !savedData.isEmpty())` – Dibzmania Feb 06 '17 at 06:04
  • I am assigning `null` to `savedData`. in first line there is `saveString` to `null` then i am assigning this `saveString` to `savedData` in line 12 using `String savedData = settings.getString(saveString, null);`. what i am doing wrong there ? – Nishant Bhakta Feb 06 '17 at 06:10

1 Answers1

0
if (myString != null && !myString.isEmpty()) {
    //
}

If this doesn't work then it isn't null. If it's not working then try setting it directly equal to null beforehand, and then figuring out why that function isn't returning null . As to why myString != null doesn't work by itself, here's a post that can explain it better than I could. Avoiding != null statements

Community
  • 1
  • 1