I guess your crash occurs due to an IllegalArgumentException: Unknown URL, which indicates that the URI used in the insert operation does not match the URI pattern registered in the ContentProvider
. First, ensure the AUTHORITY
value in your UriMatcher
matches exactly with what is used in AppDataProviderWrapper
. Update the UriMatcher
definition as follows:
private val sUriMatcher = UriMatcher(UriMatcher.NO_MATCH).apply {
addURI(AUTHORITY, "globaldataapp", 1)
}
Similarly, in AppDataProviderWrapper
, ensure you are using the correct URI:
private val mContentUri: Uri = Uri.parse("content://$AUTHORITY/globaldataapp")
Additionally, modify the insert()
method in AppGlobalDataContentProvider
to handle unknown URIs gracefully by logging the error instead of throwing an exception.
override fun insert(uri: Uri, values: ContentValues?): Uri? {
return when (sUriMatcher.match(uri)) {
1 -> {
val value = values?.getAsString(KEY_VALUE) ?: return null
sharedPreferences.edit().putString(KEY_VALUE, value).apply()
context?.contentResolver?.notifyChange(uri, null)
uri
}
else -> {
Log.e("AppGlobalDataContentProvider", "Unknown URI: $uri")
null
}
}
}
Your saveData()
function should also handle potential failures when inserting into the ContentProvider
:
fun saveData(data: Int) {
val contentResolver = context.contentResolver
val contentValues = ContentValues().apply {
put(KEY_VALUE, data)
}
try {
val resultUri = contentResolver.insert(mContentUri, contentValues)
if (resultUri == null) {
Log.e("AppDataProviderWrapper", "Failed to insert data into ContentProvider")
}
} catch (e: Exception) {
Log.e("AppDataProviderWrapper", "Error inserting data", e)
}
}
Furthermore, as you need to maintain data consistency across multiple user profiles, ensure that all reads and writes are performed using DeviceProtectedStorageContext
, allowing the data to persist across different user sessions:
val context = context.createDeviceProtectedStorageContext()
Lastly, check your AndroidManifest.xml`` to ensure that
android:exported="true"is set if other apps or system services require access. Also, consider adding
android:directBootAware="true"``` to ensure preferences are accessible across user profiles. With these fixes, your application should correctly save and retrieve data across all user profiles without crashing.