Monday, October 12, 2015

java - How to convert string to boolean

MainActivity.java

package com.cfsuman.me.javaexamples;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {

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

        // Get widget reference from XML layout
        TextView tv = (TextView) findViewById(R.id.tv);

        // Initialize a new string with boolean data type value
        String stringOfBooleanValue = "true";
        tv.setText("String : " + stringOfBooleanValue);

        // Parse string to boolean
        boolean booleanFromString = Boolean.parseBoolean(stringOfBooleanValue);
        tv.setText(tv.getText()+ "\nBoolean.parseBoolean(): " + booleanFromString);

        // Another way to convert string to boolean
        boolean booleanOfString = Boolean.valueOf(stringOfBooleanValue);
        tv.setText(tv.getText()+ "\nBoolean.valueOf(): " + booleanOfString);

        // Initialize a new string with boolean value
        String stringOfBoolean = "false";
        tv.setText(tv.getText() + "\n\nString : " + stringOfBoolean);

        // Parse string to boolean
        boolean booleanVal = Boolean.parseBoolean(stringOfBoolean);
        tv.setText(tv.getText()+ "\nBoolean.parseBoolean(): " + booleanVal);

        // Initialize a new string with boolean value ignore case
        String stringAsBoolean = "TRue";
        tv.setText(tv.getText() + "\n\nString : " + stringAsBoolean);

        // Only return true when string contains true by ignoring case
        // Otherwise return false
        boolean booleanValue = stringAsBoolean.equalsIgnoreCase("true");
        tv.setText(tv.getText()+ "\nString.equalsIgnoreCase(): " + booleanValue);

        // Initialize a new string with boolean value ignore case
        String stringValue= "text";
        tv.setText(tv.getText() + "\n\nString : " + stringValue);

        // If string contains false or other text then it return false
        boolean value = stringValue.equalsIgnoreCase("true");
        tv.setText(tv.getText()+ "\nString.equalsIgnoreCase(): " + value);
    }
}
More android examples