How to call a method within another method?

Asked

Viewed 1,649 times

-1

I am developing a quiz. Using as Radiobutton response. So far I have created using the onClick method on each Radiobutton, but it is not effective.

So I’d like to call every question ask1();, ask2(); within the method rate(View view) and from there calculate the total score of the user’s responses showing a Toast.

But when calling for example the method ask6(); within the rate(View view); error. Even if I put the view parameter ask(view); why rate has is a view.

public class MainActivity extends AppCompatActivity {

    double rating = 0;
    String userAnswer;

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

    public void ask1( View view ) {
        //See if checked
        boolean checked = ((RadioButton) view).isChecked();

        //Do some if checked
        switch (view.getId()) {
            case R.id.answer1_ask1:
                if (checked) {
                    rating += 1;
                    break;
                }
            default:
                if (checked) {
                    rating -= 1;
                    break;
                }
        }
    }

    public void ask2( View view ) {
        //is checked?
        boolean checked = ((CheckBox) view).isChecked();

        //Do some
        switch (view.getId()) {
            case R.id.answer1_ask2:
                if (checked) rating -= 1;

            case R.id.answer2_ask2:
                if (checked) rating += 0.5;

            case R.id.answer3_ask2:
                if (checked) rating += 0.5;
        }
    }

    public void ask3(){
        EditText answer = findViewById(R.id.answer1_ask3);
        userAnswer = String.valueOf(answer.getText());

        if (userAnswer.equals("Láctea")) {
            rating += 1;

        } else if (userAnswer.equals("Via Láctea")) {
            rating += 1;

        } else {
            rating -= 1;

        }

    }

    public void ask4(View view){
        //See if checked
        boolean checked = ((RadioButton) view).isChecked();

        //Do!
        switch (view.getId()) {
            case R.id.answer1_ask4:
                if (checked) {
                    rating += 1;
                    break;
                }
            case R.id.answer2_ask4:
                if (checked) {
                    rating -= 1;
                    break;
                }
            case R.id.answer3_ask4:
                if (checked) {
                    rating -= 1;
                    break;
                }

        }
    }

    public void ask5(View view){
        //is checked?
        boolean checked = ((RadioButton)view).isChecked();

        //Do it now!!!!
        switch (view.getId()){
            case R.id.answer1_ask5:
                if(checked){
                    rating += 1;
                }
            case R.id.answer2_ask5:
                if (checked) {
                    rating -= 1;
                }
        }
    }

    public void ask6(View view){
        //is checked?
        boolean checked = ((RadioButton)view).isChecked();

        //Please do fast!
        switch (view.getId()){
            case R.id.answer1_ask6:
                if(checked){
                    rating += 1;
                }
            case R.id.answer2_ask6:
                if(checked){
                    rating -= 1;
                }
        }
    }

    public void rate( View view ) {
        // ask6(View view); Why can't I call?
        // ask6(view); Why bug?

        ask6();
        Toast.makeText(this, ("Oi "+ rating ), Toast.LENGTH_SHORT).show();
        rating = 0;
    }



    /*
    public void ask3( View view ) {
        //was wrote?
        //String answer = ((EditText)view).getText(findViewById(R.id.answer1_ask3)).toString();

        //was wrote?
        EditText answer = findViewById(R.id.answer1_ask3);
        String userAnswer = String.valueOf(answer.getText());

        String rightAnswer1 = "Via Láctea";
        String rightAnswer2 = "Láctea";

        //do some
        if(userAnswer == rightAnswer1) rating += 1;
        if (userAnswer == rightAnswer2) rating += 1;
        else rating -= 1;

        // if (userAnswer == "a"){


    }
    */
}

Part of XML:

<RadioGroup
    android:layout_marginLeft="72dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="16dp">
    <RadioButton
        android:id="@+id/answer1_ask6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/answer1_ask6"/>
    <RadioButton
        android:id="@+id/answer2_ask6"
        android:layout_marginVertical="4dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/answer2_ask6"/>
