如何执行一次保存时间功能?

时间:2016-03-09 03:55:09

标签: android sharedpreferences

现在代码运行,以便将时间保存在共享首选项中,以便它可以加载保存的特定时间。但是,当您离开活动并返回活动时,时间将重置为当前时间,并且不会加载已保存的时间。 这是我的代码(这部分在我的oncreate上):

SharedPreferences sharedPreferences2 = getSharedPreferences("MyData2", Context.MODE_PRIVATE);
String clockedout = sharedPreferences2.getString("clockedout",DEFAULT);

if(clockedout.equals(DEFAULT)) {
    Toast.makeText(this, "No hours logged today.",Toast.LENGTH_LONG).show();
}
else {
    SimpleDateFormat format= new SimpleDateFormat("hh:mm a", Locale.US);
    format.setLenient(false);
}

//Here is the button that is saving the time:
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
    if(b) {
        Calendar c = Calendar.getInstance();
        System.out.println(c.getTime());
        SimpleDateFormat df = new SimpleDateFormat("hh:mm a");                
        String formattedDate = df.format(c.getTime());
        TextView clockedin = (TextView)findViewById(R.id.clockedin);
        clockedin.setText(formattedDate);

        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean("toggleButton", tb.isChecked());
        editor.commit();

        SharedPreferences sharedPreferences2=getSharedPreferences("MyData", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor1= sharedPreferences2.edit();
        editor1.putString("clockedin", formattedDate);
        editor1.commit();
    } else {
        Calendar c = Calendar.getInstance();
        System.out.println(c.getTime());
        SimpleDateFormat df = new SimpleDateFormat("hh:mm a");
        String formattedDate = df.format(c.getTime());
        TextView clockedout = (TextView)findViewById(R.id.clockedout);
        clockedout.setText(formattedDate);

        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean("toggleButton", false);
        editor.commit();

        SharedPreferences sharedPreferences2=getSharedPreferences("MyData2", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor1= sharedPreferences2.edit();
        editor1.putString("clockedout", clockedout.getText().toString());
        editor1.commit();
    }
}

2 个答案:

答案 0 :(得分:0)

为什么会这样:

每次状态变化时都会调用

onCheckedChanged

您只需使用 onClickListener 而不是 onCheckedChanged

说一个例子:

   CheckBox checkBox = findViewById(R.id.checkBox);

    checkBox.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            if(checkBox.isChecked()){

                Calendar c = Calendar.getInstance();
                System.out.println(c.getTime());
                SimpleDateFormat df = new SimpleDateFormat("hh:mm a");
                String formattedDate = df.format(c.getTime());
                TextView clockedin = (TextView)findViewById(R.id.clockedin);
                clockedin.setText(formattedDate);

                SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putBoolean("toggleButton", tb.isChecked());
                editor.commit();

                SharedPreferences sharedPreferences2=getSharedPreferences("MyData", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor1= sharedPreferences2.edit();
                editor1.putString("clockedin", formattedDate);
                editor1.commit();
            } else {
                Calendar c = Calendar.getInstance();
                System.out.println(c.getTime());
                SimpleDateFormat df = new SimpleDateFormat("hh:mm a");
                String formattedDate = df.format(c.getTime());
                TextView clockedout = (TextView)findViewById(R.id.clockedout);
                clockedout.setText(formattedDate);

                SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putBoolean("toggleButton", false);
                editor.commit();

                SharedPreferences sharedPreferences2=getSharedPreferences("MyData2", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor1= sharedPreferences2.edit();
                editor1.putString("clockedout", clockedout.getText().toString());
                editor1.commit();
            }
         }
    });

希望这会对你有所帮助

答案 1 :(得分:0)

这就是你想要的,只需复制并粘贴即可。

activity_main.xml中

   <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@android:color/white"
xmlns:android="http://schemas.android.com/apk/res/android">

   <Switch
   android:layout_gravity="center"
   android:id="@+id/switch_button"
   android:textSize="30dp"
   android:layout_width="match_parent"
   android:layout_height="wrap_content" />

<TextView
    android:id="@+id/clockedin"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColor="@android:color/black"
    android:layout_marginTop="20dp"
    android:text="clocked_in : "
    android:textSize="30dp"
    />

<TextView
    android:id="@+id/last_clockedin"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColor="@android:color/black"
    android:layout_marginTop="20dp"
    android:text="last_clocked_in : shows on restart app"
    android:textSize="30dp"
    />

<TextView
    android:id="@+id/clockedout"
    android:layout_width="match_parent"
    android:textColor="@android:color/black"
    android:layout_height="wrap_content"
    android:text="clocked_out : "
    android:layout_marginTop="20dp"
    android:textSize="30dp"
    />
</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener
 {

String DEFAULT = "def";
Switch switch_btn;
TextView clocked_in,clocked_out,last_clockedin;
SharedPreferences sharedPreferences2;
Spinner spinner;
  static  String fileName = "my_flags";

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

    spinner = new Spinner(this);
    spinner.setGravity(Gravity.RIGHT);

    switch_btn = (Switch) findViewById(R.id.switch_button);
    clocked_in = (TextView) findViewById(R.id.clockedin);
    clocked_out = (TextView) findViewById(R.id.clockedout);
    last_clockedin = (TextView) findViewById(R.id.last_clockedin);

    switch_btn.setOnCheckedChangeListener(this);


        if(readFromPrefrences(this,"clockedout",DEFAULT).equals(DEFAULT))   {
        Toast.makeText(this, "No hours logged today.", Toast.LENGTH_LONG).show();
    }
    else {
       clocked_out.setText("last clocked out : "+readFromPrefrences(this,"clockedout",DEFAULT));
    }

    if(readFromPrefrences(this,"clockedin",DEFAULT).equals(DEFAULT)) {
        Toast.makeText(this, "No last logged in", Toast.LENGTH_LONG).show();
    }
    else {
        last_clockedin.setText("last clocked in : "+readFromPrefrences(this,"clockedin",DEFAULT));
    }

}


@Override
public void onCheckedChanged(CompoundButton buttonView, boolean b) {
    if(buttonView.isChecked()) {
        Calendar c = Calendar.getInstance();
        SimpleDateFormat df = new SimpleDateFormat("hh:mm a");
        String formattedDate = df.format(c.getTime());
        clocked_in.setText("clock_in : " + formattedDate);
        saveToPrefrences(this, "clockedin", formattedDate);


    } else {
        Calendar c = Calendar.getInstance();
        System.out.println(c.getTime());
        SimpleDateFormat df = new SimpleDateFormat("hh:mm a");
        String formattedDate = df.format(c.getTime());

        saveToPrefrences(this, "clockedout", formattedDate);
        if (!readFromPrefrences(this,"clockedout",DEFAULT).equals(DEFAULT))
        clocked_out.setText(readFromPrefrences(this,"clockedout",DEFAULT));


    }


}

    public static void saveToPrefrences(Context context, String key, String value)
{
        SharedPreferences sharedPreferences = context.getSharedPreferences(fileName ,Context.MODE_PRIVATE);
    SharedPreferences.Editor edit =  sharedPreferences.edit();
    edit.putString(key,value);
    edit.apply();
}

    public static String readFromPrefrences(Context context,String key, String default_value)
    {
        SharedPreferences sharedPreferences =  context.getSharedPreferences(fileName,Context.MODE_PRIVATE);
    return sharedPreferences.getString(key,default_value);
    }


}