Android - Problemas y dudas con el spinner

 
Vista:
sin imagen de perfil
Val: 40
Ha aumentado su posición en 2 puestos en Android (en relación al último mes)
Gráfica de Android

Problemas y dudas con el spinner

Publicado por Hector (35 intervenciones) el 05/10/2021 16:34:24
Hola amigos y amigas del foro, esperando que todos se encuentren muy bien de salud, he aquí nuevamente molestando, poseo un spinner el cual me carga los nombres el cual los hace muy bien, pero lo que pretendo ahora es que al seleccionar un nombre ya sea cualquiera me traiga los datos de ese nombre en particular, este es el código que utilizo actualmente:

public class MainActivity extends AppCompatActivity {

EditText et_siniestro,et_poliza,et_item,et_denuncia,et_designacion,et_inspeccion,et_liq,et_analista,et_nombre,
et_rut,et_direccion,et_mail,et_fono,et_conductor,et_rut1,et_mail1,et_fono1,et_licencia,et_control,
et_fechasiniestro,et_hora,et_lugar,et_ciudad,et_descripcion,et_tercero,et_rut2,et_fono2,et_marca,
et_anotercero,et_patentetercero,et_inicio,et_termino,et_plan,et_corredor,et_rut3,et_poliza1,et_deducible,et_valor,
et_valor1,et_monto,et_final,et_tipo,et_marca1,et_modelo,et_motor,et_chasis,et_ano,et_color,et_patente,
et_unidad,et_constancia,et_parte,et_estamento,et_causa,et_fechaparte,et_fechacitacion,et_id;
Spinner cmbcorredor,cmbcobertura;
private AsyncHttpClient cliente;
Button btn_grabar, btn_eliminar, btn_buscar;
AlertDialog.Builder builder;
RequestQueue requestQueue;

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

et_siniestro = findViewById(R.id.txtsiniestro1);
et_id = findViewById(R.id.txtid);
et_poliza = findViewById(R.id.txtpoliza1);
et_item = findViewById(R.id.txtitem3);
et_denuncia = findViewById(R.id.txtfechadenuncia1);
et_designacion = findViewById(R.id.txtfechadesignacion1);
et_inspeccion = findViewById(R.id.txtfechainspeccion);
et_liq = findViewById(R.id.txtliq);
et_analista = findViewById(R.id.txtanalista1);
et_nombre = findViewById(R.id.txtnombre1);
et_rut = findViewById(R.id.txtrut6);
et_direccion = findViewById(R.id.txtdireccion3);
et_mail = findViewById(R.id.txtmail4);
et_fono = findViewById(R.id.txtfono4);
et_conductor = findViewById(R.id.txtconductor1);
et_rut1 = findViewById(R.id.txtrut7);
et_mail1 = findViewById(R.id.txtmail5);
et_fono1 = findViewById(R.id.txtfono5);
et_licencia = findViewById(R.id.txtlicencia);
et_control = findViewById(R.id.txtfechacontrol);
et_fechasiniestro = findViewById(R.id.txtfechasiniestro1);
et_hora = findViewById(R.id.txthora);
et_lugar = findViewById(R.id.txtlugar);
et_ciudad = findViewById(R.id.txtciudad3);
et_descripcion = findViewById(R.id.txtdescripcion1);
et_tercero = findViewById(R.id.txttercero1);
et_rut2 = findViewById(R.id.txtrut8);
et_fono2 = findViewById(R.id.txtfono6);
et_marca = findViewById(R.id.txtmarcatercero);
et_anotercero = findViewById(R.id.txtañotercero);
et_patentetercero = findViewById(R.id.txtpatentetercero1);
et_inicio = findViewById(R.id.txtfechainicio);
et_termino = findViewById(R.id.txtfechatermino);
et_plan = findViewById(R.id.txtplan);
cmbcorredor = findViewById(R.id.cmbcorredor);
cliente = new AsyncHttpClient();
et_corredor = findViewById(R.id.txtcorredor);
et_rut3 = findViewById(R.id.txtrut9);
cmbcobertura = findViewById(R.id.cmbcobertura);
et_poliza1 = findViewById(R.id.txtpoliza2);
et_deducible = findViewById(R.id.txtdeducible);
et_valor = findViewById(R.id.txtvalor);
et_valor1 = findViewById(R.id.txtvalortotal);
et_monto = findViewById(R.id.txtmonto);
et_final = findViewById(R.id.txtfechafinal);
et_tipo = findViewById(R.id.txttipo);
et_marca1 = findViewById(R.id.txtmarca);
et_modelo = findViewById(R.id.txtmodelo);
et_motor = findViewById(R.id.txtmotor);
et_chasis = findViewById(R.id.txtchasis);
et_ano = findViewById(R.id.txtaño);
et_color = findViewById(R.id.txtcolor);
et_patente = findViewById(R.id.txtpatente1);
et_unidad = findViewById(R.id.txtunidad);
et_constancia = findViewById(R.id.txtconstancia);
et_parte = findViewById(R.id.txtparte);
et_estamento = findViewById(R.id.txtestamento);
et_causa = findViewById(R.id.txtcausa);
et_fechaparte = findViewById(R.id.txtfechaparte);
et_fechacitacion = findViewById(R.id.txtfechacitacion);
btn_grabar = findViewById(R.id.btn_grabar);
btn_eliminar = findViewById(R.id.btn_eliminar);
btn_buscar = findViewById(R.id.btn_buscar);
btn_grabar.setBackgroundColor(Color.CYAN);
btn_eliminar.setBackgroundColor(Color.CYAN);
btn_buscar.setBackgroundColor(Color.CYAN);
builder = new AlertDialog.Builder(this);
String a = "N° 2021-*-FVJ/VEH";
et_liq.setText(a);
llenarspinner();
et_siniestro.requestFocus();

btn_buscar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
builder.setMessage(R.string.dialog_message3).setTitle(R.string.dialog_title);
builder.setMessage("¿Desea recuperar los datos?").setCancelable(false).setPositiveButton("Si", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
et_id.setVisibility(View.VISIBLE);
et_id.requestFocus();
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
et_siniestro.requestFocus();
}
});
AlertDialog alert = builder.create();
alert.setTitle("Oficina");
alert.show();
}
});