</RadioGroup>

<Button
    android:text="RESPONDER"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="rate"
    android:layout_marginLeft="72dp"
    android:layout_marginBottom="20dp"/>
</LinearLayout>

=================== Adding an edit =============

In the Android documentation, there is an example of how to use Radiobutton:

public void onRadioButtonClicked(View view) {
    // Is the button now checked?
    boolean checked = ((RadioButton) view).isChecked();

// Check which radio button was clicked
switch(view.getId()) {
    case R.id.radio_pirates:
        if (checked)
            // Pirates are the best
        break;
    case R.id.radio_ninjas:
        if (checked)
            // Ninjas rule
        break;
}

}

The good thing about this method is that I just have to play the id of each Radiobutton and use the switch to run everything at once. Then I edited my code to make case of each Radiobutton I have in the quiz. It was like this:

public void askRadioButton(View view){
    //is checked?
    boolean checked = ((RadioButton)view).isChecked();

    //Do it now!!!!
    switch (view.getId()){

        case R.id.answer1_ask1:
            if (checked) {
                rating += 1;
                break;
            }
        case R.id.answer1_ask2:
            if (checked) rating -= 1;
            break;

        case R.id.answer2_ask2:
            if (checked) rating += 0.5;
            break;

        case R.id.answer3_ask2:
            if (checked) rating += 0.5;
            break;

        case R.id.answer1_ask4:
            if (checked) {
                rating += 1;
                break;
            }
        case R.id.answer2_ask4:
            if (checked) {
                rating -= 1;
                break;
            }
        case R.id.answer3_ask4:
            if (checked) {
                rating -= 1;
                break;
            }
        case R.id.answer1_ask5:
            if(checked){
                rating += 1;
            }
        case R.id.answer2_ask5:
            if (checked) {
                rating -= 1;
            }
    }
}

public void rate( View view ) {
    askRadioButton();

    Toast.makeText(this, ("Oi "+ rating ), Toast.LENGTH_SHORT).show();
    rating = 0;
}

But I still can’t properly call the new method. If I remove the view parameter, the rest of the code doesn’t work.

  • 2

    You are not passing the parameter view when calling the method ask6();

  • I already tried to pass the view parameter, but of the error. Why rate is a method of a button of my xml @Valdeirpsr

  • I get it. Then replace ((RadioButton)view).isChecked(); for ((RadioButton) findViewById(R.id.ID_DO_RADIO_BUTTON)).isChecked(); and pass the parameter view

  • Can you provide the classes of each method? And also what objects do you have that instance?

  • Hi @Valdeirpsr I described the problem better. Can you look please?

  • @Jeffersonquesado I described the problem better, you could take a look?

Show 1 more comment

1 answer

3


The first error is that you are not passing the parameter view for the method ask6.

Error: Do not compile

Explanation: If you define a parameter in a method, you must pass a parameter when calling it. O java nay allows you to call a method that needs parameter, without using parameter.


The second mistake is that you are passing one Button, but in the method ask6, you are trying to "convert" to a RadioButton.

Error: Caused by: java.lang.Classcastexception: android.widget.Button cannot be cast to android.widget.Radiobutton

Explanation: Here you nay will be able to convert a Button in a RadioButton, although the names are similar, android does not allow you to convert two totally different objects.

You can only convert both to View, because they inherit methods and attributes from a class called View.


So, how to do?

First of all define a id, in XML, for your RadioGroup.

<RadioGroup
...
android:id="@+id/ask6" />

Now let’s go to the code java.

In the java, let’s remove the parameter view of the method ask6, he is not useful.

Next step is to remove all content from the method ask6, let’s do it differently.

