如何保存最后一位用户的历史记录?

时间:2014-04-23 11:18:06

标签: android sharedpreferences

我的应用中的用户可以选择活动B中的某些日期,最后五个选择应该保存。 问题是每个用户可以有不同的故事计算!事实上,我最后一个用户的应用计算是记住的,但即使对于应该有日期空字段的新用户也是如此。

这是我的第一个活动:

package com.example.dnitygodnia;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;


public class Ekran1 extends Activity {


    EditText editText;
    Button dalej;
    SharedPreferences preferences;

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

        preferences = getSharedPreferences("Dni Tygodnia", Activity.MODE_PRIVATE);
        editText = (EditText) findViewById(R.id.editTextUserName);

        String LastUser = preferences.getString("LastUser", "");
        editText.setText(LastUser);
        //set listeners
        editText.addTextChangedListener(textWatcher);

        //run once to disable if empty
        checkFieldsForEmptyValues();

    }

     protected TextWatcher textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3)
           {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
                checkFieldsForEmptyValues();
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        };

    protected void checkFieldsForEmptyValues() {

        dalej = (Button) findViewById(R.id.btnDalej);
        String s = editText.getText().toString();

        if (s.equals(""))
        {
            dalej.setEnabled(false);
        }
        else if (s.matches("[A-Za-z\\d]*")){
            dalej.setEnabled(true);

        }
        else
            dalej.setEnabled(false);
    }   

    public void onClick (View v){
        SharedPreferences.Editor preferencesEditor = preferences.edit();
        String wyslij = editText.getText().toString();
        Intent intent = new Intent (this, TestowyEkran.class);
        intent.putExtra("Nazwa Uzytkownika", wyslij);
        preferencesEditor.putString("LastUser", wyslij);
        preferencesEditor.commit();
        startActivity (intent);


    }


}

这是第二项活动:

package com.example.dnitygodnia;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;


public class TestowyEkran extends Activity implements OnClickListener , TextWatcher {

    String userName;
    TextView txt;
    TextView[] calData;
    Button button;
    Button backButton;
    DatePicker picker;
    Boolean backPressed = false;
    SharedPreferences preferences;

    Queue<String> strings;

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

        setContentView(R.layout.activity_testowy_ekran);

        preferences = getSharedPreferences("Dni Tygodnia", Activity.MODE_PRIVATE);
         userName = getIntent().getExtras().getString("LOGIN");
         txt = (TextView) findViewById(R.id.textViewLogin1);
         backButton = (Button) findViewById(R.id.buttonBack);
         button = (Button) findViewById(R.id.buttonDayOfTheWeek);
         button.setOnClickListener(this);
         picker = (DatePicker) findViewById(R.id.datePicker1);

//       Bundle b = getIntent().getExtras();
//       String odbior = b.getString("Nazwa Uzytkownika");  
//       txt.setText(odbior);


         String LastUser = preferences.getString("LastUser", "");
         txt.setText(LastUser);

         backButton.setOnClickListener(this);

         strings = new LinkedList<String>();

         calData = new TextView[5];

         calData[0] = (TextView) findViewById(R.id.textView1);
         calData[1] = (TextView) findViewById(R.id.textView2);
         calData[2] = (TextView) findViewById(R.id.textView3);
         calData[3] = (TextView) findViewById(R.id.textView4);
         calData[4] = (TextView) findViewById(R.id.textView5);

         if ( strings != null )
             updateFields();
    }

    @Override
    public void afterTextChanged(Editable arg0) {
        // TODO Auto-generated method stub

    }
    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
            int arg3) {
        // TODO Auto-generated method stub

    }
    @Override
    public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        // TODO Auto-generated method stub

    }
    @Override
    public void onClick(View arg0) {

            if ( arg0.getId() == R.id.buttonBack )
            {
                backPressed = true;
                finish();
            }
            else
            {

              SimpleDateFormat simpledateformat = new SimpleDateFormat("EEEE");

              Date date = new Date(picker.getYear(),picker.getMonth(), picker.getDayOfMonth()-1);
              String a = Integer.toString(picker.getYear());
              String b = Integer.toString(picker.getMonth());
              String c = Integer.toString(picker.getDayOfMonth());
              String dayOfWeek = simpledateformat.format(date);

              String fin = String.format("%s-%s-%s : %s" , a,b,c,dayOfWeek);


              if (   strings.peek() != null && strings.peek().equals(fin) )
                  return;

              strings.add(fin);
              updateFields();

            }
    }

    @Override
    public void onBackPressed() {

    }

    private void updateFields()
    {
        if ( strings == null || strings.size() == 0 )
            return;

        if ( strings.size() == 6  )
        {
            strings.remove();
        }

        int i = 0;

        for ( String s : strings)
        {
            calData[i].setText(s);
            i++;
        }

        for ( TextView v : calData )
            v.setTextColor(-16777216);

        calData[i-1].setTextColor(-16711936);
    }

    @SuppressLint("NewApi")
    @Override
    protected void onPause() {

        super.onPause();

        SharedPreferences pref = getSharedPreferences("shared",0);
        SharedPreferences.Editor ed = pref.edit();

        ed.putStringSet(userName, new HashSet<String>(strings));
        if ( !backPressed )
        ed.putBoolean("secondscreen", true);
        ed.putString("user", userName);

        ed.commit();

    }

    @SuppressLint("NewApi")
    @Override
    protected void onResume() {

        SharedPreferences pref = getSharedPreferences("shared",0);
        Set<String> hash = pref.getStringSet(userName, null);

        if ( hash != null && hash.size() > 0 )
        {
            strings = new LinkedList<String>(hash);
            updateFields();
        }


        super.onResume();
    }





    @SuppressLint("NewApi")
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //outState.putStringArray(userName, (String[])strings.toArray());
        super.onSaveInstanceState(outState);
    }

    @SuppressLint("NewApi")
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {

        String[] arr = savedInstanceState.getStringArray(userName);
        if ( arr != null && arr.length > 0 )
        {
        strings = new LinkedList<String>(Arrays.asList(arr));
         updateFields();
        }

        super.onRestoreInstanceState(savedInstanceState);
    }

}

这是活动1的xml:

<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=".Ekran1" >

    <Button
        android:id="@+id/btnDalej"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="102dp"
        android:layout_marginRight="123dp"
        android:text="@string/dalej" 
        android:onClick="onClick"/>

    <TextView
        android:id="@+id/textViewUserName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editTextUserName"
        android:layout_alignParentTop="true"
        android:text="@string/wpisz_nazw_u_ytkownika"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/editTextUserName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textViewUserName"
        android:layout_marginLeft="47dp"
        android:layout_marginTop="52dp"
        android:layout_toLeftOf="@+id/btnDalej"
        android:ems="10"
        android:inputType="textPersonName" >

        <requestFocus />
    </EditText>

</RelativeLayout>

这是活动2的xml:

<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=".TestowyEkran" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="174dp"
        android:text="TextView1" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_alignTop="@+id/textView1"
        android:layout_marginTop="17dp"
        android:text="TextView2" />

    <Button
        android:id="@+id/buttonDayOfTheWeek"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/textView1"
        android:layout_alignParentRight="true"
        android:layout_marginRight="46dp"
        android:text="Day of the week" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView2"
        android:layout_below="@+id/textView2"
        android:text="TextView3" />

    <Button
        android:id="@+id/buttonBack"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="34dp"
        android:layout_marginRight="18dp"
        android:text="back" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView3"
        android:layout_below="@+id/textView3"
        android:text="TextView4" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView4"
        android:layout_below="@+id/textView4"
        android:text="TextView5" />

    <DatePicker
        android:id="@+id/datePicker1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/buttonDayOfTheWeek"
        android:layout_marginTop="51dp"
        android:calendarViewShown="false" />

    <TextView
        android:id="@+id/textViewLogin1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_alignParentTop="true"
        android:layout_marginTop="16dp"
        android:text="TextView" />

</RelativeLayout>

1 个答案:

答案 0 :(得分:2)

替换

 getSharedPreferences("Dni Tygodnia", Activity.MODE_PRIVATE);

 getSharedPreferences("Dni Tygodnia", MODE_PRIVATE);