将数据从alertdilog返回mainactivty

j0pj023g  于 2021-07-03  发布在  Java
关注(0)|答案(4)|浏览(209)

我正在开发一个应用程序来计算你的体重指数,我有一个trobles传递一个数据,该数据是一个请求到用户进入一个警报日志,因为当我回到主活动,我失去了数据,我进入这个活动。我尝试使用活动的生命周期来恢复bundle,我将mainactivity的数据保存到onpostresume()方法中,但两者都不起作用。
主活动类

public class MainActivity extends AppCompatActivity implements DiologInterface {

    private ImageView imgChico;
    private ImageView imgChica;
    private RadioButton rbChico;
    private RadioButton rbChica;
    private EditText EtAnios;
    private EditText EtAltura;
    private EditText EtPeso;
    private TextView txtResultado;
    private TextView txtResultadoCalorias;
    private Button btnEstiloVida;
    private double peso;
    private double altura;
    private int edad;
    private double calorias;

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

        //Set up the Components.
        imgChico = findViewById(R.id.imgChico);
        imgChico.setImageResource(R.drawable.ic_launcher_chico_foreground);
        imgChica = findViewById(R.id.imgChica);
        imgChica.setImageResource(R.drawable.ic_launcher_chica_foreground);

        rbChica = (RadioButton) findViewById(R.id.rbChica);
        rbChico = (RadioButton) findViewById(R.id.rbChico);

        EtAltura = (EditText) findViewById(R.id.EtAltura);
        EtAnios = (EditText) findViewById(R.id.EtAnios);
        EtPeso = (EditText) findViewById(R.id.EtPeso);

        txtResultado = (TextView) findViewById(R.id.txtResultado);
        txtResultadoCalorias = (TextView) findViewById(R.id.txtResultadoCalorias);

        /****Utilizamos el Bundle del metodo OnCreate para establecer los datos introducidos.****/
        if(savedInstanceState!=null){
            EtPeso.setText((int) savedInstanceState.getDouble("peso"));
            EtAnios.setText(savedInstanceState.getInt("edad"));
            EtAltura.setText((int) savedInstanceState.getDouble("altura"));
        }

        /****Si rescato aqui los datos los machaca al volver al MainActivity****/
        //getDatos(peso, altura, edad);

        /***AQAUI INTETNABA HACERLO CON UN INTENT Y UN BUNDLE.***/

