简体   繁体   中英

How do I transfer a boolean value from the main activity to a class?

so i am trying to transfer a boolean value "isclicked" from a button in the main activity to a Java class that would use that value (true) in an if statement , the debugger shows no errors but the app crashes on launch , here is a snippet of my code:

Main.java

if (isclicked) {
        Intent myIntent = new Intent(this, AP.class);
        myIntent.putExtra("isclicked", "true");
        startActivity(myIntent);
    }else{
        Intent myIntent = new Intent(this, AP.class);
        myIntent.putExtra("isclicked", "false");
        startActivity(myIntent);
    }

and AP.java

Boolean value = getIntent().getBooleanExtra("isclicked", false);

any other methods are welcomed.

Simplify it a bit, like this and it will work:

Intent myIntent = new Intent(this, AP.class);
myIntent.putExtra("isclicked", isclicked);
startActivity(myIntent);
if (isclicked) {    
    Intent myIntent = new Intent(this, AP.class);
    myIntent .putExtras("isclicked", true);
    startActivity(myIntent);    
}

Retrieve intent extra:

@Override
protected void onCreate(Bundle savedInstanceState) {
    Boolean value = getIntent().getExtras().getBoolean("isclicked");
}

Your Code

    if (isclicked) {
    Intent myIntent = new Intent(this, AP.class);
    myIntent.putExtra("isclicked", "true");
    startActivity(myIntent);
}

// Change

    if (isclicked) {
    Intent myIntent = new Intent(this, AP.class);
    myIntent.putExtra("isclicked", true);
    startActivity(myIntent);
}

Do not pass the boolean value in quotes. If you pass that in quotes, it will be passed as string. Just pass true and not "true".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM