kabuto178
kabuto178

Reputation: 3167

Comparing strings in android

I want to compare a string literal that is "failed" to a string that has been passed to this function, but my problem is that the string that is passed "result" is not the same as the string fail, and i explicitly passed "failed" to the function.

       if(result.equals(fail))

always returns false for me

protected void onPostExecute(String result) {
 super.onPostExecute(result);   
 TextView data_details = (TextView)findViewById(R.id.results_tab);
 data_details.setText(result); // THIS PRINTS OUT THE VALUE TO SCREEN WHICH IS 'failed'
 String fail = "failed";

 if(result.equals(fail))
 {

    Intent redirect = new Intent(LogActivity.this, MainActivity.class);
    redirect.putExtra("error", result);
    startActivity(redirect);
    finish();
  }     
 }

And also I tried:

if(result.equalsIgnoreCase("failed"))

Upvotes: 0

Views: 740

Answers (2)

Lucifer
Lucifer

Reputation: 29632

Your String variables might contain white spaces, i suggest you to check if condition as follows,

if(result.trim().equalsIgnoreCase(fail.trim()))
{
    // your code
}

Upvotes: 3

Amit Deshpande
Amit Deshpande

Reputation: 19185

Try fail.equals(result.trim()) There may be possibility that result contains a space because of which is it causing issues.

Reason here fail is used for comparison is in your case it can be never null. If result is null you will get NullPointerException

Upvotes: 0

Related Questions