        btnEstiloVida = (Button) findViewById(R.id.btnEstiloVida);
        btnEstiloVida.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                openDiolog();
               getDatos(peso, altura, edad);

            }
        });

    }

    private void openDiolog() {

        DialogFragment newFragment = new EstiloVida();
        newFragment.show(getSupportFragmentManager(), "Entrada_Usuario");

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
        // Get the layout inflater
        LayoutInflater inflater = getLayoutInflater();

        // Inflate and set the layout for the dialog
        // Pass null as the parent view because its going in the dialog layout
        builder.setView(inflater.inflate(R.layout.estilo_vida, null));

        return builder.create();
    }
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.item_info:
                Toast miToast = Toast.makeText(getApplicationContext(), "Author: Manuel Lucas Sánchez", Toast.LENGTH_LONG);
                miToast.setGravity(Gravity.CENTER, 0, 0);
                miToast.show();
                return true;

            case R.id.item__salir:
                Toast miToast2 = Toast.makeText(getApplicationContext(), "Saliendo de la aplicación", Toast.LENGTH_LONG);
                miToast2.setGravity(Gravity.CENTER, 0, 0);
                miToast2.show();
                System.exit(0);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    @Override
    protected void onPostResume() {
        super.onPostResume ();

        /****************ESTA LINEA AL RECUPERAR EL BUNDLE DE LA ACTIVITY ESTA A NULL, AUNQUE ANTES DE ABANDONAR EL MAINACTIVTY SI QUE EXISTÍA**************************/

        Bundle datos = getIntent().getExtras();

        /****************************************************************************************************************************************************************/
        if(datos==null){
            Toast.makeText(getApplicationContext(), "Es necesario introducir el estilo de vida", Toast.LENGTH_LONG).show();
        }else {
            int actividad = datos.getInt("ACTIVIDAD");

            /****Si rescato aqui los datos los machaca al volver al MainActivity, igual que en el OnCreated()****/
           //getDatos(peso, altura, edad);

            switch (actividad){

                case 1:
                    txtResultado.setText("No muy activo");
                    if(rbChico.isChecked()){
                        calorias = CalculaCalorias.calculaTBM(peso, altura, edad, true, 1);
                    }else{
                        calorias = CalculaCalorias.calculaTBM(peso, altura, edad, false, 1);
                    }
                    txtResultadoCalorias.setText(String.valueOf(calorias));
                    break;
                case 2:
                    txtResultado.setText("Medianamente activo");
                    if(rbChico.isChecked()){
                        calorias =  CalculaCalorias.calculaTBM(peso, altura, edad, true, 2);
                    }else{
                        calorias = CalculaCalorias.calculaTBM(peso, altura, edad, false, 2);
                    }
                    txtResultadoCalorias.setText(String.valueOf(calorias));
                    break;
                case 3:
                    txtResultado.setText("Activo");
                    if(rbChico.isChecked()){
                        calorias = CalculaCalorias.calculaTBM(peso, altura, edad, true, 3);
                    }else{
                        calorias =  CalculaCalorias.calculaTBM(peso, altura, edad, false, 3);
                    }
                    txtResultadoCalorias.setText(String.valueOf(calorias));
                    break;
                case 4:
                    txtResultado.setText("Muy activo");
                    if(rbChico.isChecked()){
                        calorias = CalculaCalorias.calculaTBM(peso, altura, edad, true, 4);
                    }else{
                        calorias = CalculaCalorias.calculaTBM(peso, altura, edad, false, 4);
                    }
                    txtResultadoCalorias.setText(String.valueOf(calorias));
                    break;
            }
        }

    }

    private void getDatos(double peso, double altura, int edad) {

       if(EtPeso.getText().toString().trim().isEmpty()){
           Toast.makeText(getApplicationContext(), "Se debe introducir el peso", Toast.LENGTH_SHORT).show();
        }else {
           peso = Double.parseDouble(EtPeso.getText().toString());
            if (EtAnios.getText().toString().trim().isEmpty()) {
                Toast.makeText(getApplicationContext(), "Se debe introducir la edad", Toast.LENGTH_SHORT).show();

            }else {
                edad = Integer.parseInt(EtAnios.getText().toString());
                if(EtAltura.getText().toString().trim().isEmpty()){
                    Toast.makeText(getApplicationContext(), "Se debe introducir la altura", Toast.LENGTH_SHORT).show();
                }else{
                    altura = Double.parseDouble(EtAltura.getText().toString());
                }
            }
        }
    }
    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {

        outState.putDouble("peso",peso);
        outState.putDouble("altura",altura);
        outState.putInt("edad",edad);

        super.onSaveInstanceState(outState);
    }
    @Override
    protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {

        EtAnios.setText(savedInstanceState.getInt("edad"));
        EtAltura.setText((int) savedInstanceState.getDouble("altura"));
        EtPeso.setText((int) savedInstanceState.getDouble("peso"));

        super.onRestoreInstanceState(savedInstanceState);
    }
}

estilovida.类

public class EstiloVida extends AppCompatDialogFragment {

    private int actividad;
    private CheckBox cbxActivo;
    private CheckBox cbxInactivo;
    private CheckBox cbxPocoActivo;
    private CheckBox cbxMuyActivo;
    private Button btnEnviar;

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LayoutInflater inflater = requireActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.estilo_vida,null);

        cbxActivo = (CheckBox) view.findViewById(R.id.cbxActivo);
        cbxInactivo = (CheckBox) view.findViewById(R.id.cbxInactivo);
        cbxMuyActivo = (CheckBox) view.findViewById(R.id.cbxMuyActivo);
        cbxPocoActivo = (CheckBox) view.findViewById(R.id.cbxMedioActivo);

        btnEnviar = (Button) view.findViewById(R.id.btnEnviar);
        btnEnviar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                actividad = 0;
                if(cbxInactivo.isSelected()){
                    actividad = 1;
                }else if (cbxPocoActivo.isSelected()){
                    actividad = 2;
                }else if (cbxActivo.isSelected()){
                    actividad = 3;
                }else if (cbxMuyActivo.isSelected()){
                    actividad = 4;
                }
                Intent miIntent = new Intent(getContext(), MainActivity.class);
                miIntent.putExtra("ACTIVIDAD", actividad);
                startActivity(miIntent);
            }
        });
        builder
                .setTitle(R.string.title_login)
                .setMessage(R.string.EstiloVida)
                .setView(view);

    return builder.create();
        }
    }

diologinterface.interface接口

public interface DiologInterface {
    Dialog onCreateDialog(Bundle savedInstanceState);
}

