Save a value on Android

2

I want to take the value I have in TextView , add it, save it and repeat this process every time the button is touched, but I do not understand why I can not save it.

My code:

public class MainActivity extends Activity {

    Button b1;
    TextView tv3,tv4;

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

        b1 = (Button) findViewById(R.id.b1);
        tv3=(TextView)findViewById(R.id.tv3);
        tv4=(TextView)findViewById(R.id.tv4);
        SharedPreferences preferences=getSharedPreferences("Saldo", Context.MODE_PRIVATE);
        tv4.setText(preferences.getString("Valor", ""));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
            return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void a(View view){

        int x=200;

        String valor1=tv4.getText().toString();
        int nro1=Integer.parseInt(valor1);
        int sumar=nro1 + x;
        String resultado=String.valueOf(sumar);
        tv4.setText(resultado);

        SharedPreferences preferences=getSharedPreferences("Saldo", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor=preferences.edit();
        editor.putString("Valor", tv4.getText().toString());
        editor.commit();
    }
}
    
asked by Agustin Val 09.06.2016 в 18:14
source

3 answers

2

You have some small mistakes in the code, but do not worry, I'll try to explain them as best as possible:

It turns out that if you want the button to add and save when you press the button, you are doing it wrong, because for a button to be linked to the action, it can be done in several ways:

NOTE: if you already know the ways to link an action with a button, go to the section of SharedPreferences , just under the explanation of the buttons.

LINK A METHOD TO A BUTTON

This way you have to create a method in your code Java and from the properties of the button in the section XML of Desing , you would have to look for a property called onClick and assign there the method that you have created. You do not need to pass any View to this method as you do in the a() method

IMPLEMENT THE ONCLICKLISTENER METHOD

To do this, you have two ways:

  • In your declaration of the main class you add the following and implement the necessary codes:

    public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    
        Button b1;
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            b1 = (Button) findViewById(R.id.b1);
            // Así se enlaza el botón a el método
            b1.setOnClickListener(this);
    
        }
    
        @Override
        public void onClick(View v) {
            // Método necesario de implementar
            // Para saber que botón se pulsa en caso de tener más de uno
            switch (v.getId()){
                case R.id.b1:
                    // Añadir aquí el código que quieras que funcione cuando     se presione el botón 
                break;
            }
        }
    }
    
  • The other way, is to implement it directly to your button in the onCreate() method:

    public class MainActivity extends AppCompatActivity{
    
        Button b1;
        TextView tv3;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            b1 = (Button) findViewById(R.id.btGuardar);
            // Implementación de la ación del botón
            b1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //Acciones que quieras que realice el botón
                }
            });
        }
    }
    

Once you know this, I'll explain the SharedPreferences and understand why you fail:

SHAREDPREFERENCES

  • To get a value of SharedPreferences this code is used:

    SharedPreferences preferences = getSharedPreferences ("Balance", Context.MODE_PRIVATE); textview.setText (preferences.getString ("Value", "5"));

The first line declares the file of SharedPreferences that will be accessed. In this case it will be called Saldo . When this line is executed, on your Android device a file called Saldo will be created, which you will access whenever you declare the first line, no matter what Activity (screen) you are.

In the second line you are saying to add a value to TextView that is stored with the code name Valor and that in case the key Valor does not exist, it will be created and its initial value will be 5 .

You in your app, you have set "" , so you will NEVER get anything or add anything and you will execute the action, but the value is still "" , that is, nothing.

  • If you want to save, the following code is executed, as you have in your code:

    SharedPreferences preferences = getSharedPreferences("Saldo", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString("Valor", String.valueOf(tv3.getText()));
    editor.apply();
    

Try using apply() to save the data instead of commit() .

Now you know the reason for your error and I leave you an example code that I have made:

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    Button b1;
    TextView tv3;

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

        b1 = (Button) findViewById(R.id.btGuardar);
        tv3 = (TextView) findViewById(R.id.tvNumero);
        SharedPreferences preferences = getSharedPreferences("Saldo", Context.MODE_PRIVATE);
        tv3.setText(preferences.getString("Valor", "5"));
        b1.setOnClickListener(this);
    }


    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btGuardar:
                int x = 200;

                String valor1 = (String) tv3.getText();
                int num1 = Integer.parseInt(valor1);
                int sumar = num1 + x;
                String resultado = String.valueOf(sumar);
                tv3.setText(resultado);

                SharedPreferences preferences = getSharedPreferences("Saldo", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = preferences.edit();
                editor.putString("Valor", String.valueOf(tv3.getText()));
                editor.apply();
                break;
        }

    }
}

activity_main.xml :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.victoriavicent.myapplication.MainActivity">


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/_5"
        android:id="@+id/tvNumero"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:layout_above="@+id/btGuardar"
        android:layout_alignParentEnd="true"
        android:gravity="center"
        android:textSize="50sp"
        android:textColor="@android:color/black" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/guardar"
        android:id="@+id/btGuardar"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentEnd="true" />
</RelativeLayout>

I hope you have made everything clear, but even so, if you need anything or do not just understand something that I just explained, write me a comment and I'll solve the question.

Good luck with your app!

    
answered by 09.06.2016 / 19:16
source
0

Try to use a single instance of SharedPreferences , declare a global instance in your class just like the editor, and use that same instance to bring the information and to save it, with this you ensure that you are using the same record of SharedPreferences , sometimes even if you put the tag in your case 'Balance' to be another instance of shared preferences the values are not the same.

    
answered by 09.06.2016 в 18:38
0

The reason is that you are calling the method from the button in the layout, defining the method a(View view)

You have not defined the method call:

 <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/guardar"
        android:id="@+id/btGuardar"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentEnd="true" />

add the android property: onClick="a":

 <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/guardar"
        android:id="@+id/btGuardar"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentEnd="true" 
        android:onClick="a" />

to call the a() method from the Layout.

   public void a(View view){
...
...

If you were to call the same method by calling the method using a OnClickListener code, the method would change to:

    public void a(){
...
...
    
answered by 09.06.2016 в 19:23