Coin converter in android studio

0

I'm doing a currency converter in android, with three currencies (euro, dollar and pound) but I can not get conversions right. I do not know what fault I have and I can not clarify it, I leave the MainActivity.java class to see if someone can detect it.

public class MainActivity extends AppCompatActivity implements Spinner.OnItemSelectedListener {

double opcionEntrada = 0;
double opcionSalida = 0;

TextView resultado;
TextView entrada;

Moneda[] tiposDeMoneda = new Moneda[]{new Moneda(R.drawable.europa, "Euro"),

        new Moneda(R.drawable.unitedkingdom, "Reino Unido"),

        new Moneda(R.drawable.eeuu, "Estados Unidos")};

public MainActivity() {
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    Spinner sp = (Spinner) findViewById(R.id.spinner);
    AdaptadorPersonalizado a = new AdaptadorPersonalizado(this, R.layout.diseno_combo, tiposDeMoneda);
    sp.setAdapter(a);
    sp.setOnItemSelectedListener(this);

    resultado = (TextView) findViewById(R.id.textView4);
    entrada = (TextView) findViewById(R.id.editText);

    Button boton = (Button) findViewById(R.id.button);
    boton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            double resultadoNumero;

            if (opcionSalida == 0 && opcionEntrada == 0) {
                resultado.setText(entrada.getText());
            }

            if (opcionEntrada == 0 && opcionSalida == 1) {
                int num1 = entrada.getInputType();
                double num2 = 0.89;

                resultadoNumero =  num2 * num1;
                resultado.setText(String.valueOf(resultadoNumero));

            }

            if (opcionEntrada == 0 && opcionSalida == 2) {
                int num1 = entrada.getInputType();
                double num3 = 1.14;

                resultadoNumero = num1 * num3;
                resultado.setText(String.valueOf(resultadoNumero));
            }
        }
    });
}

@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
    TextView textView = (TextView) view.findViewById(R.id.textView);
    String valor = (String) textView.getText();
    switch (valor) {
        case "Euro":
            opcionSalida = 0;
            break;

        case "Reino Unido":
            opcionSalida = 1;
            break;

        case "Estados Unidos":
            opcionSalida = 2;
            break;

    }
    Toast.makeText(this, textView.getText(), Toast.LENGTH_SHORT).show();

}

@Override
public void onNothingSelected(AdapterView<?> adapterView) {

}

}

    
asked by Juan 02.12.2018 в 14:52
source

2 answers

0

I leave you an example of how I implemented a functionality similar to what you need.

Project Structure

java
-- beans
---- MonedaBean.java
-- views
---- adapters
------ MonedaAdapter.java
-- MainActivity.java
res
-- layout
---- activity_main.xml
---- model_item_moneda.xml

1.- I make the design in the layout activity_main.xml

<?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"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/etMonto"
        android:hint="Ingresar monto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Spinner
        android:id="@+id/spMoneda"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></Spinner>

    <Button
        android:id="@+id/btnConvertir"
        android:text="Convertir"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/tvResultado"
        android:layout_marginTop="16dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

2.- I create the layout model_item_moneda.xml, they are the options that will be shown in the spinner.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:paddingTop="8dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingBottom="8dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/ivMoneda"
        tools:background="@mipmap/ic_currency_eur_black_24dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/tvMoneda"
        android:layout_marginLeft="8dp"
        android:text="Euro"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

3.- I believe MonedaBean.java, its function is to feed a DataSource list, which will work with MonedaAdapter.java to show the types of coins in the spinner.

public class MonedaBean {

    private int image;
    private String name;
    private Double montoCambio;

    public MonedaBean(int image, String name, Double montoCambio) {
        this.image = image;
        this.name = name;
        this.montoCambio = montoCambio;
    }

    public int getImage() {
        return image;
    }

    public void setImage(int image) {
        this.image = image;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getMontoCambio() {
        return montoCambio;
    }

    public void setMontoCambio(Double montoCambio) {
        this.montoCambio = montoCambio;
    }

    @Override
    public String toString() {
        return name;
    }
}

4.- I create MonedaAdapter.java, it will serve as a manager or administrator to create the options in the spinner based on a DataSource list of MonedaBean.java

public class MonedaAdapter extends ArrayAdapter<MonedaBean> {

