如何在Android Kotlin中将HashMap保存到SharedPreferences?
此示例演示如何在Android Kotlin中将HashMap保存到SharedPreferences。
步骤1 − 在Android Studio中创建一个新项目,转到文件?新建项目,并填写所有必需的详细信息以创建新项目。
步骤2 − 将以下代码添加到res/layout/activity_main.xml。
示例
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/rlMain" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="16dp" android:orientation="vertical"> <EditText android:id="@+id/etName" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Name" android:inputType="text" /> <EditText android:id="@+id/etAge" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Age" android:inputType="number" /> <EditText android:id="@+id/etGame" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Favourite game" android:inputType="text" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:onClick="saveLocal" android:text="save local" /> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:textColor="@android:color/background_dark" android:textSize="24sp" android:textStyle="bold|italic" /> </LinearLayout>
步骤3 − 将以下代码添加到src/MainActivity.kt
示例
import android.content.Context import android.content.SharedPreferences import android.os.Bundle import android.view.View import android.widget.EditText import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import org.json.JSONObject import java.util.* import kotlin.collections.HashMap class MainActivity : AppCompatActivity() { private val mapKey = "map" lateinit var etName: EditText lateinit var etAge: EditText lateinit var etGame: EditText lateinit var textView: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" textView = findViewById(R.id.textView) etName = findViewById(R.id.etName) etAge = findViewById(R.id.etAge) etGame = findViewById(R.id.etGame) val outputMap: Map<String, Any> = loadMap() if (outputMap.containsKey("name")) etName.setText(Objects.requireNonNull(outputMap["name"]).toString()) if (outputMap.containsKey("age")) etAge.setText(Objects.requireNonNull(outputMap["age"]).toString()) if (outputMap.containsKey("game")) etGame.setText(Objects.requireNonNull(outputMap["game"]).toString()) } private fun loadMap(): Map<String, Any> { val outputMap: Map<String, Any> = HashMap() val pSharedPref = applicationContext.getSharedPreferences( "MyVariables", Context.MODE_PRIVATE ) if (pSharedPref != null) { val jsonString = pSharedPref.getString(mapKey, JSONObject().toString()) val jsonObject = JSONObject(jsonString) val keysItr = jsonObject.keys() while (keysItr.hasNext()) { val key = keysItr.next() outputMap[key] } } return outputMap } fun saveLocal(view: View) { val name = etName.text.toString().trim() val age = etAge.text.toString().trim() val game = etGame.text.toString().trim() when { name.isEmpty() -> { etName.error = "*required" etName.requestFocus() } age.isEmpty() -> { etAge.error = "*required" etAge.requestFocus() } game.isEmpty() -> { etGame.error = "*required" etGame.requestFocus() } else -> { val inputMap: MutableMap<String, Any> = HashMap() inputMap["name"] = name inputMap["age"] = age inputMap["game"] = game saveMap(inputMap) Toast.makeText(applicationContext, "Saved Locally!", Toast.LENGTH_SHORT).show() textView.text = inputMap.toString() } } } private fun saveMap(inputMap: MutableMap<String, Any>) { val sharedPreferences: SharedPreferences = applicationContext.getSharedPreferences( "MyVariables", Context.MODE_PRIVATE ) val jsonObject = JSONObject(inputMap) val jsonString = jsonObject.toString() val editor: SharedPreferences.Editor = sharedPreferences.edit() editor.remove(mapKey).apply() editor.putString(mapKey, jsonString) editor.commit() } }
步骤4 − 将以下代码添加到androidManifest.xml
示例
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.myapplication"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
让我们尝试运行您的应用程序。我假设您已将您的实际Android移动设备连接到您的计算机。要从Android Studio运行应用程序,请打开您项目的某个活动文件,然后单击工具栏中的运行图标 。选择您的移动设备作为选项,然后检查您的移动设备,它将显示您的默认屏幕。
广告