How do I store information when I exit an application and recover on next use?

4

I'd like to know how to store information, such as this variable:

int t = 0;

Let's say that while using the application, the user did some operation that added + 5 to this variable.

How do I when the user closes the application, the value will remain 5 in the next use, instead of returning to 0?

I want to store the floats gf and mf in a database.

My code:

package com.gustavo.sample;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    Button send;
    TextView say;
    EditText num;
    CheckBox g;
    CheckBox m;
    float gf = 0;
    float mf = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bacon();

        send.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                String counter = num.getText().toString();
                if (counter.equals("")) {
                    Toast.makeText(getApplicationContext(),
                            "Digite um valor numerico", Toast.LENGTH_SHORT)
                            .show();

                } else {
                    float counterAsFloat = Float.parseFloat(counter);
                    if (g.isChecked() && m.isChecked()) {
                        Toast.makeText(getApplicationContext(),
                                "Selecione apenas um checkbox",
                                Toast.LENGTH_SHORT).show();

                    } else if (m.isChecked()) {
                        mf = mf + counterAsFloat;
                        say.setText("Math " + Float.toString(mf));
                    } else if (g.isChecked()) {
                        gf = gf + counterAsFloat;
                        say.setText("Geo " + Float.toString(gf));
                    } else
                        Toast.makeText(getApplicationContext(),
                                "Selecione um checkbox", Toast.LENGTH_SHORT)
                                .show();
                }
            }
        });
    }


    private void bacon() {
        g = (CheckBox) findViewById(R.id.checkBox1);
        m = (CheckBox) findViewById(R.id.checkBox2);
        send = (Button) findViewById(R.id.button1);
        say = (TextView) findViewById(R.id.textView1);
        num = (EditText) findViewById(R.id.editText1);

    }

}
    
asked by anonymous 01.10.2014 / 20:23

2 answers

3

I recommend using SharedPreferences because it is simple for you (recording an integer), which:

  
    
  • Stores preferences in files;
  •     
  • By default, they are shared between the components of your application, but are not visible to other applications;
  •     
  • Preferences are saved in the form of key and value pairs.
  •     
    import android.app.Activity;
    import android.content.Context;
    import android.content.SharedPreferences;
    import android.os.Bundle;

    public class MainActivity extends Activity {

        private int t = 0;
        private SharedPreferences save;
        private SharedPreferences.Editor editor;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            save = getSharedPreferences("save",
                    Context.MODE_PRIVATE);
            t = save.getInt("valor", 0);//recupera o valor armazenado na chave "valor" e default 0
        }
        @Override
        protected void onStop() {
            super.onStop();
            editor = save.edit();
            editor.putInt("valor", t);//seta o par de chave("valor") e valor(t)
            editor.commit();//grava a preferencia
        }

    }

In the case of your code you can do this:

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    Button send;
    TextView say;
    EditText num;
    CheckBox g;
    CheckBox m;
    float gf = 0;
    float mf = 0;
    private SharedPreferences save;
    private SharedPreferences.Editor editor;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bacon();
        save = getSharedPreferences("save",
                Context.MODE_PRIVATE);
        gf = save.getFloat("valorGeo", 0);//recupera o valor armazenado na chave "valorGeo" e default 0
        mf = save.getFloat("valorMath", 0);//recupera o valor armazenado na chave "valorMath" e default 0
        send.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                String counter = num.getText().toString();
                if (counter.equals("")) {
                    Toast.makeText(getApplicationContext(),
                            "Digite um valor numerico", Toast.LENGTH_SHORT)
                            .show();

                } else {
                    float counterAsFloat = Float.parseFloat(counter);
                    if (g.isChecked() && m.isChecked()) {
                        Toast.makeText(getApplicationContext(),
                                "Selecione apenas um checkbox",
                                Toast.LENGTH_SHORT).show();

                    } else if (m.isChecked()) {
                        mf = mf + counterAsFloat;
                        say.setText("Math " + Float.toString(mf));
                    } else if (g.isChecked()) {
                        gf = gf + counterAsFloat;
                        say.setText("Geo " + Float.toString(gf));
                    } else
                        Toast.makeText(getApplicationContext(),
                                "Selecione um checkbox", Toast.LENGTH_SHORT)
                                .show();
                }
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        editor = save.edit();
        editor.putFloat("valorGeo", gf);//seta o par de chave("valorGeo") e valor(gf)
        editor.putFloat("valorMath", mf);//seta o par de chave("valorMath") e valor(mf)
        editor.commit();//grava a preferencia
    }

    private void bacon() {
        g = (CheckBox) findViewById(R.id.checkBox1);
        m = (CheckBox) findViewById(R.id.checkBox2);
        send = (Button) findViewById(R.id.button1);
        say = (TextView) findViewById(R.id.textView1);
        num = (EditText) findViewById(R.id.editText1);

    }

}
    
01.10.2014 / 20:51
7

There are several ways to store app data on Android.

Here are the most common:

  • Internal storage: to store private data on the device;

  • Shared Preferences: Save Data to Keys = > values;

  • Database: to store a larger and more "processable" amount of information;

  • Web: If you want the data stored on your server, not the user


Internal storage:

It's basically a write to file:

String ARQUIVO = "NomeDoMeuArquivo";
String string = "Batatinhas";

FileOutputStream fos = openFileOutput( ARQUIVO, Context.MODE_PRIVATE );
fos.write(string.getBytes());
fos.close();


Shared preferences:

See an example:

public class Teste extends Activity {
    public static final String PREFS_NAME = "PreferenciasNOME_DO_APP";

    @Override
    protected void onCreate(Bundle state){
       super.onCreate(state);
       . . .

       // Recuperando os dados no início da aplicação
       SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
       boolean minhaVariavel = settings.getBoolean("minhaVariavel", false);
    }

    @Override
    protected void onStop(){
       super.onStop();

      // Gravando dados na saída
      SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
      SharedPreferences.Editor editor = settings.edit();
      editor.putBoolean("minhaVariavel", minhaVariavel );
      editor.commit();
    }
}


Click here to visit an article with an interesting translation of the official Android documentation.

    
01.10.2014 / 20:29