j. doe j. doe - 7 months ago 16
Java Question

Java string equals does not work

protected void onPostExecute(String result){
dialog.dismiss();
Log.d(TAG, "login activity onpostexe, result="+result);

if(result.compareTo("success")==0){
Log.d(TAG, "login activity onpostexe result success");
Toast.makeText(context,"Login successful", Toast.LENGTH_LONG).show();
Intent intent = new Intent(context, MainActivity.class);
// intent.putExtra("USERNAME", enteredUsername);
// intent.putExtra("MESSAGE", "You have been successfully Registered");
context.startActivity(intent);
}
else{
Log.d(TAG, "login activity onpostexe result unsuccess");
Toast.makeText(context,"Login unsuccessful, try again", Toast.LENGTH_LONG).show();
}
}//postexecute end


But logs are

04-17 17:15:26.311 11606-11606/com.example.caneraydin.androidwithlogin D/Chic: login activity onpostexe, result=success
04-17 17:15:26.311 11606-11606/com.example.caneraydin.androidwithlogin D/Chic: login activity onpostexe result unsuccess


summary is this

result = "success";
if(result.equals("success")//or compareto("success") ==0
return true;


As you can see in the logs, it goes into else part despite logs say result = success.

Why cant it give equality?

I read that strings comparison but it doesnot work.

Answer

Maybe there is a space in the result. Try this:

if (result != null && result.trim().equals("success")) {
    // your coding
}