How to save user preferences?

Asked

Viewed 225 times

0

I have a code on android that runs an alarm, only I have to register and then check some values, for example day of the week, and has an option called mode, which boils down in "Vibrate" and "Play".

Pieces of code:

    public class Alarme_Receiver extends BroadcastReceiver {
     AlarmManager alarmManager;
     private PendingIntent pendingIntent;
     private AudioManager myAudioManager;

     @Override
     public void onReceive(Context context, Intent intent) {
      // For our recurring task, we'll just display a message
      myAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);

      if (Modo.valor == "Vibrar") {
       myAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
       Toast.makeText(context, "Setando modo Vibracal", Toast.LENGTH_SHORT).show();
      } else {
       if (Modo.valor == "Tocar") {
        myAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
        Toast.makeText(context, "Setando modo normal", Toast.LENGTH_SHORT).show();

       } else {
        Toast.makeText(context, "Erro " + Modo.valor, Toast.LENGTH_SHORT).show();
       }

      }

      if (alarmManager != null) {
       alarmManager.cancel(pendingIntent);
      }

     }
    }



    final Calendar c = Calendar.getInstance();
    int hour = tmp.getHour();
    int minute = tmp.getMinute();

    c.set(Calendar.HOUR_OF_DAY, hour);
    c.set(Calendar.MINUTE, minute);
    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MILLISECOND, 0);


    String ho = String.valueOf(hour);
    String mi = String.valueOf(minute);


    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);


    Intent intent = new Intent(cadastro.this, Alarme_Receiver.class);
    final int _id = (int) System.currentTimeMillis();
    PendingIntent appIntent = PendingIntent.getBroadcast(cadastro.this, _id, intent, PendingIntent.FLAG_ONE_SHOT);

    alarmManager.setExact(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), appIntent);

    Toast.makeText(getApplicationContext(), "Alarme setado para as " + ho + "h e " + mi + " minutos" + Modo.valor, Toast.LENGTH_LONG).show();

    kill_activity();
    }
  • 1

    What would be your question? do you already save something in your application? Would you like to know how to save? What would you like to save exclusively?

  • so it’s already saving the right alarm time, only I want to save the mode and the day of the week that the user type, only every time the user clicks the alarm button will have to accept new values.

  • How are you saving? Sharedprefrences? or even Sqlite? could edit your question and put the code you use to save?

  • I am using neither an alarm and scheduled by Alarm Manager I want to know how to save other information that and the question

1 answer

3


For this (because it is little information) I suggest the SharedPreferences.

For example, I created an object called User to facilitate data manipulation!

Here is an example of implementation:

 /**
     * Constantes utilizadas para salvar / resgatar os dados
     */
    private String USER = "#USER";
    private String DIA_SEMANA = "#diaSemana";
    private String TIPO = "#tipo";

    /**
     * Coleta os dados de SharedPreferences e retorna no objeto
     * @param mContext
     * @return User
     */

    public User getUser(final Context mContext){
        if(null == mContext) return null;
        //Cria uma instancia do SharedPreferences
        final SharedPreferences prefs = mContext.getSharedPreferences(USER, Context.MODE_PRIVATE);
        // se for nulo, n˜ao temos mais o que fazer, e retornamos nulo!
        if(null == prefs) return null;

        /**
         *  Cria uma nova instacia e coleta os valores!
         *  Para carregar um valor passamos o nome da Propriedade e um valor padrão.
         *  Se não haver dados para esta propriedade, ele irá retornar o valor padão
         */

        final User user = new User();
        user.setDiaSemana(prefs.getInt(DIA_SEMANA, 0));
        user.setTipo(prefs.getInt(TIPO, 0));
        return user;
    }

    /**
     * Grava as informações do objeto em um SharedPreferences.
     * @param user
     * @param mContext
     */
    public void setUser(final User user, final Context mContext){
        if(null == user) return;
        //Cria uma instancia do SharedPreferences
        SharedPreferences prefs = mContext.getSharedPreferences(USER, Context.MODE_PRIVATE);
        // Criamos um instancia do editor, para salvamos os dados
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt(DIA_SEMANA, user.getDiaSemana());
        editor.putInt(TIPO, user.getTipo());
        // Para que as informações sejam atualizadas
        editor.apply();
    }

Class User:

/**
 * Objeto que encapsula as informações que serão armazenadas
 */
public static class User{
    /**
     * Propriedades do Objeto
     */
    private Integer diaSemana;
    private Integer tipo;


    /**
     * Contrutor que carrega as informações
     */
    public User(final Integer  diaSemana, final Integer tipo ){
        this.diaSemana = diaSemana;
        this.tipo = tipo;
    }

    /**
     * Construtor padrão
     */
    public User(){ }

    public Integer getDiaSemana() {
        return diaSemana;
    }

    public void setDiaSemana(Integer diaSemana) {
        this.diaSemana = diaSemana;
    }

    public Integer getTipo() {
        return tipo;
    }

    public void setTipo(Integer tipo) {
        this.tipo = tipo;
    }
}
  • sorry the delay obg for the help.

Browser other questions tagged

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