public void ask6(){

    /* Nessa linha iremos capturar o RadioGroup da pergunta 6 e vamos capturar o ID do RadioButton marcado */
    int buttonChecked = ((RadioGroup) findViewById(R.id.ask6)).getCheckedRadioButtonId();

    switch (buttonChecked) {
        /* Iremos comparar o ID do RadioButton marcado com o ID da Resposta 1 (da pergunta 6) */
        case R.id.answer1_ask6:
            rating += 1;
        break;

        /* Iremos comparar o ID do RadioButton marcado com o ID da Resposta @ (da pergunta 6) */
        case R.id.answer2_ask6:
            rating -= 1;
        break;

        /* Caso nenhum dos buttons seja marcado, exibimos um Toast. */
        default:
            Toast.makeText(this, "Selecione a resposta da pergunta 6", Toast.LENGTH_SHORT).show();    
    }
}

That way we can call the method ask6 without the parameter view.

public void rate( View view ) {
    ask6();
    Toast.makeText(this, ("Oi "+ rating ), Toast.LENGTH_SHORT).show();
    rating = 0;
}

In case you want to check the scores of all at once, just follow the step by step.

Step 1: In XML let’s define the attribute android:tag="NOTA". Replace the note with positive or negative values. Ex:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.test.RadioButtonsActivity"
    android:orientation="vertical">

    <RadioGroup
        android:layout_marginLeft="72dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:id="@+id/ask6">
        <RadioButton
            android:id="@+id/answer1_ask6"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Resposta 1 de 6"
            android:tag="+1"/>
        <RadioButton
            android:id="@+id/answer2_ask6"
            android:layout_marginVertical="4dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Resposta 2 de 6"
            android:tag="-1"/>
    </RadioGroup>

    <RadioGroup
        android:layout_marginLeft="72dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:id="@+id/ask7">
        <RadioButton
            android:id="@+id/answer1_ask7"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Resposta 1 de 7"
            android:tag="+0.5"/>
        <RadioButton
            android:id="@+id/answer2_ask7"
            android:layout_marginVertical="4dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Resposta 2 de 7"
            android:tag="-0.5"/>
    </RadioGroup>

    <Button
        android:text="RESPONDER"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="rate"
        android:layout_marginLeft="72dp"
        android:layout_marginBottom="20dp"/>

</LinearLayout>

Step 2: In the java let’s define it this way read the comments in the code to understand:

package com.example.test;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RadioButtonsActivity extends Activity {

    private float rating = 0;

    /* Armazene aqui todos os IDs dos RadioGroup */
    List<Integer> radioGroups = new ArrayList<Integer>() {{
        add(R.id.ask6);
        add(R.id.ask7);
    }};

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

    public void ask(){

        for (Integer radioGroupId : radioGroups) {
            /* Nessa linha iremos capturar o RadioGroup da pergunta 6 e vamos capturar o ID do RadioButton marcado */
            int buttonChecked = ((RadioGroup) findViewById(radioGroupId)).getCheckedRadioButtonId();

            /* Vamos capturar o RadioButton marcado */
            RadioButton radioButton = findViewById(buttonChecked);

            /* Atribuimos "0" para caso a resposta não tenha sido marcada */
            Float point = 0f;

            try {
                /* Vamos capturar a pontuação que definimos no atributo android:tag */
                point = Float.parseFloat(radioButton.getTag().toString());
            }  catch (NullPointerException ignored) {}

            /* Vamos somar/subtrair da variável rating */
            rating += point;
        }
    }

    public void rate( View view ) {
        ask();
        Toast.makeText(this, ("Oi "+ rating ), Toast.LENGTH_SHORT).show();
        rating = 0;
    }
}

Follow this pattern, do not try to do as you have in the demo of such site, it will probably not fit in the solution you seek. Use examples for learning only.

  • Thank you so much for the answer!!! I am a student and your answer helped me a lot. But I made some changes to my code to work using switch, can you see? I’m going to post now here.

  • I can see yes..

  • Oops! I tried to post here, but the comments are really short. So I edited my question by adding the code I redid. If you can look I really appreciate it, because I’m stuck in this here.

  • Like... you didn’t follow the tips I gave, right at the beginning I posted why all the mistakes. The only thing you changed was adding a bunch of Ids to the Switch. I changed my answer. I added.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.