    private Context context;
    private List<MonedaBean> list;

    public MonedaAdapter(Context context, int resource, List<MonedaBean> list) {
        super(context,  R.layout.model_item_moneda, resource, list);
        this.context = context;
        this.list = list;
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }

    public View getCustomView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View row = inflater.inflate(R.layout.model_item_moneda, parent, false);

        TextView tvMoneda = row.findViewById(R.id.tvMoneda);
        // Importante incluir el atributo setTextColor ya que de lo contrario el texto se muestra en color blanco
        tvMoneda.setTextColor(Color.parseColor("#000000"));
        tvMoneda.setText(list.get(position).getName());

        ImageView ivMoneda = row.findViewById(R.id.ivMoneda);
        ivMoneda.setImageResource(list.get(position).getImage());

        return row;
    }

}

5.- Finally I work in the MainActivity.java.

public class MainActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener {

    private EditText etMonto;
    private Spinner spMoneda;
    private Button btnConvertir;
    private TextView tvResultado;

    private List<MonedaBean> list;

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

        // Obtener función sobre las referencias
        getUI();
    }

    public void getUI() {
        // Referencias o binding
        etMonto = findViewById(R.id.etMonto);
        spMoneda = findViewById(R.id.spMoneda);
        btnConvertir = findViewById(R.id.btnConvertir);
        tvResultado = findViewById(R.id.tvResultado);

        // Habilitar acción click
        btnConvertir.setOnClickListener(this);

        // Cargar monedas
        list = new ArrayList<>();
        list.add(new MonedaBean(0, "Seleccionar Moneda", 0.0));
        list.add(new MonedaBean(R.mipmap.ic_currency_eur_black_24dp, "Euro", 3.8));
        list.add(new MonedaBean(R.mipmap.ic_currency_usd_black_24dp, "Dollar", 3.4));

        // Iniciar Adaptador
        MonedaAdapter monedaAdapter = new MonedaAdapter(getApplicationContext(), android.R.layout.simple_spinner_item, list){
            @Override
            public boolean isEnabled(int position) {
                // Si la posición es cero desahabilitamos la primera opción
                if (position == 0) {
                    return false;
                } else {
                    return true;
                }
            }

            @Override
            public View getDropDownView(int position, View convertView, ViewGroup parent) {
                View view = super.getDropDownView(position, convertView, parent);
                TextView textview = view.findViewById(R.id.tvMoneda);
                // Si la posición es cero modificamos el color del texto
                if (position == 0) {
                    textview.setTextColor(Color.GRAY);
                } else {
                    textview.setTextColor(Color.BLACK);
                }
                return view;
            }
        };
        monedaAdapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
        spMoneda.setAdapter(monedaAdapter);
        spMoneda.setOnItemSelectedListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnConvertir:

                // Validar que se ingreso un monto
                if(!etMonto.getText().toString().isEmpty()) {
                    // Nos aseguramos que se seleccione una moneda
                    int position = spMoneda.getSelectedItemPosition();

                    if(position > 0) {
                        Double resultado = Double.parseDouble(etMonto.getText().toString()) * list.get(position).getMontoCambio();
                        tvResultado.setText(resultado.toString());
                    } else {
                        Toast.makeText(getApplicationContext(), "Seleccionar Moneda", Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "Ingresar monto", Toast.LENGTH_LONG).show();
                }

                break;
        }
    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {

    }

}
    
answered by 03.12.2018 / 18:30
source
0

I would think that your problem is solved that at the moment of pressing verify that item is selected in the spinner:

 boton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            double resultadoNumero;
            int posicionSeelccionada = sp.getSelectedItemPosition(); // vemos que posicion se selecciono iniciando desde la posicion cero
            if (posicionSeelccionada==1){
                // hacemos el calculo
            }else if(posicionSeelccionada== 2){
                //hacemos el calculo
            }else{
                // hacemos el calculo
            }
        }
    });
    
answered by 03.12.2018 в 02:22