(Kotlin)我如何从另一个活动中的共享首选项获取数据

问题描述 投票:0回答:2

我有一个设置活动,我想在其他屏幕上使用这些设置我正在开发一个应用程序来发送手机余额,通常进行这些销售的人必须在他的销售电话上输入一系列代码,我想要的是省去了供应商的烦恼并修复了代码,但每个供应商都有一个唯一的引脚,在我的应用程序中应该在设置中仅输入一次(您的供应商引脚),然后不用担心任何事情

This is the settings Activity u have to enter your pin in that EditText and then the app have to remember the pin at each transaction u do


override fun onCreatelsavedInstanceState: Bundle?) { 
        
        super.onCreate(savedInstance5tate) 
        
        setContentView(R. Layout.activity_main) 
        
        
        loadData()
        
        
        savebutton. setonClicklistener (){saveData() }
      
    }
                                           
     
    private fun loadData (){ 
            
            val sharePref = getPreferences(Context.MODE_PRIVATE) 
            
            val mydata = sharePref.getString( key: "mydata", defValue: "") 
            
            dataEditText.setText (dato)
    }
            
    private fun saveData(){ 
            
         sharePref = getPreferences (Context.MODE_PRIVATE)
            
         with(sharePref.edit()){
           putString("pin", dataEditText.text.tostring())
           commit() ^with
         }
    }
android-studio kotlin sharedpreferences
2个回答
1
投票
  • 您可以使用
    getSharedPreferences
  • 因为
    getPreferences
    :该活动仅使用一个共享首选项文件。
  • getSharedPreferences
    :如果您需要使用第一个参数指定的名称标识多个共享首选项文件,请使用此选项。您可以从应用程序中的任何上下文调用它。
val sharedPref = getSharedPreferences(
    getString(R.string.preference_file_key),
    Context.MODE_PRIVATE
)

0
投票

1.创建班级

class SharedPreference(val context: Context) { 私有 val PREFS_NAME = "kotlincodes" val sharedPref: SharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)

fun save(KEY_NAME: String, text: String) {
    val editor: SharedPreferences.Editor = sharedPref.edit()
    editor.putString(KEY_NAME, text)
    editor!!.commit()
}

fun save(KEY_NAME: String, value: Int) {
    val editor: SharedPreferences.Editor = sharedPref.edit()
    editor.putInt(KEY_NAME, value)
    editor.commit()
}

fun save(KEY_NAME: String, status: Boolean) {
    val editor: SharedPreferences.Editor = sharedPref.edit()
    editor.putBoolean(KEY_NAME, status!!)
    editor.commit()
}

fun getValueString(KEY_NAME: String): String? {
    return sharedPref.getString(KEY_NAME, null)
}

fun getValueInt(KEY_NAME: String): Int {
    return sharedPref.getInt(KEY_NAME, 0)
}

fun getValueBoolien(KEY_NAME: String, defaultValue: Boolean): Boolean {
    return sharedPref.getBoolean(KEY_NAME, defaultValue)
}

fun clearSharedPreference() {
    val editor: SharedPreferences.Editor = sharedPref.edit()
    //sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
    editor.clear()
    editor.commit()
}

fun removeValue(KEY_NAME: String) {
    val editor: SharedPreferences.Editor = sharedPref.edit()
    editor.remove(KEY_NAME)
    editor.commit()
}

}

© www.soinside.com 2019 - 2024. All rights reserved.