Recuperacion y almacenamieento de informacion
en esta entrada se vera un ejemplo del uso de shrap preference con el cual guardaremos y recuperaremos datos en el ambiente android studio
CODIGO.
packagecom.example.a3;importandroidx.appcompat.app.AppCompatActivity;importandroid.content.Context;importandroid.content.SharedPreferences;importandroid.os.Bundle;importandroid.view.View;importandroid.widget.EditText;importandroid.widget.TextView;publicclassMainActivityextendsAppCompatActivity {privateEditText etJugador, etNumero;privateTextView tvAcumulado, tvAcumulado2, tvMensaje;privateintnumero;@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);etJugador =(EditText) findViewById(R.id.etJugador);etNumero =(EditText) findViewById(R.id.etNumero);tvAcumulado =(TextView) findViewById(R.id.tvAcumulado);tvAcumulado2 =(TextView) findViewById(R.id.tvAcumulado2);tvMensaje =(TextView) findViewById(R.id.tvmensaje);SharedPreferences prefe=getSharedPreferences("datos", Context.MODE_PRIVATE);String v=String.valueOf(prefe.getInt("puntos",0));tvAcumulado.setText(v);tvAcumulado2.setText(v);numero =1+(int)(Math.random()*20);}publicvoidVerificar(View View) {intvalor = Integer.parseInt(etNumero.getText().toString());intjugador = Integer.parseInt(etJugador.getText().toString());if(jugador==1){if(numero == valor) {intpuntosactual = Integer.parseInt(tvAcumulado.getText().toString());puntosactual = puntosactual +1;tvAcumulado.setText(String.valueOf(puntosactual));tvMensaje.setText("¡Muy bien! ¡Gano!. Digita otro numero");etNumero.setText("");SharedPreferences prefe = getSharedPreferences("datos", Context.MODE_PRIVATE);SharedPreferences.Editor editor = prefe.edit();editor.putInt("puntos", puntosactual);editor.commit();random();}else{if(valor>numero){tvMensaje.setText("Ingreso un numero mayor al que genro la maquina");}else{tvMensaje.setText("Ingreso un numero menor al que genro la maquina");}}}if(jugador==2){if(numero == valor) {intpuntosactual1 = Integer.parseInt(tvAcumulado2.getText().toString());puntosactual1 = puntosactual1 +1;tvAcumulado2.setText(String.valueOf(puntosactual1));tvMensaje.setText("¡Muy bien! ¡Gano!. Digita otro numero");etNumero.setText("");SharedPreferences prefe = getSharedPreferences("datos", Context.MODE_PRIVATE);SharedPreferences.Editor editor = prefe.edit();editor.putInt("puntos", puntosactual1);editor.commit();random();}else{if(valor>numero){tvMensaje.setText("Ingreso un numero mayor al que genro la maquina");}else{tvMensaje.setText("Ingreso un numero menor al que genro la maquina");}}}}publicintrandom(){numero =1+(int)(Math.random()*20);returnnumero;}}
Comentarios
Publicar un comentario