ALMACENACION Y RECUPERACION SHAREDPREFERENCES EJERCICIO 2
package com.example.portafolioej3;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView tvresul;
Button btnrestar,btnsumar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvresul=(TextView) findViewById(R.id.tvresul);
btnrestar=(Button) findViewById(R.id.btnrestar);
btnsumar=(Button) findViewById(R.id.btnsumar);
SharedPreferences preferences=getSharedPreferences("numeros", Context.MODE_PRIVATE);
String v=String.valueOf(preferences.getInt("acumu",0));
tvresul.setText(v);
}
public void onclick(View view){
switch (view.getId()){
case R.id.btnsumar:
sumar();
break;
case R.id.btnrestar:
restar();
break;
case R.id.btnsalir:
salir();
break;
}
}
private void restar() {
int res=Integer.parseInt(tvresul.getText().toString());
res--;
tvresul.setText(String.valueOf(res));
SharedPreferences preferences=getSharedPreferences("numeros", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=preferences.edit();
editor.putInt("acumu",res);
editor.commit();
}
private void sumar(){
int sum=Integer.parseInt(tvresul.getText().toString());
sum++;
tvresul.setText(String.valueOf(sum));
SharedPreferences preferences=getSharedPreferences("numeros", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=preferences.edit();
editor.putInt("acumu",sum);
editor.commit();
}
private void salir(){
finish();
}
}
Comentarios
Publicar un comentario