How to store information when leaving an application and recover in next use?

Asked

Viewed 1,201 times

4

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

int t = 0;

Let’s say that during the use of the application, the user did some operation that added + 5 in this variable.

How do I stop when the user closes the application, the value continue to be 5 in the next use, instead of going back to 0?

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

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);

    }

}
  • I lightly edited your question to make it easier for other users to find it. Make sure that’s what you want to know. If you prefer, you can [Dit] the question and leave it better, or even reverse my edition if it has not turned out good.

  • Thank you friend, I am beginner in the forum and still do not have much experience ...

2 answers

7

There are several ways to store application data on Android.

These are the most common:

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

  • Shared preferences: store data in keys => values;

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

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


Internal storage:

It’s basically a file recording:

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

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


Shared preferences:

Take 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.

  • Yes, your answer is perfect but mine is giving an error even when the user puts the information and closes the app, and then opens again is not appearing the value there continues again at 0 instead of staying 5.

  • And actually I don’t want a string I want an int.

  • Then you would have to see your code, be careful not to write the variable after recovering. The type you can change at will, was just an example. In the second example, putBoolean could be putFloat, for example putInt

  • I posted my code down there

  • But there’s nothing in your code that I put in the answer. Well, I need to go out for an appointment, but tonight I get a better look. Try to update your code with the answer data and do some tests.

  • Beauty worth I’ll test here

Show 1 more comment

3


I recommend you use Sharedpreferences for being simple for your case(recording of an integer), which:

  • Stores preferences in files;
  • By default, they are shared between the components of your application, but not visible to other applications;
  • Preferences are to save 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 as follows:

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);

    }

}
  • My friend, your code is not picking up is giving Unfortunately ...

  • @Gutie can be some mistake in your layout... because for me and for many people does not present any error.

  • @Gutie will edit my answer just a moment...

  • @Gutie edited look again in the part "In the case of your code you can do as follows:"

  • Our thanks again bro kkk

Browser other questions tagged

You are not signed in. Login or sign up in order to post.