我有三个活动A, B和C,其中A和B是表单,并在数据库(SQLite)中填充和保存表单数据后。我使用意图从A到B,然后从B到C,我想要的是,每次我打开我的应用程序时,我想要C作为我的主屏幕,而不再是A和B。

我想共享偏好可以解决这个问题,但我找不到一个好的例子来给我一个起点。


当前回答

共享偏好是如此容易学习,所以看看这个 关于共享偏好的简单教程

import android.os.Bundle;
import android.preference.PreferenceActivity;

    public class UserSettingActivity extends PreferenceActivity {

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

      addPreferencesFromResource(R.xml.settings);

    }
}

其他回答

在“偏好”中设置值:

// MY_PREFS_NAME - a static String variable like: 
//public static final String MY_PREFS_NAME = "MyPrefsFile";
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
 editor.putString("name", "Elena");
 editor.putInt("idName", 12);
 editor.apply();

从首选项检索数据:

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value.

更多信息:

使用共享首选项

共同的喜好

如何初始化?

// 0 - for private mode`
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); 

Editor editor = pref.edit();

如何在共享偏好中存储数据?

editor.putString("key_name", "string value"); // Storing string

OR

editor.putInt("key_name", "int value"); //Storing integer

别忘了申请:

editor.apply();

如何从共享首选项检索数据?

pref.getString("key_name", null); // getting String

pref.getInt("key_name", 0); // getting Integer

希望这对你有帮助:)

写入共享首选项

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
 editor.commit(); 

从共享首选项读取

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
        // Create object of SharedPreferences.
        SharedPreferences sharedPref = getSharedPreferences("mypref", 0);

        //now get Editor
        SharedPreferences.Editor editor = sharedPref.edit();

        //put your value
        editor.putString("name", required_Text);

        //commits your edits
        editor.commit();

       // Its used to retrieve data
       SharedPreferences sharedPref = getSharedPreferences("mypref", 0);
       String name = sharedPref.getString("name", "");

       if (name.equalsIgnoreCase("required_Text")) {
          Log.v("Matched","Required Text Matched");
          } else {
               Log.v("Not Matched","Required Text Not Matched"); 
                 }
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();