Nishant Bhakta Nishant Bhakta - 4 years ago 74
Java Question

Why the code getting executed under `if( savedData != null )`, no matter if `savedData` is set to any value or null

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" );
}

Answer Source
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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download