如何在此代码中应用SharedPreferences



这也是我在android和java中的第一个"合法项目"。这是一个具有附加功能的简单计数器[其中大部分功能尚未添加]。我遇到了一个问题,当用户关闭应用程序时,我无法保存计数。假设有人点击到50,然后关闭应用程序(不仅仅是退出,而是关闭整个应用程序(,然后重新打开,我希望它从50开始继续。

我知道我可以通过共享的偏好来做到这一点,但我试着自己做,也看了一些YouTube视频,但没有成功。它就是不起作用,或者应用程序崩溃。

如果有人能查看我的代码并帮助我添加所需的共享偏好代码,那将是一件令人惊叹的事情,我还计划从选项菜单中添加一个设置页面/活动,我希望在其中保持亮/暗主题切换。

package com.example.tapcounter;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Display;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
public class MainActivity extends AppCompatActivity {
private AdView mAdView ;
private int counter = 0;
TextView txt;
Button btnU,btnT,btnR;
Switch sw;
private static long back_pressed;
//Double Tap Exit
@Override
public void onBackPressed()
{
if (back_pressed + 2000 > System.currentTimeMillis()) super.onBackPressed();
else Toast.makeText(getBaseContext(), "Press once again to exit!", Toast.LENGTH_SHORT).show();
back_pressed = System.currentTimeMillis();
}

//Inflater for Menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu,menu);
return true;
}
//Menu
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch(item.getItemId()){
case R.id.menui1:
Intent aboutIntent = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(aboutIntent);
break;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(this, "AppID");
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
btnT =  findViewById(R.id.tapbtn);
btnR =  findViewById(R.id.resetbtn);
btnU =  findViewById(R.id.undobtn);
sw = findViewById(R.id.swch);
txt =  findViewById(R.id.txtv);
;

//TAP Button
btnT.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
counter ++;
txt.setText(Integer.toString(counter));

}
});

//UNDO Button
btnU.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(counter > 0) {
counter--;
txt.setText(Integer.toString(counter));
}
else{
return;
}
}
});
//RESET Button
btnR.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
counter = 0;
txt.setText(Integer.toString(counter));
}
});
//Lock Switch
sw.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(sw.isChecked()) {
btnR.setEnabled(false);
btnT.setEnabled(false);
btnU.setEnabled(false);
}
else{
btnR.setEnabled(true);
btnT.setEnabled(true);
btnU.setEnabled(true);
}
}
});
}
}

不知道xml代码是否是必要的,但现在开始吧。

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:background="@color/BG"
tools:context=".MainActivity">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/MainLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/BG"
tools:context=".MainActivity">
<Button
android:id="@+id/undobtn"
android:layout_width="103dp"
android:layout_height="70dp"
android:text="@string/undobtnS"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.051"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tapbtn"
app:layout_constraintVertical_bias="1.0" />
<Button
android:id="@+id/resetbtn"
android:layout_width="100dp"
android:layout_height="70dp"
android:text="@string/restbtnS"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tapbtn"
app:layout_constraintVertical_bias="1.0" />
<Switch
android:id="@+id/swch"
android:layout_width="102dp"
android:layout_height="70dp"
android:layout_marginTop="39dp"
android:text="@string/swchS"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.948"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tapbtn"
app:layout_constraintVertical_bias="0.748" />
<TextView
android:id="@+id/txtv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/txtvS"
android:textSize="130sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="@+id/tapbtn"
app:layout_constraintVertical_bias="0.325" />
<Button
android:id="@+id/tapbtn"
android:layout_width="415dp"
android:layout_height="450dp"
android:layout_marginTop="92dp"
android:alpha="0.1"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.gms.ads.AdView
android:id="@+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
app:adSize="SMART_BANNER"
app:adUnitId="ca-app-pub-3940256099942544/6300978111"
app:layout_constraintBottom_toTopOf="@+id/tapbtn"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</com.google.android.gms.ads.AdView>
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>

当活动生命周期的onStoponDestroy方法被调用时,您必须保存计数器值,而在onResumeonCreate方法中,您必须检索该值。

使用共享首选项保存整数值:

SharedPreferences.Editor editor =  getContext().getSharedPreferences("NAME_OF_SHARED_PREF" , MODE_PRIVATE).edit();
editor.putInt("KEY_NAME_HERE" , COUNTER_INT_VALUE_HERE);

您可以检索这样的值:

SharedPreferences prefs = getActivity().getApplicationContext().getSharedPreferences("NAME_OF_SHARED_PREF", MODE_PRIVATE);
int counter = prefs.getInt("KEY_NAME_HERE", ANY_DEFAULT_VALUE);

您可以通过这种方式创建共享首选项

public class MySharedPref {
//Shared Preferences
SharedPreferences pref;
//Editor for Shared preferences
SharedPreferences.Editor editor;
//context
Context context;
//shared pref mode
int PRIVATE_MODE=0;
//shared pref file name
public static final String PREF_NAME="MySharedPref";

public MySharedPref(Context context){
this.context=context;
pref=context.getSharedPreferences(PREF_NAME,PRIVATE_MODE);
editor=pref.edit();
}
public void changeCount(String count){
editor.putString("Count",count);
editor.commit();
}
public String getCount(){
return pref.getString("Count","0");
}
}

然后在您的MainActivity中,您可以将其用作-

MySharedPref mySharedPref; //declare it
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mySharedPref=new MySharedPref(getApplicationContext());
//other part
}
//TAP Button
btnT.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
counter ++;
mySharedPref.changeCount(Integer.toString(counter));
//other part
}
});

//UNDO Button
btnU.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(counter > 0) {
counter--;
mySharedPref.changeCount(Integer.toString(counter));
//other part
}
else{
return;
}
}
});
//RESET Button
btnR.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
counter = 0;
mySharedPref.changeCount(Integer.toString(counter));
//other part
}
});

您可以使用类似的mySharedPref.getCount()获得重新打开后保存的最后一次计数

txt.setText(mySharedPref.getCount());

希望它能帮助