和calculacalorias.class`

public class CalculaCalorias {

    public static double calculaTBM(double peso, double altura, int edad, boolean esChico, int estiloVida){

        double TBM = 0;

        if(esChico){

            TBM = (10*peso) + (6.25*altura) - (5-edad) -161;

        switch (estiloVida) {
            case 1:
                TBM = TBM*1.2;
                break;
            case 2:
                TBM = TBM*1.375;

                break;
            case 3:
                TBM = TBM*1.55;
                break;
            case 4:
                TBM = TBM*1.725;
                break;
        }

        }else {

            TBM = (10*peso) + (6.25*altura) - (5-edad) +5;
            switch (estiloVida) {
                case 1:
                    TBM = TBM*1.2;
                    break;
                case 2:
                    TBM = TBM*1.375;

                    break;
                case 3:
                    TBM = TBM*1.55;
                    break;
                case 4:
                    TBM = TBM*1.725;
                    break;
            }
        }

        return TBM;
    }
}

我希望你能给这个问题带来一些启示,如果你知道解决方法或者知道这个,请提前感谢!

dnph8jn4

dnph8jn41#

好的,这是xml文件:
活动\u main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".MainActivity">

    <TextView
        android:id="@+id/txtAltura5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="¿Cuánto pesas?"
        app:layout_constraintBottom_toTopOf="@+id/EtPeso"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/EtAnios" />

    <TextView
        android:id="@+id/txtResultadoCalorias"
        android:layout_width="129dp"
        android:layout_height="0dp"
        android:layout_marginBottom="28dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/txtResultado" />

    <TextView
        android:id="@+id/txtTituloPrincipal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="700dp"
        android:text="Calorias diarias recomendas:"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/EtPeso"
        android:layout_width="124dp"
        android:layout_height="0dp"
        android:layout_marginBottom="11dp"
        android:textSize="14sp"
        app:layout_constraintBottom_toTopOf="@+id/txtAltura"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/txtAltura5" />

    <RadioButton
        android:id="@+id/rdbChico"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="130dp"
        android:layout_marginBottom="300dp"
        android:text="Hombre"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/imgChico"
        android:layout_width="105dp"
        android:layout_height="103dp"
        android:layout_marginStart="200dp"
        android:layout_marginEnd="60dp"
        android:layout_marginBottom="500dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/ic_launcher_chico_foreground" />

    <ImageView
        android:id="@+id/imgChica"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="60dp"
        android:layout_marginEnd="200dp"
        android:layout_marginBottom="500dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/ic_launcher_chica_foreground" />

    <RadioButton
        android:id="@+id/rdbChica"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="180dp"
        android:layout_marginBottom="300dp"
        android:text="Mujer"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/txtCuantosAnios"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="450dp"
        android:text="¿Cuantos años tienes?"
        app:layout_constraintBottom_toTopOf="@+id/EtAnios"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/EtAnios"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="4dp"
        android:layout_marginEnd="4dp"
        android:layout_marginBottom="14dp"
        android:textSize="14sp"
        app:layout_constraintBottom_toTopOf="@+id/txtAltura5"
        app:layout_constraintEnd_toEndOf="@+id/EtPeso"
        app:layout_constraintStart_toStartOf="@+id/EtPeso"
        app:layout_constraintTop_toBottomOf="@+id/txtCuantosAnios" />

    <TextView
        android:id="@+id/txtAltura"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="¿Cuánto mides?"
        app:layout_constraintBottom_toTopOf="@+id/EtAltura"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/EtPeso" />

    <EditText
        android:id="@+id/EtAltura"
        android:layout_width="113dp"
        android:layout_height="0dp"
        android:layout_marginBottom="113dp"
        android:textSize="14sp"
        app:layout_constraintBottom_toTopOf="@+id/btnEstiloVida"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/txtAltura" />

    <Button
        android:id="@+id/btnEstiloVida"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="46dp"
        android:layout_marginEnd="46dp"
        android:layout_marginBottom="100dp"
        android:text="Estilo de vida"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/EtAltura" />

    <TextView
        android:id="@+id/txtResultado"
        android:layout_width="247dp"
        android:layout_height="0dp"
        android:layout_marginEnd="164dp"
        android:layout_marginBottom="50dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnEstiloVida"
        app:layout_constraintVertical_bias="0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>

estilo_vida.xml

<androidx.constraintlayout.widget.ConstraintLayout 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">

    <CheckBox
        android:id="@+id/cbxMedioActivo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Medianamente activo"
        app:layout_constraintStart_toStartOf="@+id/cbxInactivo"
        app:layout_constraintTop_toBottomOf="@+id/cbxInactivo" />

    <CheckBox
        android:id="@+id/cbxActivo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="23dp"
        android:text="Activo"
        app:layout_constraintStart_toStartOf="@+id/cbxMedioActivo"
        app:layout_constraintTop_toBottomOf="@+id/cbxMedioActivo" />

    <CheckBox
        android:id="@+id/cbxMuyActivo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="38dp"
        android:layout_marginTop="26dp"
        android:text="Muy activo"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/cbxActivo" />

    <TextView
        android:id="@+id/txtTituloPrincipal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="33dp"
        android:text="Estilo de Vida"
        android:textSize="18sp"
        android:textStyle="bold|italic"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <CheckBox
        android:id="@+id/cbxInactivo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="38dp"
        android:layout_marginTop="25dp"
        android:text="No muy activo"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/txtTituloPrincipal" />

    <androidx.constraintlayout.widget.Group
        android:id="@+id/group"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:constraint_referenced_ids="cbxInactivo,cbxMedioActivo,cbxActivo,cbxMuyActivo"
        app:layout_constraintBottom_toTopOf="parent"
        app:layout_constraintEnd_toStartOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnEnviar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="14dp"
        android:layout_marginTop="25dp"
        android:layout_marginEnd="49dp"
        android:layout_marginBottom="601dp"
        android:text="Enviar"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/txtTituloPrincipal"
        app:layout_constraintTop_toBottomOf="@+id/txtTituloPrincipal" />
</androidx.constraintlayout.widget.ConstraintLayout>
bfrts1fy

bfrts1fy2#

好吧,我找到了解决我最后一个问题的方法https://parzibyte.me/blog/2019/02/23/android-solucion-error-unable-to-add-window-token-null-is-not-valid-is-your-activity-running/
但现在我进入了troble这个“btnenviar”,它什么都不做:
此按钮的代码如下:

public class EstiloVida extends AppCompatDialogFragment {

    private int actividad;
    private CheckBox cbxActivo;
    private CheckBox cbxInactivo;
    private CheckBox cbxPocoActivo;
    private CheckBox cbxMuyActivo;
    private Button btnEnviar;

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LayoutInflater inflater = requireActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.estilo_vida,null);

        cbxActivo = (CheckBox) view.findViewById(R.id.cbxActivo);
        cbxInactivo = (CheckBox) view.findViewById(R.id.cbxInactivo);
        cbxMuyActivo = (CheckBox) view.findViewById(R.id.cbxMuyActivo);
        cbxPocoActivo = (CheckBox) view.findViewById(R.id.cbxMedioActivo);

        btnEnviar = (Button) view.findViewById(R.id.btnEnviar);
        btnEnviar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                actividad = 0;
                if(cbxInactivo.isSelected()){
                    actividad = 1;
                }else if (cbxPocoActivo.isSelected()){
                    actividad = 2;
                }else if (cbxActivo.isSelected()){
                    actividad = 3;
                }else if (cbxMuyActivo.isSelected()){
                    actividad = 4;
                }
                if (requireActivity() instanceof OnReceiveDataListener) {
                    Bundle data = new Bundle();
                    data.putInt("ACTIVIDAD", actividad);
                    ((OnReceiveDataListener) requireActivity()).onReceiveData(data);
                }

                Intent miIntent = new Intent(getContext(), MainActivity.class);
                miIntent.putExtra("ACTIVIDAD", actividad);
                startActivity(miIntent);
            }
        });
        builder
                .setTitle(R.string.title_login)
                .setMessage(R.string.EstiloVida)
                .setView(view);

        //dismiss();

    return builder.create();
        }
    }

很显然,它必须将用户的活动级别发送到主活动,但这就像onclicklistener方法不起作用一样。
我不知道我是否需要在代码的其他部分添加侦听器或者什么。。

9rygscc1

9rygscc13#

好的,在做了修改之后,当我点击estilovida按钮时,我在logcat上得到以下错误

2020-12-16 14:18:08.467 29610-29610/com.example.contador_calorias E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.contador_calorias, PID: 29610
    android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
        at android.view.ViewRootImpl.setView(ViewRootImpl.java:907)
        at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:387)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:95)
        at android.app.Dialog.show(Dialog.java:342)
        at com.example.contador_calorias.MainActivity$1.onClick(MainActivity.java:83)

误差线如下:

btnEstiloVida = (Button) findViewById(R.id.btnEstiloVida);
        btnEstiloVida.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               // Toast.makeText(getApplicationContext(), "Introduce el estilo de vida", Toast.LENGTH_LONG).show();

/**********************THIS LINE IS WHICH THROW THE ERROR*************/
                OnCreatedDiolog().show();

/*******************************************************/
                openDiolog();
                getDatos(peso, altura, edad);

            }
        });
    }

    private AlertDialog OnCreatedDiolog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
        // Get the layout inflater
        LayoutInflater inflater = getLayoutInflater();

        // Inflate and set the layout for the dialog
        // Pass null as the parent view because its going in the dialog layout
        builder.setView(inflater.inflate(R.layout.estilo_vida, null));

        return builder.create();
    }

    private void openDiolog() {

        DialogFragment newFragment = new EstiloVida();
        newFragment.show(getSupportFragmentManager(), String.valueOf(R.string.title_login));

    }
6ljaweal

6ljaweal4#

解决方案
第一步。删除 DiologInterface 接口
第二步。删除里面的代码 MainActivity 实现 DiologInterface .

// Remove this
implements DiologInterface

// Remove this
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
    // Get the layout inflater
    LayoutInflater inflater = getLayoutInflater();

    // Inflate and set the layout for the dialog
    // Pass null as the parent view because its going in the dialog layout
    builder.setView(inflater.inflate(R.layout.estilo_vida, null));

    return builder.create();
}

第三步。创建一个名为 OnReceiveDataListener ,此接口将用于将数据从对话框传递到活动。

interface OnReceiveDataListener {
    void onReceiveData(Bundle data);
}

第四步。让 MainActivity 实现此接口

public class MainActivity extends AppCompatActivity implements OnReceiveDataListener {

    @Override
    public void onReceiveData(Bundle data) {
        if (data == null) {
            Toast.makeText(getApplicationContext(), "Es necesario introducir el estilo de vida", Toast.LENGTH_LONG).show();
        } else {
            int actividad = data.getInt("ACTIVIDAD");

            /****Si rescato aqui los datos los machaca al volver al MainActivity, igual que en el OnCreated()****/
            //getDatos(peso, altura, edad);

            switch (actividad) {

                case 1:
                    txtResultado.setText("No muy activo");
                    if (rbChico.isChecked()) {
                        calorias = CalculaCalorias.calculaTBM(peso, altura, edad, true, 1);
                    } else {
                        calorias = CalculaCalorias.calculaTBM(peso, altura, edad, false, 1);
                    }
                    txtResultadoCalorias.setText(String.valueOf(calorias));
                    break;
                case 2:
                    txtResultado.setText("Medianamente activo");
                    if (rbChico.isChecked()) {
                        calorias = CalculaCalorias.calculaTBM(peso, altura, edad, true, 2);
                    } else {
                        calorias = CalculaCalorias.calculaTBM(peso, altura, edad, false, 2);
                    }
                    txtResultadoCalorias.setText(String.valueOf(calorias));
                    break;
                case 3:
                    txtResultado.setText("Activo");
                    if (rbChico.isChecked()) {
                        calorias = CalculaCalorias.calculaTBM(peso, altura, edad, true, 3);
                    } else {
                        calorias = CalculaCalorias.calculaTBM(peso, altura, edad, false, 3);
                    }
                    txtResultadoCalorias.setText(String.valueOf(calorias));
                    break;
                case 4:
                    txtResultado.setText("Muy activo");
                    if (rbChico.isChecked()) {
                        calorias = CalculaCalorias.calculaTBM(peso, altura, edad, true, 4);
                    } else {
                        calorias = CalculaCalorias.calculaTBM(peso, altura, edad, false, 4);
                    }
                    txtResultadoCalorias.setText(String.valueOf(calorias));
                    break;
            }
        }
    }
}

第五步。将数据从对话框传递到活动

btnEnviar.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        actividad = 0;
        if (cbxInactivo.isSelected()) {
            actividad = 1;
        } else if (cbxPocoActivo.isSelected()) {
            actividad = 2;
        } else if (cbxActivo.isSelected()) {
            actividad = 3;
        } else if (cbxMuyActivo.isSelected()) {
            actividad = 4;
        }

        // Pass data back to Activity using OnReceiveDataListener
        if (requireActivity() instanceof OnReceiveDataListener) {
            Bundle data = new Bundle();
            data.putInt("ACTIVIDAD", actividad);
            ((OnReceiveDataListener) requireActivity()).onReceiveData(data);
        }

        // You can dismiss the dialog if you want
        // dismiss();
    }
});

相关问题