cmbcorredor.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position){
case 0:
int index = cmbcorredor.getSelectedItemPosition();
et_corredor.setVisibility(View.GONE);
case 1:
int index1 = cmbcorredor.getSelectedItemPosition();
String url = "http://192.168.1.96/oficina/buscar_corredores.php?Nombre_Corredor=" + cmbcorredor.getSelectedItem().toString();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
if (response.length() == 1) {
try {
JSONObject jsonObject = new JSONObject(response.get(0).toString());
et_corredor.setText(jsonObject.getString("Nombre_Corredor"));
et_rut3.setText(jsonObject.getString("Rut_Corredor"));
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, "Este Nombre de Corredor no ha sido ingresado aún", Toast.LENGTH_SHORT).show();
llenarspinner();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(jsonArrayRequest);
break;
}
}
});

}

public void Consultar1 (View view){
String url = "http://192.168.1.96/oficina/buscar_casos1.php?ID=" + et_id.getText().toString();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
if (response.length() == 1) {
try {
JSONObject jsonObject = new JSONObject(response.get(0).toString());
et_id.setText(jsonObject.getString("ID"));
et_siniestro.setText(jsonObject.getString("N_Siniestro"));
et_denuncia.setText(jsonObject.getString("Fecha_Denuncia"));
et_fechasiniestro.setText(jsonObject.getString("Fecha_Siniestro"));
et_descripcion.setText(jsonObject.getString("Descripcion"));
et_conductor.setText(jsonObject.getString("Nombre_Conductor"));
et_rut1.setText(jsonObject.getString("Rut_Conductor"));
et_patente.setText(jsonObject.getString("Patente_Vehiculo"));
et_tercero.setText(jsonObject.getString("Nombre_Tercero"));
et_patentetercero.setText(jsonObject.getString("Patente_Tercero"));
et_nombre.setText(jsonObject.getString("Nombre_Asegurado"));
et_rut.setText(jsonObject.getString("Rut_Asegurado"));
et_poliza.setText(jsonObject.getString("N_Poliza"));
et_designacion.setText(jsonObject.getString("Fecha_Designacion"));
et_id.setVisibility(View.GONE);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, "Este N° de Registro no ha sido ingresado", Toast.LENGTH_SHORT).show();
et_siniestro.setText("");
et_id.setText("");
et_id.setVisibility(View.GONE);
et_siniestro.requestFocus();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}

private void llenarspinner (){
String url1 = "http://192.168.1.96/oficina/buscar_corredores1.php";
cliente.post(url1, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
if (statusCode == 200){
cargarSpinner (new String(responseBody));
}
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

}
});
}

private void cargarSpinner (String respuesta){
requestQueue = Volley.newRequestQueue(this);
ArrayList <Corredores> lista = new ArrayList<Corredores>();
try {
JSONArray jsonArreglo = new JSONArray(respuesta);
for (int i = 0; i < jsonArreglo.length(); i++){
Corredores c = new Corredores();
c.setNombre(jsonArreglo.getJSONObject(i).getString("Nombre_Corredor"));
lista.add(c);
}
ArrayAdapter <Corredores> a = new ArrayAdapter<>(this,android.R.layout.simple_dropdown_item_1line,lista);
cmbcorredor.setAdapter(a);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}

y este es la java.class que utiizo

package com.example.prueba;

public class Corredores {
private String nombre;
private String rut;

public Corredores() {
this.nombre = nombre;
this.rut = rut;
}

public void setNombre(String nombre) {
this.nombre = nombre;
}

public void setRut(String rut) {
this.rut = rut;
}

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

como pueden apreciar en el cmbcorredor es lo que pretendo hacer traer los datos a distintas cajas de texto, estoy aprendiendo android con java y es la primera vez que utilizo el spinner, ojala que me puedan ayudar y asesorar con este gran problema para mi y desde ya muchas gracias.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
1
Responder
Imágen de perfil de Rene
Val: 22
Ha disminuido 1 puesto en Android (en relación al último mes)
Gráfica de Android

Problemas y dudas con el spinner

Publicado por Rene (21 intervenciones) el 16/12/2021 21:10:01
Aqui te envio 3 tutoriales en 3 respuestas por separado, de como utilizar el spinner, espero te ayuden.

Te recomiendo te hagas de tutoriales y libros para especializar tus conocimientos, estos lugares son buenos. Los libros los puedes bajar aqui mismo en Cursos y Manuales.

Lynda - Android SDK Essential Training Tutorial
Lynda - Android SDK Local Data Storage
codigoprogramacion.com
Desarrollo en Android _ sgoliver.net blog.htm

Atte René
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
Imágen de perfil de Rene
Val: 22
Ha disminuido 1 puesto en Android (en relación al último mes)
Gráfica de Android

Problemas y dudas con el spinner

Publicado por Rene (21 intervenciones) el 16/12/2021 21:50:52
Y además este libro que te motivará con la programación en Android

Atte: Rene

PD: Vi la fecha en que publicaste tu pregunta y yo te respondo dos meses después de todas maneras recibe la ayuda que puedo hacerte.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar