Introduction
Local storage saves data directly on your device. This lets your app work even without internet.
Local storage saves data directly on your device. This lets your app work even without internet.
val sharedPref = context.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE) val editor = sharedPref.edit() editor.putString("key", "value") editor.apply() val value = sharedPref.getString("key", "default")
val sharedPref = context.getSharedPreferences("UserData", Context.MODE_PRIVATE) sharedPref.edit().putString("username", "Alice").apply()
val sharedPref = context.getSharedPreferences("UserData", Context.MODE_PRIVATE) val username = sharedPref.getString("username", "Guest")
This app saves a welcome message locally and then shows it on screen. It works even if there is no internet.
import android.content.Context import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import android.widget.TextView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(android.R.layout.simple_list_item_1) val sharedPref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE) val editor = sharedPref.edit() // Save data locally editor.putString("welcomeMessage", "Hello, offline user!") editor.apply() // Read data locally val message = sharedPref.getString("welcomeMessage", "Welcome!") val textView = findViewById<TextView>(android.R.id.text1) textView.text = message } }
Local storage is fast and works without internet.
Use it for small data like settings or cached info.
For large or complex data, consider databases or files.
Local storage keeps data on the device for offline use.
SharedPreferences is a simple way to save key-value pairs in Android.
This helps apps work smoothly without internet connection.
val prefs = getSharedPreferences("prefs", MODE_PRIVATE)
val name = prefs.getString("username", "Guest")
println(name)val prefs = getSharedPreferences("prefs", MODE_PRIVATE)
prefs.edit().putBoolean("isLoggedIn", true)Pass the test and this pattern moves unknown