gpt4 book ai didi

java - 共享首选项未保存或循环不起作用

转载 作者:行者123 更新时间:2023-12-02 12:14:30 24 4
gpt4 key购买 nike

非常感谢一些帮助。我有两项 Activity 。 MainActivity 和 SharedPrefs。我希望打开该应用程序以查看是否有一些已保存的首选项。如果不是,它必须转到另一个要求一些细节的 Activity 。然后,按下提交按钮后,它必须保存共享首选项并转到 MainActivity。但事实并非如此,它只是跳回 SharedPrefs Activity 。现在我不知道我的共享首选项是否没有被保存(我认为“editor.commit”可以完成这项工作),或者我的循环是否有问题。我确实改变了我的循环,它以相反的方式工作,但我可能会弄错整个事情,因为我对 Android 和 Java 还很陌生。就像我说的,一些帮助将不胜感激。

这是我的 MainActivity 和我的循环:

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
boolean check = sharedPreferences.getBoolean("Check",false);
if(!check){
//Intent intent;
Intent SharedPrefsIntent = new Intent(MainActivity.this, SharedPrefs.class);
startActivity(SharedPrefsIntent); }
else {
setContentView(R.layout.activity_main);
TextView brands = (TextView) findViewById(R.id.brands);
brands.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent brandsIntent = new Intent(MainActivity.this, brands.class);
startActivity(brandsIntent);
}
});
}
}

这是我的 SharedPrefs,我尝试在其中获取一些信息以添加到共享首选项中:

public class SharedPrefs extends AppCompatActivity {
//public static Context context;
EditText ed1,ed2,ed3;
Button b1;

public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
public static final String Phone = "phoneKey";
public static final String Email = "emailKey";

SharedPreferences sharedpreferences;

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

ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
ed3=(EditText)findViewById(R.id.editText3);

b1=(Button)findViewById(R.id.button);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String n = ed1.getText().toString();
String ph = ed2.getText().toString();
String e = ed3.getText().toString();

SharedPreferences.Editor editor = sharedpreferences.edit();

editor.putString(Name, n);
editor.putString(Phone, ph);
editor.putString(Email, e);
editor.commit();

Toast.makeText(SharedPrefs.this,"Thanks",Toast.LENGTH_LONG).show();
Intent BackToMainIntent = new Intent(SharedPrefs.this, MainActivity.class);
startActivity(BackToMainIntent);
}
});
}

最佳答案

请在设置所需值后将“检查”键值添加到 SharedPreferences,因为它在 MainActivity 上始终返回 false。

您也可以使用 .apply() 代替 .commit()。

关于java - 共享首选项未保存或循环不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46286429/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com