How to call a method inside another method?

-1

I'm developing a quiz. Using RadioButton as Answer. So far I created using the onClick method on each RadioButton, but it is not effective.

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

But when calling for example the ask6(); method within the rate(View view); of error. Even putting the view parameter ask(view); by what rate it 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 execute everything at once. So I edited my code to make each RadioButton case I have on the quiz. It looks 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 not properly call the new method. If I remove the view parameter, the rest of the code does not work.

    
asked by anonymous 08.01.2018 / 11:45

1 answer

3

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

  

Error: Do not compile

Explanation: If you set a parameter in a method, you must pass a parameter when calling it. does not allows you to call a method that needs a parameter, without using a parameter.

The second error is that you are passing Button , but in method ask6 , you are trying to "convert" to RadioButton .

  

Error: Caused by: java.lang.ClassCastException: android.widget.Button can not be cast to android.widget.RadioButton

Explanation: Here you will not be able to convert Button to RadioButton , although the names are similar, android it 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 do you do it?

First of all set a id , in XML, to its RadioGroup .

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

Now let's go to the java code.

In java , let's remove the view parameter from the ask6 method, it is not useful.

Next step is to remove all content from the ask6 method, 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();    
    }
}

In this way we can call the ask6 method without the view parameter.

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

If you want to check everyone's score at once, just follow step by step.

Step 1: In XML we will define the android:tag="NOTA" attribute. 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 java let's define 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 a site, it probably will not fit the solution you are looking for. Use the examples for learning only.

    
08.01.2018 / 13:02