Dataset Preview
Full Screen
The full dataset viewer is not available (click to read why). Only showing a preview of the rows.
The dataset generation failed because of a cast error
Error code:   DatasetGenerationCastError
Exception:    DatasetGenerationCastError
Message:      An error occurred while generating the dataset

All the data files must have the same columns, but at some point there are 2 new columns ({'Instructions', 'date'}) and 1 missing columns ({'instruction'}).

This happened while the json dataset builder was generating data using

hf://datasets/shajmaan/android/android_dataset_last6yr.json (at revision e92df9827c7e12ca1de4508bce7df0f54efe3808)

Please either edit the data files to have matching columns, or separate them into different configurations (see docs at https://hf.co/docs/hub/datasets-manual-configuration#multiple-configurations)
Traceback:    Traceback (most recent call last):
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 2011, in _prepare_split_single
                  writer.write_table(table)
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/arrow_writer.py", line 585, in write_table
                  pa_table = table_cast(pa_table, self._schema)
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2302, in table_cast
                  return cast_table_to_schema(table, schema)
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2256, in cast_table_to_schema
                  raise CastError(
              datasets.table.CastError: Couldn't cast
              Instructions: string
              date: int64
              output: string
              input: string
              to
              {'instruction': Value(dtype='string', id=None), 'output': Value(dtype='string', id=None), 'input': Value(dtype='string', id=None)}
              because column names don't match
              
              During handling of the above exception, another exception occurred:
              
              Traceback (most recent call last):
                File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1534, in compute_config_parquet_and_info_response
                  parquet_operations = convert_to_parquet(builder)
                File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1155, in convert_to_parquet
                  builder.download_and_prepare(
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1027, in download_and_prepare
                  self._download_and_prepare(
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1122, in _download_and_prepare
                  self._prepare_split(split_generator, **prepare_split_kwargs)
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1882, in _prepare_split
                  for job_id, done, content in self._prepare_split_single(
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 2013, in _prepare_split_single
                  raise DatasetGenerationCastError.from_cast_error(
              datasets.exceptions.DatasetGenerationCastError: An error occurred while generating the dataset
              
              All the data files must have the same columns, but at some point there are 2 new columns ({'Instructions', 'date'}) and 1 missing columns ({'instruction'}).
              
              This happened while the json dataset builder was generating data using
              
              hf://datasets/shajmaan/android/android_dataset_last6yr.json (at revision e92df9827c7e12ca1de4508bce7df0f54efe3808)
              
              Please either edit the data files to have matching columns, or separate them into different configurations (see docs at https://hf.co/docs/hub/datasets-manual-configuration#multiple-configurations)

Need help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.

instruction
string
output
string
input
string
Hilt with ksp instead of kapt
When using kotlin, ksp and compose you have to keep in mind to use versions that are compatible with each other, otherwise building the project will most likely fail. Kotlin and KSP Take a look at releases, ksp version always consist of two parts e.g. 1.9.23-1.0.20 where 1.9.23 is kotlin version and 1.0.20 is actual KSP version (i think). Kotlin and Compose List of compatible versions can be found in Android docs. Your case Since you are using kotlin 1.9.0 you should use KSP 1.9.0-1.0.13 and kotlinCompilerExtensionVersion 1.5.2. For the dagger it should word fine for version 2.48 and above based on this, so version 2.51 is fine.
how to use hilt with ksp instead of kapt seems like i can't figure it out please let me know what dependencies should i add and how should i add them dependencies i added: //hilt val hiltVersion = "2.51" implementation("com.google.dagger:hilt-android:$hiltVersion") ksp("com.google.dagger:hilt-android-compiler:$hiltVersion") ksp("com.google.dagger:hilt-compiler:$hiltVersion") plugins: plugins { id("com.android.application") id("org.jetbrains.kotlin.android") id ("com.google.dagger.hilt.android") id("com.google.devtools.ksp") version "1.9.22-1.0.17" } build gradle: plugins { id("com.android.application") version "8.2.2" apply false id("org.jetbrains.kotlin.android") version "1.9.0" apply false id("com.google.dagger.hilt.android") version "2.51" apply false id("com.google.devtools.ksp") version "1.9.22-1.0.17" apply false } i tried different hilt versions like 2.48.1 different kotlinCompilerExtensionVersion like 1.5.8 nothing seems to work i've got multiple different errors don't know what i'm doing neither do i know what i'm doing wrong
Creating a circle button and centering text in compose android
Set default content padding contentPadding = PaddingValues(0.dp) ElevatedButton( onClick = { Toast.makeText(this@MainActivity, "Click", Toast.LENGTH_SHORT).show() }, modifier = Modifier.width(34.dp), contentPadding = PaddingValues(0.dp) ) { Text( text = "JB", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis ) }
I am trying to create a circle button with text of some initials inside that should be centered. The button size should be 34.dp and the text should be 13.sp but I have to increase the size of the button to get the text to display correctly I think the reason the text doesn't display is because of the internal padding of the Text composable. Button( modifier = Modifier.size(49.dp), colors = ButtonDefaults.buttonColors( containerColor = Color.Black, contentColor = Color.White), onClick = { }) { Text(text = "JB", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, style = TextStyle( lineHeightStyle = LineHeightStyle( alignment = LineHeightStyle.Alignment.Center, trim = LineHeightStyle.Trim.Both ) ) ) }
Round decimals to the closest non zero digit in Kotlin
Double.toString() already does most of this for you - it just retains as many digits as necessary to distinguish the number from other doubles, so it'll strip the trailing zeroes. The only issue is wanting 1.0 represented as 1, since that's technically an integer representation, not a double. You can write a function to take care of that case though: // or a val with a get() to make the string representation a property fun Double.roundToString() = when { toInt().toDouble() == this -> toInt() else -> this }.toString() Just FYI, if the number's small enough (less than 10¯³) toString() will produce scientific notation instead of listing all the digits with leading zeroes. If you want to handle those, you'll probably have to work with format strings, decide how much precision you want, etc. Here's a way you can do that, with up to 10 digits of precision, and any trailing zeroes removed (and the decimal point itself, if it ends up at the end): fun Double.roundToString() = "%.10f".format(this).trimEnd('0').trimEnd('.') or using a regex if you're into that fun Double.roundToString() = "%.10f".format(this).replace(Regex("\\.*0+$"), "")
I am trying to print multiple doubles with different decimal points, I have search for a while but I cannot find the exact solution for my need. Let me explain it as an example, so there are a few double variables here: 1.23 0.330 1.00 1.001 The result I want: 1.23 0.33 (unwanted 0 removed) 1 (unwanted 0 removed) 1.001 Is there any pre-developed syntax for this or do I have to make the algo myself? My current solution: fun Double.roundToLastDecimal(): Number { val num = this.toString().toDouble() return if (num % 1 == 0.0) { num.toInt() } else { num } }
Jetpack Compose run animation after recomposition
Please provide producible example so you won't need to ask it again. You can run an animation with Animatable calling animatable.animateTo() inside LaunchedEffect after composition is completed. And instead of creating recomposition by using Modifier.offset(), Modifier.background() you can select Modifiers counterparts with lambda. https://developer.android.com/jetpack/compose/performance/bestpractices#defer-reads You can animate alpha for instance without triggering recomposition after composition is completed inside Draw phase of frame val animatable = remember { Animatable(0f) } LaunchedEffect(key1 = Unit) { animatable.animateTo(1f) } Box( Modifier .size(100.dp) .drawBehind { drawRect(Color.Red.copy(alpha = animatable.value)) } ) https://stackoverflow.com/a/73274631/5457853
Is there any way how to run animation once recomposition (of screen, or some composable) is done? When animation is running and there is recomposition at the same time, animation has very bad performance (it is not smooth at all). I tried delay to delay animation for a while, but I don't think that's a good idea. There must be better way of doing this.
Does Android Automotive support Jetpack Compose?
In general, it is not possible to use Jetpack Compose to write an application for Android Automotive OS that will be distributed via the Play Store. There are a few exceptions to this however: Parked apps can be written in either Views or Compose and do not use the Car App Library templating system The Settings/Sign In activities of Media applications can also use either Views or Compose. One thing to note is that only the following category of apps are currently permitted on the Play Store for Android Automotive OS Media (audio - e.g. music, podcasts, audiobooks) Point of Interest Internet of Things Navigation Parked apps Video Games Browsers (see Supported app categories for more details/up-to-date information)
We are trying to publish an Android Automotive app, but have some issues extending the CarAppService. Disclaimer: I am very new to Android Automotive, so there might be an obvious answer to this question. The code we are working on was developed by a previous team (which we don´t have contact with), and they have used Jetpack Compose for the application. Instead of CarAppService, they have used MainActivity, and instead of onGetTemplate, they have used setContent (code snippet below). The function in MainActivity which implements the main component (Calculator()) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) carInfo = fetchCarInfo() fetchUxRestrictions() setContent { Theme { Calculator(this, isCarRestrictionNoSetup) } } } From the AndroidManifest.xml file: <activity android:name=".MainActivity" android:exported="true"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> <category android:name="androidx.car.app.category.POI" /> </intent-filter> <meta-data android:name="distractionOptimized" android:value="true" /> </activity> I have found very little documentation on the use of Jetpack Compose for Android Automotive, and in this video https://android-developers.googleblog.com/2021/03/android-auto-apps-powered-by-jetpack.html, at 09:38, its stated that "[...] currently and probably for forseeable future, you can only build apps relied on templates". In the examples I have found online with CarAppService, onGetTemplate is always used to build and style the Android Automotive application. After some research, I am growing certain that we can't use Jetpack Compose for the application, and that it has to be built on the predefined templates. If that is the case, my concern is that we have to scrap the code the previous team wrote and start over, which is why I want to ask here before I do anything. My question is, is it possible to use Jetpack Compose to style an Android Automotive application, or do we have to use the templates?
Remember not recompose when value change in jetpack compose
In this case, you don't need a remember at all - Compose is already never going to change anything that pairButtonColor relies on unless selectedIndexOfAvailableItem changes, so can simply remove the remember and write: val pairButtonColor = if (selectedIndexOfAvailableItem != -1) { Color.Blue } else { Color.Yellow } But to understand why your remember isn't working, it is important to understand what remember { } is doing. When you write val pairButtonColor = remember { // ... } The code in the block is only run once and the value it returns is remembered (that's the whole point of remember). This is why remember also has a version that take a single key or multiple keys: Remember the value returned by calculation [your code block] if all values of keys are equal to the previous composition, otherwise produce and remember a new value by calling calculation. Which would mean if you want your remember to rerun when selectedIndexOfAvailableItem changes, then it would need to be one of the keys you use: val pairButtonColor = remember(selectedIndexOfAvailableItem) { if (selectedIndexOfAvailableItem != -1) { Color.Blue } else { Color.Yellow } } But as per the Best practices around using remember, usages of remember like this, where the source of the data is already a remembered value, are mostly around avoiding expensive calculations (i.e., if the block of code was very expensive to rerun, a remember on pairButtonColor might be helpful) or calculations that rely on remembered values that are changing rapidly (where remember + derivedStateOf would help improve performance). In your case, neither apply - an if check is something that doesn't require remember at all.
I am increasing a value and I want to change color of text on that bases. When my value change my text color is not changing. PairStateFul @Composable fun PairStateFul() { var selectedIndexOfAvailableItem by remember { mutableStateOf(-1) } val pairButtonColor = remember { if (selectedIndexOfAvailableItem != -1) { Color.Blue } else { Color.Yellow } } Column { PairStateLess( pairButtonColor, selectedIndexOfAvailableItem, onSelectedIndexOfAvailableItem = { selectedIndexOfAvailableItem += it } ) } } PairStateLess @Composable fun PairStateLess(pairButtonColor: Color, selectedIndexOfAvailableItem: Int, onSelectedIndexOfAvailableItem: (Int) -> Unit, ) { Text( "Hello World!", color = pairButtonColor ) Button(onClick = { onSelectedIndexOfAvailableItem(selectedIndexOfAvailableItem) }) { Text(text = "item $selectedIndexOfAvailableItem") } } PairStateFulPreview @Preview(showBackground = true) @Composable fun PairStateFulPreview() { PairStateFul() } I know my increase counter logic is wrong. I don't want to solve logic. My main problem is when selectedIndexOfAvailableItem change then my pairButtonColor will also change.
Composable getting bloated with too many callbacks passed
You can use sealed class to create click events that can be reused in different places in your project depending on your need. // Create your different click events sealed class MyClickEvent { object Press1: MyClickEvent() object Press2: MyClickEvent() object Press3: MyClickEvent() object Press4: MyClickEvent() // You can create a click event that passes arguments data class Press5(val arg: String): MyClickEvent() } // Handle each click event ( This function should be inside your view model ) fun onMyClickEvent(event: MyClickEvent) { when(event) { is MyClickEvent.Press1 -> println("Press1") is MyClickEvent.Press2 -> println("Press2") is MyClickEvent.Press3 -> println("Press3") is MyClickEvent.Press4 -> println("Press4") is MyClickEvent.Press5 -> println("Press5: ${event.arg}") } } @Composable fun MyMainComposable() { MyComposable( onMyClickEvent = { event -> onMyClickEvent(event) } ) } // Pass only single lambda for different click events @Composable fun MyComposable( onMyClickEvent: (event: MyClickEvent) -> Unit, ) { Button(onClick = { onMyClickEvent(MyClickEvent.Press1) }) { Text(text = "Press 1") } Button(onClick = { onMyClickEvent(MyClickEvent.Press2) }) { Text(text = "Press 2") } Button(onClick = { onMyClickEvent(MyClickEvent.Press3) }) { Text(text = "Press 3") } Button(onClick = { onMyClickEvent(MyClickEvent.Press4) }) { Text(text = "Press 4") } Button(onClick = { onMyClickEvent(MyClickEvent.Press5(arg = "data")) }) { Text(text = "Press 5") } }
This is my current composable: @Composable fun MyComposable( onPress1: () -> Unit, onPress2: () -> Unit, onPress3: () -> Unit, onPress4: () -> Unit, onPress5: () -> Unit, ) { Button(onClick = onPress1) { Text(text = "Press 1")} Button(onClick = onPress2) { Text(text = "Press 2")} Button(onClick = onPress3) { Text(text = "Press 3")} Button(onClick = onPress4) { Text(text = "Press 4")} Button(onClick = onPress5) { Text(text = "Press 5")} } Is there a way to reduce this, Similar to how react has useReducer hook with action types and action payload
Is it possible to invoke a back button click programmatically?
From your activity just call => onBackPressed(), or form your fragment => activity?.onBackPressed()
I've seen plenty of answers explaining how to override and add functionality to a back button press via user's interaction, but almost none of the answers explain how to programmatically trigger a back button press without any user input. Answers that do address it give somewhat deprecated code samples that don't really compute.
Android Jetpack Compose: How to react to the state changes of 3rd party composable from library (Compose Calendar by boguszpawlowski)
you can listen to state changes using LaunchedEffect i have not used your library but you can pass it to LaunchedEffect LaunchedEffect(calendarState){ // your conditions // do your api call here } or LaunchedEffect(calendarState.monthState.currentMonth){ // do your api call here }
I investigate boguszpawlowski Compose Calendar and I cannot find a way to track state changes of the component, because there are no callback for it. For example I need to get events only for current month (send a request) and after it I should show them in calendar. When user switch month I should send a request again. Author in description suggest using state hoisting for it. In case you need to react to the state changes, or change the state from the outside of the composable, you need to hoist the state out of the Calendar composable: @Composable fun MainScreen() { val calendarState = rememberCalendarState() StaticCalendar(calendarState = calendarState) // now you can manipulate the state from scope of this composable calendarState.monthState.currentMonth = MonthYear.of(2020, 5) } I understand how to change current of initial month, but I do not know how to listen event when user swipe calendar or click the button to change month. How can I do it? boguszpawlowski ComposeCalendar github link
Ionic capacitor: splash screen shows wrong image
It’s the new splash behavior starting in Android 12. It shows the app icon instead of the splash screen background. You can change the icon y adding this to the splash screen theme, but it’s not possible to use a full screen image anymore <item name="android:windowSplashScreenAnimatedIcon">@drawable/yourIcon.png</item> https://developer.android.com/develop/ui/views/launch/splash-screen
I tried to replace the default splash image with the my splash image, but it shows wrong image. The splash screen displays my custom icon image, not my custom splash image. In iOS, the splash screen shows correct splash image. It doesn't in Android. How can I solve this issue? I already tried capacitor-resources -p android, cordova-res android --skip-config --copy and node resources.js. All doesn't work... This is my resource.js in the root. const fs = require('fs'); function copyImages(sourcePath, targetPath, images) { for (const icon of images) { let source = sourcePath + icon.source; let target = targetPath + icon.target; fs.copyFile(source, target, err => { if (err) throw err; console.log(`${source} >> ${target}`); }); } } const SOURCE_ANDROID_ICON = 'resources/android/icon/'; const SOURCE_ANDROID_SPLASH = 'resources/android/splash/'; const TARGET_ANDROID_ICON = 'android/app/src/main/res/'; const TARGET_ANDROID_SPLASH = 'android/app/src/main/res/'; const ANDROID_ICONS = [ { source: 'drawable-ldpi-icon.png', target: 'drawable-hdpi-icon.png' }, { source: 'drawable-mdpi-icon.png', target: 'mipmap-mdpi/ic_launcher.png' }, { source: 'drawable-mdpi-icon.png', target: 'mipmap-mdpi/ic_launcher_round.png' }, { source: 'drawable-mdpi-icon.png', target: 'mipmap-mdpi/ic_launcher_foreground.png' }, { source: 'drawable-hdpi-icon.png', target: 'mipmap-hdpi/ic_launcher.png' }, { source: 'drawable-hdpi-icon.png', target: 'mipmap-hdpi/ic_launcher_round.png' }, { source: 'drawable-hdpi-icon.png', target: 'mipmap-hdpi/ic_launcher_foreground.png' }, { source: 'drawable-xhdpi-icon.png', target: 'mipmap-xhdpi/ic_launcher.png' }, { source: 'drawable-xhdpi-icon.png', target: 'mipmap-xhdpi/ic_launcher_round.png' }, { source: 'drawable-xhdpi-icon.png', target: 'mipmap-xhdpi/ic_launcher_foreground.png' }, { source: 'drawable-xxhdpi-icon.png', target: 'mipmap-xxhdpi/ic_launcher.png' }, { source: 'drawable-xxhdpi-icon.png', target: 'mipmap-xxhdpi/ic_launcher_round.png' }, { source: 'drawable-xxhdpi-icon.png', target: 'mipmap-xxhdpi/ic_launcher_foreground.png' }, { source: 'drawable-xxxhdpi-icon.png', target: 'mipmap-xxxhdpi/ic_launcher.png' }, { source: 'drawable-xxxhdpi-icon.png', target: 'mipmap-xxxhdpi/ic_launcher_round.png' }, { source: 'drawable-xxxhdpi-icon.png', target: 'mipmap-xxxhdpi/ic_launcher_foreground.png' } ]; const ANDROID_SPLASHES = [ { source: 'drawable-land-mdpi-screen.png', target: 'drawable/splash.png' }, { source: 'drawable-land-mdpi-screen.png', target: 'drawable-land-mdpi/splash.png' }, { source: 'drawable-land-hdpi-screen.png', target: 'drawable-land-hdpi/splash.png' }, { source: 'drawable-land-xhdpi-screen.png', target: 'drawable-land-xhdpi/splash.png' }, { source: 'drawable-land-xxhdpi-screen.png', target: 'drawable-land-xxhdpi/splash.png' }, { source: 'drawable-land-xxxhdpi-screen.png', target: 'drawable-land-xxxhdpi/splash.png' }, { source: 'drawable-port-mdpi-screen.png', target: 'drawable-port-mdpi/splash.png' }, { source: 'drawable-port-hdpi-screen.png', target: 'drawable-port-hdpi/splash.png' }, { source: 'drawable-port-xhdpi-screen.png', target: 'drawable-port-xhdpi/splash.png' }, { source: 'drawable-port-xxhdpi-screen.png', target: 'drawable-port-xxhdpi/splash.png' }, { source: 'drawable-port-xxxhdpi-screen.png', target: 'drawable-port-xxxhdpi/splash.png' } ]; copyImages(SOURCE_ANDROID_ICON, TARGET_ANDROID_ICON, ANDROID_ICONS); copyImages(SOURCE_ANDROID_SPLASH, TARGET_ANDROID_SPLASH, ANDROID_SPLASHES); This is my capacitor.config.ts import { CapacitorConfig } from '@capacitor/cli'; const config: CapacitorConfig = { appId: 'com.myapp.app', appName: 'My App', webDir: 'www', bundledWebRuntime: false, cordova: { preferences: { ScrollEnabled: 'false', BackupWebStorage: 'none', //SplashMaintainAspectRatio: 'true', 'android-minSdkVersion': '28', 'android-targetSdkVersion': '32', 'android-buildToolsVersion': '32.0.0', //SplashShowOnlyFirstTime: 'false', //SplashScreen: 'screen', //SplashScreenDelay: '2000', //AutoHideSplashScreen: 'true', GradlePluginGoogleServicesEnabled: 'false' } }, plugins: { SplashScreen: { launchShowDuration: 3000, launchAutoHide: true, //backgroundColor: "#ffffffff", androidSplashResourceName: "splash", //androidScaleType: "CENTER_CROP", showSpinner: false, //androidSpinnerStyle: "large", //iosSpinnerStyle: "small", //spinnerColor: "#999999", splashFullScreen: true, splashImmersive: true, //layoutName: "launch_screen", //useDialog: true, }, }, }; export default config;
How to remove native navigation bar elevation through Compose?
I've found the issue - it looks like if the Scaffold is wrapped in a ModalBottomSheetLayout, it will do weird colour changes like this to the BottomNavigation. In order to avoid this, you can do: ModalBottomSheetLayout( sheetElevation = 0.dp, bottomSheetNavigator = bottomSheetNavigator, ) { ... } and the "faint divider" goes away! The ModalBottomSheetLayout is from the accompanist library as well - com.google.accompanist:accompanist-navigation-material
I'm trying to get rid of a faint divider between the native navigation buttons on the bottom of the screen and the content of my app. This is what I have - you can see a very faint divider between the navigation buttons and the bottom navigation bar of my app. Is it elevation? Shadow? But this is what I want (this is the Android Slack app) - all same colour. In my app, I'm explicitly setting the bottom navigation bar to white, as well as use the accompanist library to set the navigation bar to white, like so: BottomNavigation( modifier = Modifier .background(Color.White), backgroundColor = Color.White, elevation = 0.dp, ) ... val systemUiController = rememberSystemUiController() SideEffect { systemUiController.setSystemBarsColor( color = Color.White, ) } What else can I do?
Xamarin - Permission "REQUEST_INSTALL_PACKAGES" - Which dependency brings this permission
Microsoft Appcenter What Android permissions are required? Depending on the services you use, the following permissions are required: All services: INTERNET, ACCESS_NETWORK_STATE Distribute: REQUEST_INSTALL_PACKAGES, DOWNLOAD_WITHOUT_NOTIFICATION Microsoft.AppCenter.Distribute is required that permission.
I received a mail from Google warning me about "REQUEST_INSTALL_PACKAGES" permission. I understand the warning, but I can't find which dependency brings this permission. I found the "REQUEST_INSTALL_PACKAGES" permission in the merged manifest, but it is not added by my code, so I guess it comes from a dependency but I can't find which one. Do you know how I can find which dependency brings this permission ? For your information, I'm on Xamarin.Android 11 and Xamarin.Forms 4.8. <?xml version="1.0" encoding="utf-8"?> <packages> <package id="FastAndroidCamera" version="2.0.0" targetFramework="monoandroid81" /> <package id="Forms9Patch" version="1.5.0.9" targetFramework="monoandroid81" /> <package id="LiteDB" version="5.0.9" targetFramework="monoandroid81" /> <package id="Microsoft.AppCenter" version="1.6.0" targetFramework="monoandroid81" /> <package id="Microsoft.AppCenter.Analytics" version="1.6.0" targetFramework="monoandroid81" /> <package id="Microsoft.AppCenter.Crashes" version="1.6.0" targetFramework="monoandroid81" /> <package id="Microsoft.AppCenter.Distribute" version="1.6.0" targetFramework="monoandroid81" /> <package id="Microsoft.AspNetCore.Connections.Abstractions" version="3.1.20" targetFramework="monoandroid11.0" /> <package id="Microsoft.AspNetCore.Http.Connections.Client" version="3.1.20" targetFramework="monoandroid11.0" /> <package id="Microsoft.AspNetCore.Http.Connections.Common" version="3.1.20" targetFramework="monoandroid11.0" /> <package id="Microsoft.AspNetCore.Http.Features" version="3.1.20" targetFramework="monoandroid11.0" /> <package id="Microsoft.AspNetCore.SignalR.Client" version="3.1.20" targetFramework="monoandroid11.0" /> <package id="Microsoft.AspNetCore.SignalR.Client.Core" version="3.1.20" targetFramework="monoandroid11.0" /> <package id="Microsoft.AspNetCore.SignalR.Common" version="3.1.20" targetFramework="monoandroid11.0" /> <package id="Microsoft.AspNetCore.SignalR.Protocols.Json" version="3.1.20" targetFramework="monoandroid11.0" /> <package id="Microsoft.Bcl.AsyncInterfaces" version="6.0.0" targetFramework="monoandroid11.0" /> <package id="Microsoft.CSharp" version="4.5.0" targetFramework="monoandroid81" /> <package id="Microsoft.Extensions.Configuration" version="3.1.20" targetFramework="monoandroid11.0" /> <package id="Microsoft.Extensions.Configuration.Abstractions" version="3.1.20" targetFramework="monoandroid11.0" /> <package id="Microsoft.Extensions.Configuration.Binder" version="3.1.20" targetFramework="monoandroid11.0" /> <package id="Microsoft.Extensions.DependencyInjection" version="3.1.20" targetFramework="monoandroid11.0" /> <package id="Microsoft.Extensions.DependencyInjection.Abstractions" version="5.0.0" targetFramework="monoandroid11.0" /> <package id="Microsoft.Extensions.Logging" version="3.1.20" targetFramework="monoandroid11.0" /> <package id="Microsoft.Extensions.Logging.Abstractions" version="3.1.20" targetFramework="monoandroid11.0" /> <package id="Microsoft.Extensions.Options" version="3.1.20" targetFramework="monoandroid11.0" /> <package id="Microsoft.Extensions.Primitives" version="3.1.20" targetFramework="monoandroid11.0" /> <package id="Microsoft.Identity.Client" version="4.29.0" targetFramework="monoandroid81" /> <package id="Microsoft.IdentityModel.Clients.ActiveDirectory" version="3.19.8" targetFramework="monoandroid81" /> <package id="Microsoft.NETCore.Platforms" version="1.1.1" targetFramework="monoandroid81" /> <package id="Microsoft.NETCore.Targets" version="1.1.3" targetFramework="monoandroid81" /> <package id="Microsoft.Rest.ClientRuntime" version="2.3.13" targetFramework="monoandroid81" /> <package id="Microsoft.VisualStudio.Threading" version="17.1.46" targetFramework="monoandroid11.0" /> <package id="Microsoft.VisualStudio.Threading.Analyzers" version="17.1.46" targetFramework="monoandroid11.0" developmentDependency="true" /> <package id="Microsoft.VisualStudio.Validation" version="17.0.43" targetFramework="monoandroid11.0" /> <package id="Microsoft.Win32.Primitives" version="4.3.0" targetFramework="monoandroid81" /> <package id="Microsoft.Win32.Registry" version="5.0.0" targetFramework="monoandroid11.0" /> <package id="Mvvmicro" version="0.10.17" targetFramework="monoandroid11.0" /> <package id="Navigation.Abstractions" version="2.4.0-unstable0002" targetFramework="monoandroid81" /> <package id="NETStandard.Library" version="2.0.1" targetFramework="monoandroid81" /> <package id="Newtonsoft.Json" version="12.0.1" targetFramework="monoandroid81" /> <package id="NLog" version="4.5.4" targetFramework="monoandroid81" /> <package id="NLog.Config" version="4.5.4" targetFramework="monoandroid81" /> <package id="NLog.Schema" version="4.5.4" targetFramework="monoandroid81" /> <package id="Plugin.CurrentActivity" version="2.1.0.2" targetFramework="monoandroid81" /> <package id="Plugin.Permissions" version="3.0.0.12" targetFramework="monoandroid81" /> <package id="Rg.Plugins.Popup" version="1.1.5.188" targetFramework="monoandroid81" /> <package id="SkiaSharp" version="2.80.2" targetFramework="monoandroid11.0" /> <package id="SkiaSharp.Svg" version="1.59.1" targetFramework="monoandroid81" /> <package id="SkiaSharp.Views" version="2.80.2" targetFramework="monoandroid11.0" /> <package id="SkiaSharp.Views.Forms" version="2.80.2" targetFramework="monoandroid11.0" /> <package id="StyleCop.MSBuild" version="6.0.0-beta04" targetFramework="monoandroid81" developmentDependency="true" /> <package id="System.AppContext" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Buffers" version="4.5.1" targetFramework="monoandroid11.0" /> <package id="System.Collections" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Collections.Concurrent" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.ComponentModel.Annotations" version="4.7.0" targetFramework="monoandroid11.0" /> <package id="System.ComponentModel.TypeConverter" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Console" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Diagnostics.Debug" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Diagnostics.Process" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Diagnostics.Tools" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Diagnostics.Tracing" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Dynamic.Runtime" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Globalization" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Globalization.Calendars" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.IO" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.IO.Compression" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.IO.Compression.ZipFile" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.IO.FileSystem" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.IO.FileSystem.Primitives" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.IO.Pipelines" version="4.7.4" targetFramework="monoandroid11.0" /> <package id="System.Linq" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Linq.Expressions" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Memory" version="4.5.2" targetFramework="monoandroid11.0" /> <package id="System.Net.Http" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Net.Primitives" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Net.Sockets" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Numerics.Vectors" version="4.5.0" targetFramework="monoandroid81" /> <package id="System.ObjectModel" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Private.Uri" version="4.3.2" targetFramework="monoandroid81" /> <package id="System.Reflection" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Reflection.Extensions" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Reflection.Primitives" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Reflection.TypeExtensions" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Resources.ResourceManager" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Runtime" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Runtime.CompilerServices.Unsafe" version="4.7.1" targetFramework="monoandroid11.0" /> <package id="System.Runtime.Extensions" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Runtime.Handles" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Runtime.InteropServices" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Runtime.InteropServices.RuntimeInformation" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Runtime.Numerics" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Runtime.Serialization.Formatters" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Runtime.Serialization.Json" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Runtime.Serialization.Primitives" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Security.AccessControl" version="5.0.0" targetFramework="monoandroid11.0" /> <package id="System.Security.Cryptography.Algorithms" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Security.Cryptography.Encoding" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Security.Cryptography.Primitives" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Security.Cryptography.X509Certificates" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Security.Principal.Windows" version="5.0.0" targetFramework="monoandroid11.0" /> <package id="System.Security.SecureString" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Text.Encoding" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Text.Encoding.Extensions" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Text.Encodings.Web" version="4.7.1" targetFramework="monoandroid11.0" /> <package id="System.Text.Json" version="4.7.2" targetFramework="monoandroid11.0" /> <package id="System.Text.RegularExpressions" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Threading" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Threading.Channels" version="4.7.1" targetFramework="monoandroid11.0" /> <package id="System.Threading.Tasks" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Threading.Tasks.Extensions" version="4.5.4" targetFramework="monoandroid11.0" /> <package id="System.Threading.Timer" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Xml.ReaderWriter" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Xml.XDocument" version="4.3.0" targetFramework="monoandroid81" /> <package id="System.Xml.XmlDocument" version="4.3.0" targetFramework="monoandroid81" /> <package id="Toasts.Forms.Plugin" version="3.3.2" targetFramework="monoandroid81" /> <package id="Xam.Forms.QRCode" version="0.5.0" targetFramework="monoandroid81" /> <package id="Xam.Plugin.Media" version="5.0.1" targetFramework="monoandroid81" /> <package id="Xamarin.Android.Arch.Core.Common" version="1.1.1.3" targetFramework="monoandroid81" /> <package id="Xamarin.Android.Arch.Lifecycle.Common" version="1.1.1.3" targetFramework="monoandroid81" /> <package id="Xamarin.Android.Arch.Lifecycle.Runtime" version="1.1.1.3" targetFramework="monoandroid81" /> <package id="Xamarin.Android.Support.Animated.Vector.Drawable" version="28.0.0.3" targetFramework="monoandroid81" /> <package id="Xamarin.Android.Support.Annotations" version="28.0.0.3" targetFramework="monoandroid81" /> <package id="Xamarin.Android.Support.Compat" version="28.0.0.3" targetFramework="monoandroid81" /> <package id="Xamarin.Android.Support.Core.UI" version="28.0.0.3" targetFramework="monoandroid81" /> <package id="Xamarin.Android.Support.Core.Utils" version="28.0.0.3" targetFramework="monoandroid81" /> <package id="Xamarin.Android.Support.CustomTabs" version="28.0.0.3" targetFramework="monoandroid81" /> <package id="Xamarin.Android.Support.Design" version="28.0.0.3" targetFramework="monoandroid81" /> <package id="Xamarin.Android.Support.Fragment" version="28.0.0.3" targetFramework="monoandroid81" /> <package id="Xamarin.Android.Support.Media.Compat" version="28.0.0.3" targetFramework="monoandroid81" /> <package id="Xamarin.Android.Support.Transition" version="28.0.0.3" targetFramework="monoandroid81" /> <package id="Xamarin.Android.Support.v4" version="28.0.0.3" targetFramework="monoandroid81" /> <package id="Xamarin.Android.Support.v7.AppCompat" version="28.0.0.3" targetFramework="monoandroid81" /> <package id="Xamarin.Android.Support.v7.CardView" version="28.0.0.3" targetFramework="monoandroid81" /> <package id="Xamarin.Android.Support.v7.MediaRouter" version="28.0.0.3" targetFramework="monoandroid81" /> <package id="Xamarin.Android.Support.v7.Palette" version="28.0.0.3" targetFramework="monoandroid81" /> <package id="Xamarin.Android.Support.v7.RecyclerView" version="28.0.0.3" targetFramework="monoandroid81" /> <package id="Xamarin.Android.Support.Vector.Drawable" version="28.0.0.3" targetFramework="monoandroid81" /> <package id="Xamarin.AndroidX.Activity" version="1.2.0.1" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.Annotation" version="1.2.0" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.Annotation.Experimental" version="1.0.0.9" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.AppCompat" version="1.2.0.7" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.AppCompat.AppCompatResources" version="1.3.0" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.AppCompat.Resources" version="1.1.0" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.Arch.Core.Common" version="2.1.0.8" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.Arch.Core.Runtime" version="2.1.0.8" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.AsyncLayoutInflater" version="1.0.0.1" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.Browser" version="1.0.0.1" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.CardView" version="1.0.0.8" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.Collection" version="1.1.0.7" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.ConstraintLayout" version="2.0.4.2" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.ConstraintLayout.Solver" version="2.0.4.2" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.CoordinatorLayout" version="1.1.0.7" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.Core" version="1.5.0" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.CursorAdapter" version="1.0.0.7" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.CustomView" version="1.1.0.6" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.DocumentFile" version="1.0.1.7" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.DrawerLayout" version="1.1.1.2" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.DynamicAnimation" version="1.0.0.7" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.Fragment" version="1.3.0.1" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.Interpolator" version="1.0.0.7" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.Legacy.Support.Core.UI" version="1.0.0.1" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.Legacy.Support.Core.Utils" version="1.0.0.7" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.Legacy.Support.V4" version="1.0.0.1" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.Lifecycle.Common" version="2.3.1" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.Lifecycle.LiveData" version="2.1.0.1" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.Lifecycle.LiveData.Core" version="2.3.0.1" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.Lifecycle.Runtime" version="2.3.1.1" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.Lifecycle.ViewModel" version="2.3.0.1" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.Lifecycle.ViewModelSavedState" version="2.3.0.1" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.Loader" version="1.1.0.7" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.LocalBroadcastManager" version="1.0.0.7" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.Media" version="1.3.1" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.MediaRouter" version="1.2.4" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.Migration" version="1.0.8" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.MultiDex" version="2.0.1.5" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.Palette" version="1.0.0.7" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.Print" version="1.0.0.7" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.RecyclerView" version="1.1.0.8" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.SavedState" version="1.1.0.1" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.SlidingPaneLayout" version="1.0.0.1" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.SwipeRefreshLayout" version="1.0.0.1" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.Transition" version="1.4.0.1" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.VectorDrawable" version="1.1.0.7" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.VectorDrawable.Animated" version="1.1.0.7" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.VersionedParcelable" version="1.1.1.7" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.ViewPager" version="1.0.0.7" targetFramework="monoandroid11.0" /> <package id="Xamarin.AndroidX.ViewPager2" version="1.0.0.9" targetFramework="monoandroid11.0" /> <package id="Xamarin.Build.Download" version="0.4.11" targetFramework="monoandroid81" /> <package id="Xamarin.Controls.SignaturePad" version="2.3.0" targetFramework="monoandroid81" /> <package id="Xamarin.Controls.SignaturePad.Forms" version="2.3.0" targetFramework="monoandroid81" /> <package id="Xamarin.Essentials" version="1.5.3.2" targetFramework="monoandroid81" /> <package id="Xamarin.FFImageLoading" version="2.4.5.922" targetFramework="monoandroid81" /> <package id="Xamarin.FFImageLoading.Forms" version="2.4.5.922" targetFramework="monoandroid81" /> <package id="Xamarin.FFImageLoading.Svg" version="2.4.5.922" targetFramework="monoandroid81" /> <package id="Xamarin.FFImageLoading.Svg.Forms" version="2.4.5.922" targetFramework="monoandroid81" /> <package id="Xamarin.Firebase.Common" version="60.1142.1" targetFramework="monoandroid81" /> <package id="Xamarin.Firebase.Iid" version="60.1142.1" targetFramework="monoandroid81" /> <package id="Xamarin.Firebase.Messaging" version="60.1142.1" targetFramework="monoandroid81" /> <package id="Xamarin.Forms" version="4.8.0.1821" targetFramework="monoandroid11.0" /> <package id="Xamarin.Google.Android.Material" version="1.3.0.1" targetFramework="monoandroid11.0" /> <package id="Xamarin.Google.Guava.ListenableFuture" version="1.0.0.2" targetFramework="monoandroid11.0" /> <package id="Xamarin.GooglePlayServices.Base" version="60.1142.1" targetFramework="monoandroid81" /> <package id="Xamarin.GooglePlayServices.Basement" version="60.1142.1" targetFramework="monoandroid81" /> <package id="Xamarin.GooglePlayServices.Location" version="60.1142.1" targetFramework="monoandroid81" /> <package id="Xamarin.GooglePlayServices.Tasks" version="60.1142.1" targetFramework="monoandroid81" /> <package id="ZXing.Net" version="0.16.4" targetFramework="monoandroid81" /> <package id="ZXing.Net.Mobile" version="2.4.1" targetFramework="monoandroid81" /> <package id="ZXing.Net.Mobile.Forms" version="2.4.1" targetFramework="monoandroid81" /> </packages> Thanks in advance
Room database.withTransaction { } block not Resolved
Thanks to @ianhanniballake day-saving comment above, if you run into this situation just change the room-runtime flavor from: implementation "androidx.room:room-runtime:2.4.3" kapt "androidx.room:room-compiler:2.4.3" to room-ktx flavor: implementation "androidx.room:room-ktx:2.4.3" kapt "androidx.room:room-compiler:2.4.3" As per Developers Docs ktx-libs provide Kotlin Extensions and Coroutines support which is exactly what database.withTransaction{} block is - it is an extension function on RoomDatabase as shown on this line from the source code. public suspend fun <R> RoomDatabase.withTransaction(block: suspend () -> R): R { Android KTX is a set of Kotlin extensions that are included with Android Jetpack and other Android libraries. KTX extensions provide concise, idiomatic Kotlin to Jetpack, Android platform, and other APIs. To do so, these extensions leverage several Kotlin language features, including the following: Extension functions Extension properties Lambdas Named parameters Parameter default values Coroutines
I am following this tutorial about RemoteMediator and everything is fine until I run into a weird error when using database.withTransaction{} to allow database operations. Unfortunately, the IDE doesn't seem (or is refusing) to recognize this very genuine and legit block. I have checked that I defined ROOM Database abstract class correctly and declared these ROOM and Paging 3 libs in build.gradle(app) file. // Room implementation "androidx.room:room-runtime:2.4.3" kapt "androidx.room:room-compiler:2.4.3" // Room-paging artifact implementation 'androidx.room:room-paging:2.4.3' // Paging 3.0 implementation 'androidx.paging:paging-compose:1.0.0-alpha16' So I decided to ignore the error and went ahead to call a dao function inside the withTransaction{} block but I get Suspension functions can be called only within a coroutine body. This is a bit confusing since RemoteMediator's load() override function is already a suspend function. Anyone with insights on this issue please help as I don't seem to be getting anywhere around this.
how to remove underline of outlinedtextfield compose when its focused?
You should specify the keyboardType as Password to get rid of the text underline. You can do that by using KeyboardOptions: OutlinedTextField( modifier = Modifier .fillMaxWidth() .padding(16.dp), value = password, onValueChange = { password = it }, leadingIcon = { Icon( painter = painterResource(id = R.drawable.ic_baseline_vpn_key_24), contentDescription = "icon-content" ) }, trailingIcon = { IconButton(onClick = { passwordVisibility = !passwordVisibility }) { Icon(painter = icon, contentDescription = "show-password") } }, placeholder = { Text( text = "Password", color = Color.LightGray ) }, label = { BasicText(text = "Password") }, visualTransformation = if (passwordVisibility) VisualTransformation.None else PasswordVisualTransformation(), keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Password // HERE ), ) This is the crucial change: keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Password )
When i try to enter some inputs to text field, it draws underline, how to remove this underline without change any color of outlinedtextfield. OutlinedTextField(modifier = Modifier .fillMaxWidth() .padding(16.dp),value = password, onValueChange = { password = it}, leadingIcon = { Icon(painter = painterResource(id = R.drawable.ic_baseline_vpn_key_24), contentDescription = "icon-content")}, trailingIcon = { IconButton(onClick = { passwordVisibility = !passwordVisibility }) { Icon(painter = icon, contentDescription = "show-password") }}, placeholder = { Text(text = "Password", color = Color.LightGray)}, label = { BasicText(text = "Password")}, visualTransformation = if(passwordVisibility) VisualTransformation.None else PasswordVisualTransformation() )
Kotlin vs Java : What to choose when starting a new Flutter project?
My Recommended is to Go for kotlin in Android. and For IOS go for Swift One of the best reason is Google and Apple recommended and preferred this languages. Second things kotlin is very optimized language so it's reduce the codes and make your dart file more clear to understand. Third things kotlin supports multiple platforms. where java have some limitations in it. But at the end both of the language is very useful to developed a single app. Note : If you start for Application development in native Android, First Go for Java language then you have to learn about kotlin. because Java is a Base of Native Android
When starting a new Flutter project in Android Studio, it gives you the choice of android language between Java or Kotlin. so the question is: Is my choice affecting any type of performance or compatibility? Application size or Error-handling ? Is there any difference at all ? Same goes for Objective-C vs Swift ?
registerForActivityResult is not working in Flutter
I too was searching for the solution. what i did was extend MainActivity with FlutterFragmentActivity and pass this to method channel handler. public class MainActivity extends FlutterFragmentActivity{ ... @Override public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) { handlePickerMethodChannel(flutterEngine); } private void handlePickerMethodChannel(FlutterEngine flutterEngine) { PickerMethodChannelHandler PickerMethodChannelHandler = new PickerMethodChannelHandler(new WeakReference<>(this)); new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), PHOTO_PICKER_METHOD_CHANNEL) .setMethodCallHandler(pickerMethodChannelHandler); } } class PickerMethodChannelHandler( private val activity: WeakReference<Activity>, ) : MethodChannel.MethodCallHandler { private val pickMedia = (activity.get() as ComponentActivity).registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri -> if (uri != null) { Log.d("PhotoPicker", "Selected URI: $uri") } else { Log.d("PhotoPicker", "No media selected") } } override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { when (call.method) { "pickMedia" -> pickMedia(call,result) else -> result.notImplemented() } } private fun pickMedia(call: MethodCall, result: MethodChannel.Result) { val context = activity.get() as ComponentActivity Log.i("PICK_MEDIA","PICK ${context != null}") pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageAndVideo)) } } It worked
I'm trying to launch context from android MainActivity class to flutter. code : val authResult = ComponentActivity().registerForActivityResult(PianoIdAuthResultContract()) { r -> when (r) { null -> { /* user cancelled Authorization process */ } is PianoIdAuthSuccessResult -> { val token = r.token val isNewUserRegistered = r.isNewUser if (token != null) { if (token.emailConfirmationRequired) { // process enabled Double opt-in } } // process successful authorization } is PianoIdAuthFailureResult -> { val e = r.exception // Authorization failed, check e.cause for details } } } and then calling the method launch code : try{ authResult.launch(PianoId.signIn()); }catch (e : Exception){ val text = e.message val duration = Toast.LENGTH_SHORT val toast = Toast.makeText(applicationContext, text, duration) toast.show() } and then I call this method from flutter by creating a channel between flutter and android and invoke it : signInChannel.invokeMethod('testSignIn'); when I press the sign in button it shows me this exception : Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
Android unit testing kotlin: LiveData value was never set
I found a solution to this: to make this working well, you need to add advanceUntilIdle() method. Immediately execute all pending tasks and advance the virtual clock-time to the last delay. If new tasks are scheduled due to advancing virtual time, they will be executed before advanceUntilIdle returns. @Test fun getStudentsSuccess() = runTest { Mockito.`when`(getStudentsUseCase.execute()).thenReturn(Result.success(studentList)) viewModel.getStudents() advanceUntilIdle() val value = viewModel.studentLD.getOrAwaitValueTest() assertEquals(value, studentList) }
I'm getting this error while unit testing: "LiveData value was never set." I'm trying to test the getStudents() method of my viewmodel that looks like this: StudentViewModel: @HiltViewModel class StudentViewModel @Inject constructor( private val getStudentsUseCase: GetStudentsUseCase ) : ViewModel() { private val _studentLD = MutableLiveData<List<Student>>() val studentLD: LiveData<List<Student>> = _studentLD private val _errorLD = MutableLiveData<String>() val errorLD: LiveData<String> = _errorLD fun getStudents() { viewModelScope.launch { var result = getStudentsUseCase.execute() result.onSuccess { _studentLD.value = it }.onFailure { _errorLD.value = it.message.toString() } } } } StudentViewModelTest: @OptIn(ExperimentalCoroutinesApi::class) class StudentViewModelTest { private lateinit var viewModel: StudentViewModel @get:Rule var instantExecutorRule = InstantTaskExecutorRule() @get:Rule var mainCoroutineRule = MainCoroutineRule() @Mock private lateinit var getStudentsUseCase: GetStudentsUseCase private var studentList = listOf( Student("Max", "122d"), Student("Steven", "012s") ) @Before fun setUp() { MockitoAnnotations.initMocks(this) viewModel = StudentViewModel(getStudentsUseCase) } @Test fun getStudentsSuccess() = runTest { Mockito.`when`(getStudentsUseCase.execute()).thenReturn(Result.success(studentList)) viewModel.getStudents() val value = viewModel.studentLD.getOrAwaitValueTest() assertEquals(value, studentList) } } What Am I doing wrong? I also have a class for LiveDataTest with the method getOrAwaitValueTest() defined in there. Thank you in advance Edit: Also, the getOrAwaitValueTest() method is defined here as follow: @VisibleForTesting(otherwise = VisibleForTesting.NONE) fun <T> LiveData<T>.getOrAwaitValueTest( time: Long = 2, timeUnit: TimeUnit = TimeUnit.SECONDS, afterObserve: () -> Unit = {} ): T { var data: T? = null val latch = CountDownLatch(1) val observer = object : Observer<T> { override fun onChanged(o: T?) { data = o latch.countDown() [email protected](this) } } this.observeForever(observer) try { afterObserve.invoke() // Don't wait indefinitely if the LiveData is not set. if (!latch.await(time, timeUnit)) { throw TimeoutException("LiveData value was never set.") } } finally { this.removeObserver(observer) } @Suppress("UNCHECKED_CAST") return data as T }
ERROR: cannot be cast to androidx.navigation.fragment.NavHostFragment. -- app crashing every time
Your XML file says: android:name="com.example.jetpacklesson.MainFragment" If you want that to be a NavHostFragment, you need to change that to android:name="androidx.navigation.fragment.NavHostFragment" As per the Navigation Getting Started guide.
So I'm trying to build an app with a bottom navigation bar that will switch between fragments. I did the coding according to some documentation. I tried every solution on the internet but none of them seems to work for me. the error: Caused by: java.lang.ClassCastException: com.example.jetpacklesson.MainFragment cannot be cast to androidx.navigation.fragment.NavHostFragment at com.example.jetpacklesson.MainActivity.onCreate(MainActivity.java:30) here is the XML main activity code <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <androidx.fragment.app.FragmentContainerView android:id="@+id/firstFragmentHolder" android:layout_width="0dp" android:layout_height="0dp" android:name="com.example.jetpacklesson.MainFragment" app:defaultNavHost = "true" app:layout_constraintBottom_toTopOf="@+id/bnv_bottomBar" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:navGraph = "@navigation/nav_graph"/> <com.google.android.material.bottomnavigation.BottomNavigationView android:id="@+id/bnv_bottomBar" android:layout_width="0dp" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:menu="@menu/nav_bottom_navigation" /> </androidx.constraintlayout.widget.ConstraintLayout> and main activity java code: BottomNavigationView bnv_navigationBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.firstFragmentHolder); NavController navController = navHostFragment.getNavController(); bnv_navigationBar = findViewById(R.id.bnv_bottomBar); NavigationUI.setupWithNavController(bnv_navigationBar, navController); }
How to place hanging icon in upper right corner of Card composable
You can do it in many ways. One of them is using Modifier.offset{}, another one using Modifier.graphicsLayer{} and setting translationX and translationY params, or Layout that places your Icon based on Image Composables. @Composable private fun MyIconBox() { val iconSize = 24.dp val offsetInPx = LocalDensity.current.run { (iconSize / 2).roundToPx() } Box(modifier = Modifier.padding((iconSize / 2))) { Card { Image( modifier = Modifier.size(200.dp), painter = painterResource(id = R.drawable.landscape4), contentDescription = null, contentScale = ContentScale.FillBounds ) } IconButton( onClick = {}, modifier = Modifier .offset { IntOffset(x = +offsetInPx, y = -offsetInPx) } .clip(CircleShape) .background(White) .size(iconSize) .align(Alignment.TopEnd) ) { Icon( imageVector = Icons.Rounded.Close, contentDescription = "", ) } } } Result
How can I achieve the effect shown below in the picture on a Card composable, with the X icon, for instance, hanging in the upper right corner? I don't want the rounded corners nor the black background, just the icon hanging in the upper right corner of the Card. I couldn't achieve this despite several attempts. Original Code on SO Box( modifier = Modifier .background(LightGray) .padding(16.dp) .size(88.dp), contentAlignment = Alignment.TopEnd ) { Image( painter = painterResource( id = R.drawable.ic_launcher_foreground, ), contentDescription = "", modifier = Modifier .align(Alignment.Center) .clip(RoundedCornerShape(16.dp)) .background(Black) .size(80.dp), contentScale = ContentScale.Crop, ) IconButton( onClick = {}, modifier = Modifier .clip(CircleShape) .background(White) .align(Alignment.TopEnd) .size(16.dp) ) { Icon( imageVector = Icons.Rounded.Close, contentDescription = "", ) } } Possible Code Structure? Box(...) { Card(...) { Image(...) { } } IconButton(...) { Icon(...) { } } }
Round corners for Dropdown menu compose android
With material3 the default shape used by the DropdownMenu is defined by the extraSmall attribute in the shapes You have to use: MaterialTheme( shapes = MaterialTheme.shapes.copy(extraSmall = RoundedCornerShape(16.dp)) ){ //... DropdownMenu() }
Before, I posted here, I Googled a lot. I found the following: MaterialTheme(shapes = MaterialTheme.shapes.copy(medium = RoundedCornerShape(16.dp))){} from the following SO post: Jetpack compose DropdownMenu With rounded Corners EDIT: I am using Material Design v3. MaterialTheme(shapes = MaterialTheme.shapes.copy(medium = RoundedCornerShape(16.dp))) { IconButton( onClick = { showMenu = !showMenu }) { Icon(imageVector = Icons.Outlined.MoreVert, contentDescription = "") DropdownMenu( expanded = showMenu, onDismissRequest = { showMenu = false }, modifier = Modifier.background(MaterialTheme.colorScheme.background).padding(4.dp) ) { DropdownMenuItem(text = { Text("Refresh", fontSize = 16.sp) }, onClick = { showMenu = false }) DropdownMenuItem(text = { Text("Settings", fontSize = 16.sp) }, onClick = { showMenu = false }) Divider(color = Color.LightGray, thickness = 1.dp) DropdownMenuItem(text = { Text("Send Feedback", fontSize = 16.sp) }, onClick = { showMenu = false }) } } } Currently it produces the following output: There certainly is some border radius, it isn't achieving the desired goal. The second screenshot from a third-party app, does have the border radius I am trying to get.
TopAppBar in jetpack compose without scaffold gives error
It happens because there is no matching functions with parameters you provided. Because of function overloading there can be several functions with slightly different parameters. Best way to avoid ambiguity is to use named parameters. @Composable fun TopAppBar( title: @Composable () -> Unit, modifier: Modifier = Modifier, navigationIcon: @Composable (() -> Unit)? = null, actions: @Composable RowScope.() -> Unit = {}, backgroundColor: Color = MaterialTheme.colors.primarySurface, contentColor: Color = contentColorFor(backgroundColor), elevation: Dp = AppBarDefaults.TopAppBarElevation ) closest one to yours is above and which can be set as TopAppBar( title = { Text(text = "Notes") }, actions = { Icon( imageVector = Icons.Default.Notifications, contentDescription = "Notif", ) } ) Or you can use this one @Composable fun TopAppBar( modifier: Modifier = Modifier, backgroundColor: Color = MaterialTheme.colors.primarySurface, contentColor: Color = contentColorFor(backgroundColor), elevation: Dp = AppBarDefaults.TopAppBarElevation, contentPadding: PaddingValues = AppBarDefaults.ContentPadding, content: @Composable RowScope.() -> Unit ) such as TopAppBar( // other params ) { Row(modifier = Modifier.fillMaxWidth()) { Text(text = "Notes") Spacer(modifier = Modifier.weight(1f)) Icon( imageVector = Icons.Default.Notifications, contentDescription = "Notif" ) } }
TopAppBar(title = { Text(text = "Notes") },actions = {Icon(imageVector =Icons.Default.Notifications,contentDescription = "Notif",)},) {} when I try running the above code I get the following error "None of the following functions can be called with the arguments supplied." When I look into the declaration of TopAppBar , there are two Composables of same name however only the Composable which I want cannot be used ! Any tips?
Kotlin Serialization @SerialName not working for Boolean
You are mixing the Gson and Kotlin annotation types - Gson uses @SerializedName not @SerialName. I am not sure how your string types even work in that case (maybe something in how you call Gson that isn't included in the question). As an example, the first class here (Person) can be serialized with the Kotlin serialization library, the second with Gson: Kotlin annotations @Serializable data class Person ( @SerialName("first_name") val firstName: String? = null, @SerialName("last_name") val lastName: String? = null, val age: Int? = null, @SerialName("can_sing") val canSing: Boolean? = null ) Gson Annotations data class PersonGson ( @SerializedName("first_name") val firstName: String? = null, @SerializedName("last_name") val lastName: String? = null, val age: Int? = null, @SerializedName("can_sing") val canSing: Boolean? = null ) Examples Running this unit test with the Kotlin serialization library: @Test fun testJsonKotlin() { val test = Person("hello", "world", 42, false) val json = Json.encodeToString(test) println(json) val t2 = Json.decodeFromString<Person>(json) println(t2) } produces the expected output: {"first_name":"hello","last_name":"world","age":42,"can_sing":false} Person(firstName=hello, lastName=world, age=42, canSing=false) Doing that with Gson @Test fun testJsonGsonMixed() { val testp = Person("hello", "world", 42, false) val json = Gson().toJson(testp) println(json) val t2 = Gson().fromJson(json, Person::class.java) println(t2) } technically works, but ignores the serialized name annotations (for all the cases, not just the boolean) {"firstName":"hello","lastName":"world","age":42,"canSing":false} Person(firstName=hello, lastName=world, age=42, canSing=false) Using the Gson-annotated class with Gson @Test fun testJsonGson() { val test = PersonGson("hello", "world", 42, false) val json = Gson().toJson(test) println(json) val t2 = Gson().fromJson(json, PersonGson::class.java) println(t2) } gives the correct response again {"first_name":"hello","last_name":"world","age":42,"can_sing":false} PersonGson(firstName=hello, lastName=world, age=42, canSing=false)
I'm using GSON to serialize some platform data. When I use @SerialName to capture platform data with a different naming convention in my app, it works for other types, but not Boolean types. As a simple example, if I have a class like... import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class Person ( @SerialName("first_name") val firstName: String? = null, @SerialName("last_name") val lastName: String? = null, val age: Int? = null ) ... everything works fine. The serializer finds first_name, last_name and age in the data and properly set the properties for the Person. However, when I try to add a Boolean... import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class Person ( @SerialName("first_name") val firstName: String? = null, @SerialName("last_name") val lastName: String? = null, val age: Int? = null, @SerialName("can_sing") val canSing: Boolean? = null ) ... the serializer does not catch and assign can_sing. It is strange that it works with a String but not a Boolean. Can any explain why I am seeing this behavior? I can work around this (for example, I can do val can_sing: Boolean? = null and it works), but I'm just wonder why @SerialName doesn't seem to work for a Boolean, or if I'm just missing something obvious.
Android auto manifest merger failed: attribute is also present at
Since you are targeting Android Automotive in your manifest, you can get rid of the following dependency in your gradle file: implementation("androidx.car.app:app-projected:1.1.0") That should fix the conflict you are having.
I'm currently trying to build a hello world app as my first android auto app. Earlier, when I was trying to run the app it was giving me some minSdk error and I managed to fix that. Now, when I try to run it, it gives me this error: Manifest merger failed : Attribute meta-data#androidx.car.app.CarAppMetadataHolderService.CAR_HARDWARE_MANAGER@value value=(androidx.car.app.hardware.ProjectedCarHardwareManager) from [androidx.car.app:app-projected:1.1.0] AndroidManifest.xml:34:17-86 is also present at [androidx.car.app:app-automotive:1.1.0] AndroidManifest.xml:44:17-87 value=(androidx.car.app.hardware.AutomotiveCarHardwareManager). Suggestion: add 'tools:replace="android:value"' to <meta-data> element at AndroidManifest.xml to override. I've been trying to follow the instructions here on how to edit the manifest file and everything looks fine according to the instructions. Here's the AndroidManifest.xml: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="com.smartherd.helloworld"> <uses-feature android:name="android.hardware.type.automotive" android:required="true" /> <application android:allowBackup="true" android:appCategory="audio" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.HelloWorld"> <service android:name=".HelloWorldService" android:exported="true"> <intent-filter> <action android:name="androidx.car.app.CarAppService"/> <category android:name="androidx.car.app.category.POI"/> </intent-filter> </service> <meta-data android:name="androidx.car.app.minCarApiLevel" android:value="1"/> </application> </manifest> Build.gradle: plugins { id 'com.android.application' id 'org.jetbrains.kotlin.android' } android { compileSdk 32 defaultConfig { applicationId "com.smartherd.helloworld" minSdk 29 targetSdk 32 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } dependencies { implementation("androidx.car.app:app:1.1.0") // For Android Auto specific functionality implementation("androidx.car.app:app-projected:1.1.0") // For Android Automotive specific functionality implementation("androidx.car.app:app-automotive:1.1.0") // For testing testImplementation("androidx.car.app:app-testing:1.2.0-rc01") implementation 'androidx.core:core-ktx:1.7.0' implementation 'androidx.appcompat:appcompat:1.4.2' testImplementation 'junit:junit:4.13.2' androidTestImplementation 'androidx.test.ext:junit:1.1.3' androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' }
Adding spacing between BottomNavigationItem's icon & label
I don't think you can do it using a BottomNavigationItem. The Material Design Library for Compose follows the Material Design Specification as you can see here. But you don't need to use a BottomNavigationItem to display the items in your BottomAppBar. You can use any composable, like below: Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .weight(1f) .clickable { navController.navigate(navItem.route) }) { val color = if (currentRoute == navItem.route) LocalContentColor.current else LocalContentColor.current.copy(alpha = ContentAlpha.medium) Icon( painter = painterResource(id = navItem.icon), navItem.label, tint = color ) // Set the space that you want... Spacer(modifier = Modifier.height(4.dp)) Text(text = navItem.label, color = color, fontSize = 12.sp) } However, as I mentioned above, the library follows the Material Design specs, which define the BottomAppBar's height as 56dp. Therefore, if you want something more custom, you need to it by your own (using a Row, for instance).
I'm trying to build out my Bottom navigation like this: @Composable fun BottomNavBar(navController: NavController) { Column( Modifier.background(colorResource(id = R.color.pastel_orange_white)) ) { BottomNavigation( modifier = Modifier .defaultMinSize(minHeight = 70.dp), backgroundColor = colorResource(id = R.color.bottom_nav_dark) ) { val navItems = arrayOf( BottomNavItem( stringResource(id = R.string.title_home), R.drawable.ic_home, Screen.Home.route ), BottomNavItem( stringResource(id = R.string.subjects_title), R.drawable.ic_subject, Screen.Subjects.route ), BottomNavItem( stringResource(id = R.string.grades_title), R.drawable.ic_grade, Screen.Grades.route ), BottomNavItem( "H/W", R.drawable.ic_assignments, Screen.Assignments.route ) ) // observe the backstack val navBackStackEntry by navController.currentBackStackEntryAsState() // observe current route to change the icon // color,label color when navigated val currentRoute = navBackStackEntry?.destination?.route navItems.forEach { navItem -> BottomNavigationItem( selected = currentRoute == navItem.route, onClick = { navController.navigate(navItem.route) }, icon = { Box( Modifier .width(70.dp) .height(30.dp) .background( colorResource(id = if (currentRoute == navItem.route) R.color.bottom_nav_light else R.color.bottom_nav_dark), RoundedCornerShape(32.dp) ), contentAlignment = Alignment.Center ) { Icon( painter = painterResource(id = navItem.icon), contentDescription = navItem.label, tint = colorResource(id = R.color.black) ) } }, label = { Text(text = navItem.label, fontSize = 14.sp) }, alwaysShowLabel = true, selectedContentColor = colorResource(id = R.color.black), unselectedContentColor = colorResource(id = R.color.black) ) } } } } I need to add some extra space between the label and the icon parts, since I'm applying a small background color to the selected item. I tried with paddings, column arrangements, etc. but didn't find something that actually affected the spacing. Any pointers?
My app with PROCESS_TEXT intent does not appear in all apps' copy-paste menu
After researching, I found the following: This intent-filter must be added to the activity. I have tested it with Android 11 and Android 12. AndroidManifest.xml: <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="http" /> <data android:scheme="https" /> </intent-filter>
I am trying to extend the copy/paste menu to open a specific activity in my app. The problem is, that my app appears in some applications, and in most of them do not. AndroidManifest.xml: <manifest ....> <queries> <intent> <action android:name="android.intent.action.PROCESS_TEXT" /> <data android:mimeType="text/plain" /> </intent> <intent> <action android:name="android.intent.action.SEND" /> <data android:mimeType="text/plain" /> </intent> <intent> <action android:name="android.intent.action.VIEW" /> <data android:mimeType="text/plain"/> </intent> </queries> <application ...> <activity android:name=".component.popupActivity.PopUpActivity" android:exported="true" android:theme="@style/Theme.Transparent.SemiBlack"> <intent-filter> <action android:name="android.intent.action.PROCESS_TEXT" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="text/plain" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.SEND" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="text/plain" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.BROWSABLE" /> <category android:name="android.intent.category.DEFAULT" /> <data android:scheme="http" /> <data android:scheme="https" /> <data android:mimeType="text/html"/> <data android:mimeType="text/plain"/> <data android:mimeType="application/xhtml+xml"/> </intent-filter> </activity> </application> </manifest> Is there anything wrong with my implementation? I have tested it with WhatsApp, Instagram, Facebook, FB messenger. Only works with Whatsapp. Other apps like Translate, Outlook, idealo Shopping, Firefox Focus. was always able to add their apps to the copy/paste menu. Firefox Focus is open source, I did not notice anything different in AndroidManifest.xml
Debug Console: Error: ADB exited with exit code 1 Performing Streamed Install... F
So I found the solution: Open Android Studio Open Virtual Device Manager Find your emulator and go Edit(Virtual Device Configuration) Show Advanced Settings Scroll down and find Interal Storage(for me it was by default 800MB) Set how many MB you want to emulator have ( I putted 6000MB and it works fine) Hope it helps! P.S It may take some time to emulator reloads after changes! Be patient :D
I am trying to run app on Android Emulator and it's saying that INSTALL_FAILED_INSUFFICIENT_STORAGE] but when I wipe data from AVD and restart VS Code and try again, sam error.. Sometimes I go flutter clean and flutter pub get and sometimes work but sometimes don't. I tried to do every solution that people posted previously in their similar problems but solutions don't work. When I use Windows10 on my PC I am not having this problem but on my Mackbook Air 2020 I am facing this on all projects. P.S This is new project(blank template). flutter run Using hardware rendering with device sdk gphone64 arm64. If you notice graphics artifacts, consider enabling software rendering with "--enable-software-rendering". Launching lib/main.dart on sdk gphone64 arm64 in debug mode... Running Gradle task 'assembleDebug'... 12.9s ✓ Built build/app/outputs/flutter-apk/app-debug.apk. Installing build/app/outputs/flutter-apk/app.apk... 689ms Error: ADB exited with exit code 1 Performing Streamed Install adb: failed to install /Users/harunbegic/Desktop/dev/flutter/login_authh/build/app/outp uts/flutter-apk/app.apk: Failure [INSTALL_FAILED_INSUFFICIENT_STORAGE] Error launching application on sdk gphone64 arm64. ```
How to keep bottom sheet in backstack when navigating forward?
This is not possible. As per the Navigation and the back stack documentation: Dialog destinations implement the FloatingWindow interface, indicating that they overlay other destinations on the back stack. As such, one or more FloatingWindow destinations can be present only on the top of the navigation back stack. Navigating to a destination that does not implement FloatingWindow automatically pops all FloatingWindow destinations off of the top of the stack. This ensures that the current destination is always fully visible above other destinations on the back stack. Bottom sheet destinations are also FloatingWindow destinations that float above the other destinations. As such, it is expected that they are automatically popped off the back stack when you navigate to anything other than another dialog or bottomSheet destination.
I am using Accompanist Bottom Sheet Destinations in my project. The setup is exactly the same as shown in docs. @Composable fun MyApp() { val bottomSheetNavigator = rememberBottomSheetNavigator() val navController = rememberNavController(bottomSheetNavigator) ModalBottomSheetLayout(bottomSheetNavigator) { NavHost(navController, Destinations.Home) { composable(route = "home") { HomeScreen( openBottomSheet = { navController.navigate("sheet") } ) } bottomSheet(route = "sheet") { MyBottonSheet( navigateToSomeRoute = { navController.navigate("some_route") } ) } composable(route = "some_route") { SomeComposable( onBackPress = { navController.navigateUp() } ) } } } } Here I have a button in MyBottomSheet which opens the SomeComposable screen. But when I navigateUp from there, I reach HomeScreen i.e. the bottom sheet was popped off the backstack when I navigated away from it. How can I keep my bottom sheet in the backstack so that when I press Back in SomeComposable I go back to the previous state with MyBottonSheet open (on top of HomeScreen)?
Why it says " List contains no element matching the predicate." for android jetpack compose?
I think the problem is that you are calling navController.navigate("main") during composition while not ensuring that it is called only once when the navigation should happen, thus creating a situation where navController.navigate("main") is called repeatedly in quick succession. I think that might be the cause and the exception might be the effect. Wrap the navigation call (that is now directly part of the composition) into a LaunchedEffect if (!sharedPreferences.getBoolean("firstTime", true)) { LaunchedEffect(Unit) { navController.navigate("main") } } else { val editor = sharedPreferences.edit() editor.putBoolean("firstTime", false) editor.apply() }
I have Onboarding Screens for my project, and it work correctly, but I want to show users it just once, and I was using shared preferences for it, and when debug the project it is throw an error like that in logcat, List contains no element matching the predicate. , and in android emulator I can see main screen, but app crash quickly, when I open app again on simulator, onboarding screen shows just 1 second and open main screen, than app crash, I do not know why? I guess problem is because of this line of code, if (!sharedPreferences.getBoolean("firstTime", true)) { navController.navigate("main") }else{ but I am not sure. mainscreen: @Composable fun MainScreen( navController: NavController, ) { Column( Modifier .fillMaxSize() , horizontalAlignment = Alignment.CenterHorizontally ) { Text( "WELCOME TO", modifier = Modifier .width(300.dp) , textAlign = TextAlign.Start, fontSize = 15.sp, color = custom, fontWeight = FontWeight.Medium ) } nav: @OptIn(ExperimentalPagerApi::class) @Composable fun NavScreen( sharedPreferences: SharedPreferences ) { val navController = rememberNavController() NavHost(navController = navController, startDestination = "onBoard") { composable("onBoard", ) { OnBoardScreen(navController = navController, sharedPreferences) } composable("main") { MainScreen(navController = navController) } } viewmodel: class OnBoardViewModel ( ) : ViewModel() { private val _currentPage = MutableStateFlow(0) val currentPage: StateFlow<Int> get() = _currentPage fun setCurrentPage(currentPage: Int) { _currentPage.value = currentPage } } MainActivity: @AndroidEntryPoint class MainActivity : ComponentActivity( ) { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { CustomTheme { Surface(color = MaterialTheme.colors.background) { val sharedPreferences = getSharedPreferences("onBoardingScreen", MODE_PRIVATE) NavScreen(sharedPreferences) } } } } } @ExperimentalPagerApi @Composable fun OnBoardScreen( navController: NavController, sharedPreferences: SharedPreferences ) { val scaffoldState = rememberScaffoldState() val onBoardViewModel : OnBoardViewModel = viewModel() val currentPage = onBoardViewModel.currentPage.collectAsState() val pagerState = rememberPagerState( pageCount = onBoardItem.size, initialOffscreenLimit = 2, initialPage = 0, infiniteLoop = false ) Scaffold( modifier = Modifier.fillMaxSize(), scaffoldState = scaffoldState ) { Surface( modifier = Modifier.fillMaxSize() ) { if (!sharedPreferences.getBoolean("firstTime", true)) { navController.navigate("main") }else{ val editor = sharedPreferences.edit() editor.putBoolean("firstTime", false) editor.apply() } LaunchedEffect(Unit) { onBoardViewModel.currentPage .collect { pagerState.animateScrollToPage( page = currentPage.value ) } } Box( modifier = Modifier .fillMaxWidth() .background( brush = Brush.verticalGradient( colors = listOf( white, grey ) ) ) ) { Column( horizontalAlignment = Alignment.CenterHorizontally ) { HorizontalPager( state = pagerState ) { page -> Column( modifier = Modifier .padding(top = 60.dp) .fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = onBoardItem[page].desc, modifier = Modifier .padding(30.dp), color = custom, fontSize = 18.sp, textAlign = TextAlign.Center ) Spacer(modifier = Modifier.padding(10.dp)) Image( painter = painterResource(id = onBoardItem[page].image), contentDescription = "OnBoardImage", modifier = Modifier .height(500.dp) .fillMaxWidth(), ) } } PagerIndicator(onBoardItem.size, pagerState.currentPage) } Box( modifier = Modifier .align(Alignment.BottomCenter) ) { Row( modifier = Modifier .padding(bottom = 30.dp) .fillMaxWidth(), horizontalArrangement = if (pagerState.currentPage != 2 ) { Arrangement.SpaceBetween } else { Arrangement.Center } ) { if (pagerState.currentPage == 2) { CompositionLocalProvider(LocalRippleTheme provides NoRippleTheme) { Text( text = "Start", color = custom, modifier = Modifier .padding(start = 280.dp, bottom = 40.dp) .clickable { navController.navigate("main") }, fontSize = 18.sp, fontWeight = FontWeight.Medium ) } } else { CompositionLocalProvider(LocalRippleTheme provides NoRippleTheme) { Text( text = "Skip", color = custom, modifier = Modifier .padding(start = 25.dp, bottom = 42.dp) .clickable { navController.navigate("main") }, fontSize = 18.sp, fontWeight = FontWeight.Medium ) } CompositionLocalProvider(LocalRippleTheme provides NoRippleTheme) { Text( text = "Next", color = custom, modifier = Modifier .clickable { onBoardViewModel.setCurrentPage(pagerState.currentPage + 1) } .padding(end = 25.dp, bottom = 42.dp), fontSize = 18.sp, fontWeight = FontWeight.Medium ) } } } } } } } } @Composable fun PagerIndicator(size: Int, currentPage: Int) { Row( horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.padding(top = 40.dp) ) { repeat(size) { IndicateIcon( isSelected = it == currentPage ) } } } @Composable fun IndicateIcon(isSelected: Boolean) { val width = animateDpAsState( targetValue = if (isSelected) 10.dp else 10.dp ) Box( modifier = Modifier .padding(2.dp) .height(10.dp) .width(width.value) .clip(CircleShape) .background( if (isSelected) custom else customColor ) ) }
How can we move "tab indicator" of Tab layout to top in "jetpack compose"? By default it is appearing at bottom of selected tab
There isn't a parameter to do that. It is a workaround. Currently the tab height is defined by private val SmallTabHeight = 48.dp. //only text private val LargeTabHeight = 72.dp. //text + icon You can define your own indicator applying an offset: @Composable fun TopIndicator(color: Color, modifier: Modifier = Modifier) { Box( modifier .fillMaxWidth() .offset(y= (-46).dp) //SmallTabHeight=48.dp - height indicator=2.dp .height(2.dp) .background(color = color) ) } and in your code: // Reuse the default offset animation modifier, but use our own indicator val indicator = @Composable { tabPositions: List<TabPosition> -> TopIndicator(Color.White, Modifier.tabIndicatorOffset(tabPositions[state])) } TabRow( selectedTabIndex = state, indicator = indicator ){ //... }
TabRow( selectedTabIndex = tabIndex, modifier = Modifier .fillMaxWidth() .wrapContentHeight(), indicator = {tabPositions-> Box( modifier = Modifier .tabIndicatorOffset(tabPositions[tabIndex]) .height(indicatorSize) .background(color = indicatorColor) ) } ) Can we add anything in indicator to move it to top? I couldn't see similar to this "app:tabIndicatorGravity" in jetpack compose.
Why does a call to a logic method on a ViewModel with StateFlow as a property cause a recomposition even though the value has not changed?
There are a couple of things going on here. First, the Compose compiler does not automatically memoize lambdas that capture unstable types. Your ViewModel is an unstable class and as such capturing it by using it inside the onClick lambda means your onClick will be recreated on every recomposition. Because the lambda is being recreated, the inputs to CCompose are not equal across recompositions, therefore CCompose is recomposed. This is the current behaviour of the Compose compiler but it is very possible this will change in the future as we know this is a common situation we could do better in. If you want to workaround this behaviour, you can memoize the lambda yourself. This could be done by remembering it in composition e.g. val cComposeOnClick = remember(viewModel) { { viewModel.increaseCount() } } CCompose(onClick = cComposeOnClick) or change your ViewModel to have a lambda rather than a function for increaseCount. class MyViewModel { val increaseCount = { ... } } or you could technically annotate your ViewModel class with @Stable but I probably wouldn't recommend this because maintaining that stable contract correctly would be quite difficult. Doing either of these would allow CCompose to be skipped. But I would also like to mention that if CCompose is just a small composable then 1 extra recomposition probably doesn't actually have much effect on the performance of your app, you would only apply these fixes if it was actually causing you an issue. Stability is quite a large topic, I would recommend reading this post for more info.
This application counts up A when C is pressed. Since A is the only one that has changed, I expected the recomposition to be just that. But C is also recomposition. Here is the code. ViewModel exposes StateFlow. class MainViewModel : ViewModel() { private val _count: MutableStateFlow<Int> = MutableStateFlow(0) val count: StateFlow<Int> = _count.asStateFlow() fun increaseCount() { _count.value++ } } CCompose calls increaseCount(). @Composable fun CountUpScreen( modifier: Modifier = Modifier, viewModel: MainViewModel = viewModel(), ) { val count: Int by viewModel.count.collectAsState() SideEffect { println("CountUpScreen") } Column( modifier = modifier.fillMaxSize(), verticalArrangement = Arrangement.SpaceEvenly, horizontalAlignment = Alignment.CenterHorizontally, ) { ACompose( count = count ) BCompose() CCompose { viewModel.increaseCount() } } } @Composable private fun ACompose(count: Int) { SideEffect { println("ACompose") } Column(modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) { Text( text = "$count" ) } } @Composable private fun BCompose() { SideEffect { println("BCompose") } Text( text = "I am composable that will not be recompose" ) } @Composable private fun CCompose(onClick: () -> Unit) { SideEffect { println("CCompose") } Button(onClick = { onClick() }) { Icon(Icons.Outlined.Add, contentDescription = "+") } } The following are the results of the logs that were made to count up. I/System.out: CountUpScreen I/System.out: ACompose I/System.out: CCompose Why is CCompose recomposed?
Kotlin PendingIntent with FLAG_IMMUTABLE does't work with exoplayer
As suggested by @ianhanniballake, the crash was happening in the exoplayer dependency and not in my code... So i went on https://github.com/google/ExoPlayer/blob/release-v2/RELEASENOTES.md to check all exoplayer update and i found out where they implemented PendingIntent.FLAG_IMMUTABLE funny thing it on 2.14.2 just one iteration above the one i was using. So i updated the dependency to exoplayer and everything work.
I'am using a pending intent to make a notification bar when i play a song in my music app. it used to work perfectly but i have to update my targetSdk to 31 and i run into an error telling me that i need to use some flag with my pendingIntent : Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent. Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles. Problem is that i use this flag when i declare my pending intent : val pendingIntent = PendingIntent.getActivity( applicationContext, 0, packageManager?.getLaunchIntentForPackage(packageName), PendingIntent.FLAG_IMMUTABLE ) So i don't get why it say that i need to use the flag when i already using it ? Am I missing something ? EDIT Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles. at android.app.ActivityThread.handleCreateService(ActivityThread.java:4953) at android.app.ActivityThread.access$1900(ActivityThread.java:310) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2300) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loopOnce(Looper.java:226) at android.os.Looper.loop(Looper.java:313) at android.app.ActivityThread.main(ActivityThread.java:8663) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:567) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135) Caused by: java.lang.IllegalArgumentException: info.cairn.pro: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent. Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles. at android.app.PendingIntent.checkFlags(PendingIntent.java:382) at android.app.PendingIntent.getBroadcastAsUser(PendingIntent.java:673) at android.app.PendingIntent.getBroadcast(PendingIntent.java:660) at com.google.android.exoplayer2.ui.PlayerNotificationManager.createBroadcastIntent(PlayerNotificationManager.java:1601) at com.google.android.exoplayer2.ui.PlayerNotificationManager.createPlaybackActions(PlayerNotificationManager.java:1557) at com.google.android.exoplayer2.ui.PlayerNotificationManager.<init>(PlayerNotificationManager.java:862) at com.google.android.exoplayer2.ui.PlayerNotificationManager.<init>(PlayerNotificationManager.java:793) at com.google.android.exoplayer2.ui.PlayerNotificationManager.<init>(PlayerNotificationManager.java:757) at com.google.android.exoplayer2.ui.PlayerNotificationManager.createWithNotificationChannel(PlayerNotificationManager.java:729) at com.viapresse.presskit.exoplayer.MusicNotificationManager.<init>(MusicNotificationManager.kt:29) at com.viapresse.presskit.exoplayer.MusicService.onCreate(MusicService.kt:114) at android.app.ActivityThread.handleCreateService(ActivityThread.java:4940)
How do you remove extra zeros at the end of a decimal in Kotlin?
Once you have converted the number to a string with up to 2 decimal places (as you are doing), you can use dropLastWhile to drop trailing zeros and decimal places. Here is an example fun prettyFormat(input: Double): String { if( input == 0.0 ) return "0" val prefix = if( input < 0 ) "-" else "" val num = abs(input) // figure out what group of suffixes we are in and scale the number val pow = floor(log10(num)/3).roundToInt() val base = num / 10.0.pow(pow * 3) // Using consistent rounding behavior, always rounding down since you want // 999999999 to show as 999.99M and not 1B val roundedDown = floor(base*100)/100.0 // Convert the number to a string with up to 2 decimal places var baseStr = BigDecimal(roundedDown).setScale(2, RoundingMode.HALF_EVEN).toString() // Drop trailing zeros, then drop any trailing '.' if present baseStr = baseStr.dropLastWhile { it == '0' }.dropLastWhile { it == '.' } val suffixes = listOf("","k","M","B","T") return when { pow < suffixes.size -> "$prefix$baseStr${suffixes[pow]}" else -> "${prefix}infty" } } This produces 11411.0 = 11.41k 11000.0 = 11k 9.99996E8 = 999.99M 12.4 = 12.4 0.0 = 0 -11400.0 = -11.4k If you don't care about zero or negative numbers it can be simplified a bit.
I'm creating a function that rounds large numbers over 1,000 and then returns a string of that rounded number. For example, "2374293" would return as "2.37m" However, I dont want any extra zeros at the end of decimals like "25.00" or "100.50". For Example: What I want: Input -> Output "11000" -> "11k" "11400" -> "11.4k" What I get: Input -> Output "11000" -> "11.00k" "11400" -> "11.40k" How would I remove these zeros and decimal point(if it's a whole number) when needed? Here is my code currently: private fun roundBigNumb(numb: Long): String { val newNumb = numb.toDouble() return when { numb in 1000..999994 -> { BigDecimal(newNumb/1000).setScale(2, RoundingMode.HALF_EVEN).toString()+"k" } numb in 999995..999999 -> { "999.99k" } numb in 1000000..999994999 -> { BigDecimal(newNumb/1000000).setScale(2, RoundingMode.HALF_EVEN).toString()+"m" } numb in 999995000..999999999 -> { "999.99m" } numb in 1000000000..999994999999 -> { BigDecimal(newNumb/1000000000).setScale(2, RoundingMode.HALF_EVEN).toString()+"b" } numb in 999995000000..999999999999 -> { "999.99b" } numb in 1000000000000..999994999999999 -> { BigDecimal(newNumb/1000000000000).setScale(2, RoundingMode.HALF_EVEN).toString()+"t" } numb in 999995000000000..999999999999999 -> { "999.99t" } numb >= 1000000000000000 -> "∞" else -> numb.toString() } }
RoomDB: Migration without schema changes, I just want to drop the old Database and create from asset
I would suggest that the way to go is to detect the change in the asset. Copying the asset and then comparing rows would be relatively inefficient. A more efficient approach, although a bit more complicated to manage would be to utilise the SQLITE USER_VERSION (or the APPLICATION_ID). This would entail setting the value in the latest asset to be greater than it was. A changed (increased) USER_VERSION can be detected by just accessing the files (the current database and the asset) and reading the first 100 bytes and then extracting the 4 bytes at offset 60 (68 for the Application Id). You can set the values using PRAGMA user_version = n for the USER_VERSION or (PRAGMA application_id = n) for the APPLICATION_ID via whatever tool you are using to maintain the database externally. You would do this every time you instantiate the Database class BEFORE you build the database. If the asset version is greater (changed) then you delete the database and thus when the build is actioned then createFromAsset will copy the database from the asset. I would suggest maintaining the database version in-line with the asset (although unlike the SQLite which would thrown an exception on a downgrade API Room doesn't seem to care about downgrade). Here's a working example. For the testing two asset databases have been created. The first (in the asset folder as V1Base) has rows with id's 1-5 inclusive and the second column name has V1 within the name. The second (in the asset folder as V2Base) has id's 2 and 4 from the first (1,3 and 5 have been deleted) and an additional 3 rows, id's 6, 8 and 10 and the name includes V2. The asset folder (after the 2nd test run):- Obviously you would only have the 1 asset. However, for experimentation/testing/debugging the above allows easy manipulation of the files. as the arrows show V1Base was copied to what is now INIT_DB.sqlite3_ORIGINAL (first run it was named INIT_DB.sqlite3) and V2Base was copied (after renaming INIT_DB.sqlite3 to INIT_DB.sqlite3_ORIGINAL) to INIT_DB.sqlite3 Only a single @Entity class was used that being TheTable :- @Entity class TheTable { @PrimaryKey Long id=null; String name; } An @Dao interface with just a method to extract the data TheTableDao:- @Dao interface TheTableDao { @Query("SELECT * FROM thetable") List<TheTable> getAllTheTableRows(); } A little more complex than normal @Database annotated abstract class TheDatabase :- @Database(entities = {TheTable.class}, version = MainActivity.DATABASE_VERSION,exportSchema = false) abstract class TheDatabase extends RoomDatabase { abstract TheTableDao getTheTableDao(); /* see https://www.sqlite.org/fileformat.html */ private static int SQLITE_HEADER_DATA_LENGTH = 100; private static int SQLITE_HEADER_USERVERSION_OFFSET = 60; private static int SQLITE_HEADER_USERVERSION_LENGTH = 4; private volatile static TheDatabase instance=null; static TheDatabase getInstance(Context context) { if (instance == null) { if (isNewAsset(context,MainActivity.ASSET_NAME,MainActivity.DATABASE_NAME)) { context.getDatabasePath(MainActivity.DATABASE_NAME).delete(); } instance = Room.databaseBuilder(context,TheDatabase.class,MainActivity.DATABASE_NAME) .allowMainThreadQueries() //.fallbackToDestructiveMigration() .createFromAsset(MainActivity.ASSET_NAME,ppcb) .addMigrations(v1_v2) .addCallback(cb) .build(); } return instance; } static Migration v1_v2 = new Migration(1,2) { @Override public void migrate(@NonNull SupportSQLiteDatabase database) { Log.d("MIGV1->V2","Invoked Migration from V1 to V2"); } }; static Callback cb = new Callback() { @Override public void onCreate(@NonNull SupportSQLiteDatabase db) { super.onCreate(db); Log.d("CALLBACK","OnCreate Called"); } @Override public void onDestructiveMigration(@NonNull SupportSQLiteDatabase db) { super.onDestructiveMigration(db); Log.d("CALLBACK","OnDestructiveMigration Called"); } @Override public void onOpen(@NonNull SupportSQLiteDatabase db) { super.onOpen(db); Log.d("CALLBACK","OnOpen Called"); } }; static PrepackagedDatabaseCallback ppcb = new PrepackagedDatabaseCallback() { @Override public void onOpenPrepackagedDatabase(@NonNull SupportSQLiteDatabase db) { super.onOpenPrepackagedDatabase(db); Log.d("PPCALLBACK","PrepackagedDatabase Called"); } }; private static boolean isNewAsset(Context context, String asset, String dbname) { File current_Db = context.getDatabasePath(dbname); if(!current_Db.exists()) return false; /* No Database then nothing to do */ int current_Db_version = getDBVersion(current_Db); Log.d("DBINFO","isNewAsset has determined that the current database version is " + current_Db_version); if (current_Db_version < 0) return false; /* No valid version */ int asssetVersion = getAssetVersion(context,asset); Log.d("DBINFO","isNewAsset has determined that the asset version is " + asssetVersion); if (asssetVersion > current_Db_version) { Log.d("DBINFO","isNewAsset has found that the asset version is greater than the current db version " + current_Db_version); return true; } else { Log.d("DBINFO","isNewAsset has found that the asset version is unchanged " + current_Db_version); } return false; } private static int getDBVersion(File f) { int rv = -1; byte[] buffer = new byte[SQLITE_HEADER_DATA_LENGTH]; InputStream is; try { is = new FileInputStream(f); is.read(buffer,0,buffer.length); is.close(); rv = getVersionFromBuffer(buffer); } catch (IOException e) { e.printStackTrace(); } return rv; } private static int getAssetVersion(Context context,String asset) { int rv = -1; byte[] buffer = new byte[SQLITE_HEADER_DATA_LENGTH]; InputStream is; try { is = context.getAssets().open(asset); is.read(buffer,0,buffer.length); is.close(); rv = getVersionFromBuffer(buffer); } catch (IOException e) { e.printStackTrace(); } return rv; } static int getVersionFromBuffer(byte[] buffer) { int rv = -1; if (buffer.length == SQLITE_HEADER_DATA_LENGTH) { ByteBuffer bb = ByteBuffer.wrap(buffer,SQLITE_HEADER_USERVERSION_OFFSET,SQLITE_HEADER_USERVERSION_LENGTH); return bb.getInt(); } return rv; } } Notes Although .allowMainThreadQueries has been used, this is just for convenience, no reliance is made upon it's use. what is important is the placement of the call of isNewAsset, this should be before the build. the code is complicated by callbacks (suggested as it's then easier to understand what is going on; remove them when happy) likewise some Logging see the reference to the SQLite documentation regarding the header. Last but not least and Activity to demonstrate MainActivity public class MainActivity extends AppCompatActivity { public static final int DATABASE_VERSION = 1; public static final String DATABASE_NAME = "INIT_DB.sqlite3"; public static final String ASSET_NAME = "db/" + DATABASE_NAME; TheDatabase db; TheTableDao dao; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); db = TheDatabase.getInstance(this); dao = db.getTheTableDao(); Log.d("DBINFO","Extracting data"); for (TheTable tt: dao.getAllTheTableRows()) { Log.d("DBINFO","ID= " + tt.id + " NAME= " + tt.name); } } } nothing special. However, constants placed here as it seemed more convenient for testing. First Run all assets bar V1Base.db and V2Base.db deleted. the App uninstalled if it existed. VB1Base.db copied and pasted as INIT_DB.sqlite3. DATABASE_VERSION set to 1. Run and the log includes :- 2022-06-12 09:50:37.804 D/DBINFO: Extracting data 2022-06-12 09:50:37.849 D/PPCALLBACK: PrepackagedDatabase Called 2022-06-12 09:50:37.905 D/CALLBACK: OnOpen Called 2022-06-12 09:50:37.910 D/DBINFO: ID= 1 NAME= V1Data001 2022-06-12 09:50:37.910 D/DBINFO: ID= 2 NAME= V1Data002 2022-06-12 09:50:37.911 D/DBINFO: ID= 3 NAME= V1Data003 2022-06-12 09:50:37.911 D/DBINFO: ID= 4 NAME= V1Data004 2022-06-12 09:50:37.911 D/DBINFO: ID= 5 NAME= V1Data005 Second Run Renamed INIT_DB.sqlite3 to INIT_DB.sqlite3_ORIGINAL. Copied and pasted V2Base.db to INIT_DB.sqlite3. DATABASE_VERSION changed to 2. Run and the log includes :- 2022-06-12 09:58:29.484 D/DBINFO: isNewAsset has determined that the current database version is 1 2022-06-12 09:58:29.484 D/DBINFO: isNewAsset has determined that the asset version is 2 2022-06-12 09:58:29.484 D/DBINFO: isNewAsset has found that the asset version is greater than the current db version 1 2022-06-12 09:58:29.521 D/DBINFO: Extracting data 2022-06-12 09:58:29.560 D/PPCALLBACK: PrepackagedDatabase Called 2022-06-12 09:58:29.571 D/MIGV1->V2: Invoked Migration from V1 to V2 2022-06-12 09:58:29.617 D/CALLBACK: OnOpen Called 2022-06-12 09:58:29.622 D/DBINFO: ID= 2 NAME= V1Data002 2022-06-12 09:58:29.622 D/DBINFO: ID= 4 NAME= V1Data004 2022-06-12 09:58:29.622 D/DBINFO: ID= 6 NAME= V2Data001 2022-06-12 09:58:29.622 D/DBINFO: ID= 8 NAME= V2Data002 2022-06-12 09:58:29.622 D/DBINFO: ID= 10 NAME= V2Data003 As can be seen this time (as the database exists) the versions are obtained, the change has been detected and thus the original database file has been deleted AND the data is now, as expected, from the newer asset. Third Run As a test when there is no new/updated asset, the log includes :- 2022-06-12 11:23:57.249 D/DBINFO: isNewAsset has determined that the current database version is 2 2022-06-12 11:23:57.249 D/DBINFO: isNewAsset has determined that the asset version is 2 2022-06-12 11:23:57.250 D/DBINFO: isNewAsset has found that the asset version is unchanged 2 2022-06-12 11:23:57.287 D/DBINFO: Extracting data 2022-06-12 11:23:57.304 D/CALLBACK: OnOpen Called 2022-06-12 11:23:57.308 D/DBINFO: ID= 2 NAME= V1Data002 2022-06-12 11:23:57.308 D/DBINFO: ID= 4 NAME= V1Data004 2022-06-12 11:23:57.308 D/DBINFO: ID= 6 NAME= V2Data001 2022-06-12 11:23:57.308 D/DBINFO: ID= 8 NAME= V2Data002 2022-06-12 11:23:57.308 D/DBINFO: ID= 10 NAME= V2Data003 i.e. the asset and db are at the same level and the data remains as it was. Fourth Run App is uninstalled, so as per a new install, the log includes :- 2022-06-12 11:28:46.025 D/DBINFO: Extracting data 2022-06-12 11:28:46.073 D/PPCALLBACK: PrepackagedDatabase Called 2022-06-12 11:28:46.131 D/CALLBACK: OnOpen Called 2022-06-12 11:28:46.135 D/DBINFO: ID= 2 NAME= V1Data002 2022-06-12 11:28:46.135 D/DBINFO: ID= 4 NAME= V1Data004 2022-06-12 11:28:46.136 D/DBINFO: ID= 6 NAME= V2Data001 2022-06-12 11:28:46.136 D/DBINFO: ID= 8 NAME= V2Data002 2022-06-12 11:28:46.136 D/DBINFO: ID= 10 NAME= V2Data003 i.e. the latest asset is copied. Additional example of setting the USER_VERSION using DB Brwoser for SQLite Open the database file :- Optional but suggested check the current version (here it is 1):- Change the USER_VERSION to 2:- Note that there is no result in the result window but the log window shows that the command was successfully executed. Check the USER_VERSION (strongly suggested) :- SAVE (File/Close Database), quit DB Browser, restart DB Browser, Open the file and check the USER_VERSION again, then File/Close Database. Copy the amended file into the asset replacing (suggest renaming until checked) the previous asset.
My app doesn't need to keep user's custom data yet, all Data in Database is prepopulated via createFromAsset(). Now I want to make a version 2 that, when installed in device that already runs version 1, just drop all the data and feed it with createFromAsset() just like it already works for new installations. The point is version 2 has more data than version 1, but also some old data has been removed and replaced. Remember that user doesn't insert any data at all. I tried combining createFromAsset() with fallbackToDestructiveMigration() to no avail, even incrementing the schema version parameter in @Database annotation. db = Room.databaseBuilder(mCtx, AppDatabase.class, "AppDatabase") .fallbackToDestructiveMigration() .createFromAsset("db/INIT_DB.sqlite3") .build(); This would just delete the data when updating the app, but not repopulating from asset as I expected. What is the most simple way to just drop the old database and repopulate it? Must I use migrations for this, even though the DB schema is still the same? EDIT: After trying the Callbacks provided by @MikeT, if I install and run (by pressing Play on AndroidStudio) the "version2" of the App over an already installed "version1" (from the Google Play Store), the logs I obtain are as follows: First, with fallbackToDestructiveMigration(): 2022-06-13 XX:XX:XX.XXX 5859-5907/com.mydomain.myapp I/MYAPP_INFO: CALLBACK -> OnDestructiveMigration Called 2022-06-13 XX:XX:XX.XXY 5859-5907/com.mydomain.myapp I/MYAPP_INFO: CALLBACK -> OnOpen Called ...and now, providing the "empty migration" instead: 2022-06-13 XX:XX:XX.XXX 5859-5907/com.mydomain.myapp I/MYAPP_INFO: MIGRATION! Invoked Migration from V1 to V2 2022-06-13 XX:XX:XX.XXY 5859-5907/com.mydomain.myapp I/MYAPP_INFO: CALLBACK -> OnOpen Called The .fallbackToDestructiveMigration() approach just leads to the database getting empty when installing new version over the older, and the asset with the new DB data to be ignored. The approach in which I implement the empty migration (as well as the approach in which I try to check the "new version of the asset" and call delete() database from ctx), when installing new version over the older, just keeps using the old data, ignoring (once again) all the new data from the asset. And here comes the funny part: if, after launching the version2, I just hold my finger over my app's icon (OS level), "click" on "clean data" and then "delete all data" (emptying therefore the database itself), and then open the app again, the createFromAsset() kicks in!! The whole point is I'd like to spare final users the nuisance of deleting the old database themselves! In both cases, if the installation is done without previous version on the device, the .createFromAsset works as expected. FOR THE RECORD I am still using a single "asset name" for both versions of the app, and one single asset file: INIT_DB.db (is an SQLITE3 file anyway, but the SDK won't swallow it if I don't use .db extension... yet let's consider the "mock name" INIT_DB.sqlite3 in the code samples to be valid...
Google maps crashes in every screen that containing map ('int android.graphics.Bitmap.getWidth()' on a null object reference)
I fixed issue by adding implementation 'com.google.maps.android:android-maps-utils:2.3.0' in app level build.gradle Source
Suddenly Google maps crashes in every screen that containing map which cause app crash. AndroidRuntime: FATAL EXCEPTION: GLThread 56854 Process: com.interface_fze.dawana.pharmacy, PID: 3151 java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference at com.google.maps.api.android.lib6.gmm6.vector.gl.aj.b(:com.google.android.gms.dynamite_mapsdynamite@[email protected] (150400-0):11) at com.google.maps.api.android.lib6.gmm6.vector.gl.aj.<init>(:com.google.android.gms.dynamite_mapsdynamite@[email protected] (150400-0):3) at com.google.maps.api.android.lib6.gmm6.vector.gl.g.<init>(:com.google.android.gms.dynamite_mapsdynamite@[email protected] (150400-0):18) at com.google.maps.api.android.lib6.gmm6.vector.bs.d(:com.google.android.gms.dynamite_mapsdynamite@[email protected] (150400-0):14) at com.google.maps.api.android.lib6.gmm6.vector.av.run(:com.google.android.gms.dynamite_mapsdynamite@[email protected] (150400-0):44)
Implementing snapConfiguration to SliverPersistentHeader
I managed to solve the issue. Only thing I needed to do was providing vsync. For that I need to add with TickerProviderStateMixin to my code: class _CustomBodyState extends State<CustomBody> with TickerProviderStateMixin { and in the build method vsync: this: child: CustomScrollView( controller: _scrollController, slivers: [ SliverPersistentHeader(delegate: MyDelegate(minExtent: 0, maxExtent: kToolbarHeight, vsync: this), floating: true), const CustomSliverListTile(), ], ), and changed the MyDelegate as: class MyDelegate extends SliverPersistentHeaderDelegate { @override final double minExtent; @override final double maxExtent; @override final TickerProvider vsync; MyDelegate ({required this.minExtent, required this.maxExtent, required this.vsync}) : super(); @override Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) { return Container( child: const Text('Title', textAlign: TextAlign.center, style: TextStyle(fontSize: 24),), color: Colors.green, height: maxExtent, ); } @override bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) { return true; } @override FloatingHeaderSnapConfiguration get snapConfiguration => FloatingHeaderSnapConfiguration( curve: Curves.linear, duration: const Duration(milliseconds: 100), ); }
I am trying to implement snap feature to SliverPersistentHeader but couldn't figure it out and couldn't find a good documentation on this. My code: class MyDelegate extends SliverPersistentHeaderDelegate { double he; MyDelegate ({required this.he}) : super(); @override Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) { return AnimatedContainer( child: const Text('Title', textAlign: TextAlign.center, style: TextStyle(fontSize: 24),), color: Colors.green, height: he, duration: const Duration(milliseconds: 100), ); } @override double get maxExtent => kToolbarHeight; @override double get minExtent => 0; @override bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) { return true; } @override FloatingHeaderSnapConfiguration get snapConfiguration => FloatingHeaderSnapConfiguration(); } Floating is set to true. I am getting error message for vsync being null. I couldn't make it work. I need help on implementing snap feature for SliverPersistenHeader.
Why does Xamarin.FFImageLoading SVG is not working on Android 11 & 12?
It seems that it's a special issue on the Android 11, and the solution is add the reference of the skiasharp or update the nuget package skiasharp both in the android part and the forms part. You can check the following link:https://github.com/luberda-molinet/FFImageLoading/issues/1526
Xamarin.FFImageLoading SVG seems to not be working on Android 11 & 12. For example, when I do Android Target to 11 Version, setting the SVG on Embedded Resource, with this code: <ffimageloadingsvg:SvgCachedImage HeightRequest="12" Source="resource://DemoApp.Assets.Images.svgImage.svg" BackgroundColor="Transparent" Aspect="Fill" HorizontalOptions="FillAndExpand" VerticalOptions="Start"/> This SVG works fine except on Android 11 & 12. Could anyone please help to figure out why it's not showing on Android 11 & 12?
Android Material TextInputLayout endIcon cuts off text in MaterialAutoCompleteTextView
It is a workaround, not a final solution. You can reduce the padding between the text and endIcon by adding a negative value in android:drawablePadding. Something like: <com.google.android.material.textfield.MaterialAutoCompleteTextView android:id="@+id/dropdownDay" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingTop="8dp" android:paddingBottom="8dp" android:drawablePadding="-12dp" ../> A final note. You don't need to use android:background="@drawable/text_input_assessment" to have rounded corners. Just add app:shapeAppearanceOverlay="@style/ShapeAppearanceOverlay.Rounded" in the TextInputLayout with: <style name="ShapeAppearanceOverlay.Rounded" parent=""> <item name="cornerSize">50%</item> </style
I have some very short text input (like only 2 numeric characters) yet using the endIcon will hog half of my textview and will cut off and display ellipses. I cannot make the TextInputLayout wider so I how can I display the full 2 characters (or more) while using endIconDrawable? <com.google.android.material.textfield.TextInputLayout style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense.ExposedDropdownMenu" android:layout_width="80dp" android:layout_marginEnd="8dp" android:layout_marginStart="8dp" android:layout_height="40dp" android:background="@drawable/text_input_assessment" app:boxStrokeWidth="0dp" app:boxStrokeWidthFocused="0dp" app:endIconDrawable="@drawable/ptx_down_arrow_android" app:endIconTint="@color/colorPtxDarkBlue"> <com.google.android.material.textfield.MaterialAutoCompleteTextView android:id="@+id/dropdownDay" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@null" android:fontFamily="@font/truenorg" android:textSize="15sp" app:autoSizeTextType="uniform" app:autoSizeMinTextSize="10sp" app:autoSizeMaxTextSize="15sp" app:autoSizeStepGranularity="1sp" android:inputType="none" android:maxLines="1" android:paddingTop="10dp" android:paddingBottom="10dp" android:singleLine="true" android:text="12" android:textAlignment="viewStart" android:textColor="@color/colorPtxDarkBlue" tools:ignore="LabelFor" /> </com.google.android.material.textfield.TextInputLayout>
Multiple projects react-native android build error
It seems like some of your android dependencies are in Jcenter repository. Unfortunately, Jcenter is currently down. You have two choice for now : Wait for jcenter to be up (It has been down for 4 days at the moment) Migrate to use something else. See: https://developer.android.com/studio/build/jcenter-migration Bitrise: Could not resolve all artifacts for configuration ':classpath' Could not resolve com.google.gms:google-services:4.2.0
Here are the android/build.gradle files contents of two different project. PROJECT 1 ext { buildToolsVersion = "29.0.3" minSdkVersion = 21 compileSdkVersion = 29 targetSdkVersion = 30 supportLibVersion = "29.0.0" googlePlayServicesVersion = "16.0.0" firebaseVersion = "17.3.4" firebaseMessagingVersion = "20.2.1" firebaseBomVersion="20.2.1" } repositories { google() jcenter() } dependencies { classpath("com.android.tools.build:gradle:4.0.1") classpath ("com.google.gms:google-services:4.2.0") // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { mavenLocal() maven { // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm url("$rootDir/../node_modules/react-native/android") } maven { // Android JSC is installed from npm url("$rootDir/../node_modules/jsc-android/dist") } google() jcenter() maven { url 'https://jitpack.io' } } } PROJECT 2 buildscript { ext { kotlin_version = '1.5.0' buildToolsVersion = "29.0.2" minSdkVersion = 24 compileSdkVersion = 29 targetSdkVersion = 29 androidXCore = "1.7.0" googlePlayServicesAuthVersion = "16.0.1" } repositories { google() jcenter() } dependencies { classpath("com.android.tools.build:gradle:3.5.4") classpath 'com.google.gms:google-services:4.3.10' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { mavenLocal() maven { // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm url("$rootDir/../node_modules/react-native/android") } maven { // Android JSC is installed from npm url("$rootDir/../node_modules/jsc-android/dist") } google() jcenter() maven { url 'https://www.jitpack.io' } } } When I execute: react-native-android, I get the following error. PROJECT 1 * What went wrong: Could not determine the dependencies of task ':app:mergeDebugAssets'. > Could not resolve all task dependencies for configuration ':app:debugRuntimeClasspath'. > Could not resolve com.facebook.android:facebook-login:[5,6). Required by: project :app > Failed to list versions for com.facebook.android:facebook-login. > Unable to load Maven meta-data from https://jcenter.bintray.com/com/facebook/android/facebook-login/maven-metadata.xml. > Could not HEAD 'https://jcenter.bintray.com/com/facebook/android/facebook-login/maven-metadata.xml'. > org.apache.http.client.ClientProtocolException (no error message) PROJECT 2 * What went wrong: Could not determine the dependencies of task ':app:mergeDebugAssets'. > Could not resolve all task dependencies for configuration ':app:debugRuntimeClasspath'. > Could not resolve com.facebook.android:facebook-login:[8.1). Required by: project :app > Could not resolve com.facebook.android:facebook-login:[8.1). > Could not get resource 'https://jcenter.bintray.com/com/facebook/android/facebook-login/%5B8.1)/facebook-login-%5B8.1).pom'. > Could not GET 'https://jcenter.bintray.com/com/facebook/android/facebook-login/%5B8.1)/facebook-login-%5B8.1).pom'. > org.apache.http.client.ClientProtocolException (no error message) > Could not resolve com.facebook.android:facebook-android-sdk:9.0. Required by: project :app > Could not resolve com.facebook.android:facebook-android-sdk:9.0. > Could not get resource 'https://jcenter.bintray.com/com/facebook/android/facebook-android-sdk/9.0/facebook-android-sdk-9.0.pom'. > Could not GET 'https://jcenter.bintray.com/com/facebook/android/facebook-android-sdk/9.0/facebook-android-sdk-9.0.pom'. > org.apache.http.client.ClientProtocolException (no error message) > Could not resolve com.facebook.android:facebook-android-sdk:9.0.+. Required by: project :app > project :react-native-fbsdk-next > Failed to list versions for com.facebook.android:facebook-android-sdk. > Unable to load Maven meta-data from https://jcenter.bintray.com/com/facebook/android/facebook-android-sdk/maven-metadata.xml. > Could not HEAD 'https://jcenter.bintray.com/com/facebook/android/facebook-android-sdk/maven-metadata.xml'. Note that I checked the following solutions but none worked react native - could not resolve all dependencies for configuration ':classpath' Failed to resolve: com.facebook.android:facebook-android-sdk:[4,5) https://stackoverflow.com/questions/55027644/react-native-run-android-could-not-resolve-all-artifacts-for-configuration-cl[2]
Updating a Single Column In Room Database
If it is single or few columns that you want to update then you can write custom query. In your dao class @Query("UPDATE settings-table SET nightMode = :nightModeResult WHERE id = :id") fun updateNightMode(id: Int, nightModeResult: Any): Int
That's the function I'm using for update: private fun updateSettingsDatabase(settingsDao: SettingsDao) { lifecycleScope.launch { settingsDao.update(SettingsEntity( 1, nightMode=nightModeResult, )) } } @Query("SELECT * FROM `settings-table`") fun fetchCurrentSettings(): Flow<List<SettingsEntity>> I specified nightMode= because I thought that this way I'm only updating this column, but it turns out that it resets every column, how do I update a single column, while keeping the values the rest of the columns?
Firebase Cloud Messaging : not receiving message in android 12
For the new people who may come to this issue, I had the exact same issue : In my case, I was still using Firebase library 17.x with the old deprecated architecture. As now I updated into the firebase dependency into version 23.0.4, it worked just fine.
I am trying to send push notification to android 12 device using Firebase messaging service. When i try to send FCM from nodeJs, onMessageReceived is not called. I tried to send FCM from Firebase console, but even the app is in background the app isn't showed any notification or errors. I have tested this app in android 11 and android 10 and both are working fine. AndroidManifest.xml <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/icon" android:label="@string/app_name" android:roundIcon="@mipmap/icon_round" android:supportsRtl="true" android:theme="@style/Theme.MobileSMSService" android:usesCleartextTraffic="true"> <service android:name=".helper.MessagingService" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> <meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@drawable/sms_icon_foreground" /> <meta-data android:name="com.google.firebase.messaging.default_notification_color" android:resource="@color/purple_700" /> </service> </application> MessagingService.java public class MessagingService extends FirebaseMessagingService { private static final String CHANNEL_ID = "FCM"; private static final String TAG = "MessagingService"; whatsappMessageService messageService; @Override public void onNewToken(@NonNull String s) { super.onNewToken(s); JSONObject obj = new JSONObject(); SharedPreferences sp = getSharedPreferences("Login", MODE_PRIVATE); String api = sp.getString("api", null); sp.edit().putString("token", s).apply(); try { obj.put("token", s); obj.put("api", api); new Server().post(new Server().baseUrl + "update-token", obj.toString(), new Callback() { @Override public void onFailure(@NonNull Call call, @NonNull IOException e) { } @Override public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException { } }); } catch (Exception e) { Log.e("MessagingService", "onNewToken: ", e); } } @Override public void onMessageReceived(@NonNull RemoteMessage remoteMessage) { super.onMessageReceived(remoteMessage); Log.e(TAG, "onMessageReceived: recived" ); Map<String, String> data = remoteMessage.getData(); if (data.get("web") == null) { String message = data.get("message"), to = data.get("to"), plat = data.get("plat"); if (plat != null) { if (plat.equals("w")) { PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); boolean isScreenOn = pm.isScreenOn(); boolean isScreenOnApi21 = pm.isInteractive(); if (!isScreenOn | !isScreenOnApi21) { SharedPreferences sp = getApplicationContext().getSharedPreferences("Login", MODE_PRIVATE); if (sp.getString("wake_phone", null) != null) { sendSMS(sp.getString("wake_phone", null), "Wake up"); new MessagesDatabaseHelper(this).insertMessage(sp.getString("wake_phone", null), "Wake up"); try { Thread.sleep(3500); isScreenOn = pm.isScreenOn(); isScreenOnApi21 = pm.isInteractive(); if (!isScreenOn | !isScreenOnApi21) { Thread.sleep(3500); } } catch (InterruptedException e) { e.printStackTrace(); } } else { return; } } if (messageService == null) { messageService = new whatsappMessageService(getApplicationContext()); messageService.start(); } messageService.addMessage(to, message); new WhatsappDatabaseHelper(this).insertMessage(to, message); } else { new MessagesDatabaseHelper(this).insertMessage(to, message); sendSMS(to, message); } Intent intents = new Intent(); intents.setAction("sms_receiver"); getBaseContext().sendBroadcast(intents); } } else { Log.e(TAG, "onMessageReceived: " + "web"); new webManager().onMessage(data); } }
Splash API throws You need to use a Theme.AppCompat theme (or descendant) with this activity
After a lot of trialing, I discovered my issue and I've reported the issue on their bug tracker. Apparently if you have persistentState setup on onCreate() it triggers this error but removing it, the app will not crash. If someone runs into that, hopefully this helps you and hopefully the fine people at Google will address this or make a note that you can't use that parameter with the splash API.
I'm trying to follow this android documentation on using their Splash API so my splash screen can work on any version of android I support and I'm hitting a wall. I followed it exactly and I keep getting this when I debug my app: You need to use a Theme.AppCompat theme (or descendant) with this activity. // AndroidX Components implementation 'androidx.appcompat:appcompat:1.4.1' implementation 'androidx.browser:browser:1.4.0' implementation 'androidx.cardview:cardview:1.0.0' implementation 'androidx.constraintlayout:constraintlayout:2.1.3' implementation 'androidx.constraintlayout:constraintlayout-solver:2.0.4' implementation 'androidx.coordinatorlayout:coordinatorlayout:1.2.0' implementation 'androidx.core:core-ktx:1.7.0' implementation 'androidx.core:core-splashscreen:1.0.0-beta02' implementation "androidx.datastore:datastore-preferences:1.0.0" implementation 'androidx.fragment:fragment-ktx:1.4.1' implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.4.1' implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.1' implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:2.4.1" implementation "androidx.navigation:navigation-dynamic-features-fragment:2.4.2" implementation 'androidx.navigation:navigation-fragment-ktx:2.4.2' implementation "androidx.navigation:navigation-runtime-ktx:2.4.2" implementation 'androidx.navigation:navigation-ui-ktx:2.4.2' implementation 'androidx.paging:paging-runtime-ktx:3.1.1' implementation 'androidx.preference:preference-ktx:1.2.0' implementation 'androidx.recyclerview:recyclerview:1.2.1' implementation 'androidx.recyclerview:recyclerview-selection:1.1.0' implementation "androidx.security:security-crypto:1.1.0-alpha03" implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0' implementation 'androidx.viewpager2:viewpager2:1.0.0' implementation 'androidx.webkit:webkit:1.4.0' implementation "androidx.work:work-runtime-ktx:2.7.1" // Firebase & Google Play Services implementation 'com.google.android.gms:play-services-base:18.0.1' implementation 'com.google.android.play:core:1.10.3' implementation 'com.google.android.play:core-ktx:1.8.1' implementation platform('com.google.firebase:firebase-bom:29.0.4') implementation 'com.google.firebase:firebase-analytics-ktx' implementation 'com.google.firebase:firebase-crashlytics-ktx' implementation 'com.google.firebase:firebase-messaging-ktx' implementation 'com.google.gms:google-services:4.3.10' // Glide implementation 'com.github.bumptech.glide:glide:4.13.1' implementation 'com.github.bumptech.glide:recyclerview-integration:4.13.1' kapt 'com.github.bumptech.glide:compiler:4.13.1' // Hilt implementation 'androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha03' implementation 'androidx.hilt:hilt-work:1.0.0' implementation 'com.google.dagger:hilt-android:2.41' kapt 'androidx.hilt:hilt-compiler:1.0.0' kapt 'com.google.dagger:hilt-android-compiler:2.41' // Ktor implementation 'io.ktor:ktor-client-android:2.0.0' implementation 'io.ktor:ktor-client-auth:2.0.0' implementation 'io.ktor:ktor-client-content-negotiation:2.0.0' implementation 'io.ktor:ktor-serialization-kotlinx-json:2.0.0' // Kotlin & Coroutines implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.1-native-mt' implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.1-native-mt' implementation 'org.jetbrains.kotlinx:kotlinx-datetime:0.3.2' implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.2' // Misc implementation 'com.auth0.android:jwtdecode:2.0.1' implementation "com.github.skydoves:androidveil:1.1.2" implementation 'com.github.yalantis:ucrop:2.2.8' implementation 'com.google.android.material:material:1.5.0' implementation 'com.jakewharton.timber:timber:5.0.1' // Unit Testing testImplementation 'junit:junit:4.13.2' androidTestImplementation 'androidx.test.ext:junit:1.1.3' androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' <style name="App.Material" parent="Theme.MaterialComponents.DayNight.NoActionBar"> <item name="android:navigationBarColor">@color/primary</item> <item name="android:textAllCaps">false</item> <item name="android:textColorPrimary">@color/textColor</item> <item name="android:textColorSecondary">@color/mutedTextColor</item> <item name="actionModeCloseDrawable">@drawable/close</item> <item name="actionModeStyle">@style/ActionModeStyle</item> <item name="actionMenuTextColor">#ffffff</item> <item name="colorAccent">@color/primary</item> <item name="colorPrimary">@color/primary</item> <item name="colorPrimaryDark">@color/primary</item> <item name="colorError">@color/error</item> <item name="colorPrimaryVariant">@color/primary</item> <item name="colorSecondaryVariant">@color/primary</item> <item name="colorOnPrimary">#ffffff</item> <item name="colorOnSecondary">#ffffff</item> <item name="colorOnBackground">@color/textColor</item> <item name="colorOnError">#ffffff</item> <item name="shapeAppearanceLargeComponent">@style/ShapeAppearance.LargeComponent</item> <item name="shapeAppearanceMediumComponent">@style/ShapeAppearance.MediumComponent</item> <item name="shapeAppearanceSmallComponent">@style/ShapeAppearance.SmallComponent</item> <item name="windowActionModeOverlay">true</item> <item name="windowNoTitle">true</item> </style> <style name="App.Material.Splash" parent="Theme.SplashScreen"> <item name="windowSplashScreenBackground">@color/primaryColor</item> <item name="windowSplashScreenAnimatedIcon">@drawable/splash_logo</item> <item name="postSplashScreenTheme">@style/App.Material</item> <!-- Status bar and Nav bar configs --> <item name="android:statusBarColor" tools:targetApi="l">@color/primaryColor</item> <item name="android:navigationBarColor">@color/primaryColor</item> </style> override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) { val splashScreen = installSplashScreen() super.onCreate(savedInstanceState, persistentState) // Keep the splash screen visible for this Activity splashScreen.setKeepOnScreenCondition { true } // ... rest of my app's code } I believe I followed how it's meant to be setup, so I'm just lost at this point on why it's not working at all and throwing a fit.
How do I persist authentication state in my Kotlin firebase app?
So, I was not aware that firebase users stay signed in until logged out explicitly. Understanding this solved my problem as I didn't have to write code to handle keeping the user signed in.
I am building a kotlin app using FirebaseAuth and I want to add some custom rules to keep the user signed in for a time even if they are not using the app. All I could find in the docs related to this was for Web applications. https://firebase.google.com/docs/auth/web/auth-state-persistence Is there anything like this in the docs for Android? If not, is there a way I can get that functionality? I was considering using SharedPreferences to store authentication state but I get the feeling there is a better way.
Flutter: Using Proguard with Gradle 7.0.4 [duplicate]
The 'useProguard' line has ben removed, as of Gradle 7.0.0. Flutter should obfuscate without this, but you can add shrinkResources true, if you want. Android R8 is an alternative to using Proguard, with its own settings; as long as you're configuring this, you might want to look into switching.
I just updated to Gradle 7.0.4 and upon build I now get the error. A problem occurred evaluating project ':app'. No signature of method: build_9gq7rvxos4tcg7upa17qqy1oj.android() is applicable for argument types: (build_9gq7rvxos4tcg7upa17qqy1oj$_run_closure3) values: [build_9gq7rvxos4tcg7upa17qqy1oj$_run_closure3@558fca1c] As the error pointed to the android{} tag in my app/build.gradle I tried commenting out different sections of the android{} tag. I managed to get rid of the error by commenting out Proguard: android { /* More code */ buildTypes { release { signingConfig signingConfigs.release // These lines seem to have caused the error: // minifyEnabled true // useProguard true // proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } However, I would still like to use proguard so my question is what I have to change in my code to make this happen.
when click back button, the app crashs after a seceond
before calling requireActivity().onBackPressedDispatcher.onBackPressed(). you should set isEnabled to false because if we go through the onBackPressed source code we see: it looks for active callbacks and if found any calls them and returns. that's what makes the loop. your code should be: isEnabled = false requireActivity().onBackPressedDispatcher.onBackPressed()
I have customized back button. when I click on it, the application crashes after a second. here is the code: error log private var mBackPressed: Long = 0 private val timeInterval = 2000 private fun configBackPress() { requireActivity().onBackPressedDispatcher.addCallback(this, true) { when { mBackPressed + timeInterval > System.currentTimeMillis() -> { requireActivity().onBackPressedDispatcher.onBackPressed() } else -> { Snackbar.make( requireActivity().findViewById(android.R.id.content), getString(R.string.press_once_again_back_button_to_exit), Snackbar.LENGTH_SHORT ) .setAnchorView(viewBinding.vSnackBarHelper) .show() mBackPressed = System.currentTimeMillis() } } } } when the user click two times on back button, the back should work.
Android 12 Splash Screen API inconsistent behavior
I solved the issue, first if you want to keep the splash icon screen on user screen you need to use both setKeepOnScreenCondition and setOnExitAnimationListener splashScreen.apply { // Behaves like observable, used to check if splash screen should be keep or not setKeepOnScreenCondition { keepSplash // True to keep the screen, False to remove it } setOnExitAnimationListener { splashScreenViewProvider -> // Do nothing so the splash screen will remain visible } } or just splashScreen.setOnExitAnimationListener { // Do nothing so the splash screen will remain visible splashScreenViewProvider = it } Then just call splashScreenViewProvider.remove() later when you are done. Just remember that setKeepOnScreenCondition can be a UI blocking thread so if ever you are fetching some data during splash screen and showed an error message via dialog, Toast, or SnackBar it wont work. You need to set setKeepOnScreenCondition to false first. The role of empty setOnExitAnimationListener here is not to remove the splash screen even after setting a false condition on setKeepOnScreenCondition. UPDATED It is probably best to just use and empty setOnExitAnimationListener if you want to control and extend the Splash Screen. Then save its splashScreenViewProvider in a variable and use it later to control or dismiss the screen by calling remove(). Documentation is here. There might times where the splash logo may not show due to how it works with hot start and cold start. https://developer.android.com/develop/ui/views/launch/splash-screen#how Note that there still issue when installing and running the app directly using USB debugging in Android Studio where the SplashScreen never showed up and stuck in empty screen which can be problematic when you are using Firebase Test Lab. The issue only happens in SDK 31 and 32. https://issuetracker.google.com/issues/197906327
I am implementing the new Splash Screen API but encountered an inconsistent behavior on it. Sometimes the screen with app icon shows and sometimes it doesn't. There is also a long white screen on the beginning which is visibly annoying (The attached image was just speed up 3x since I cannot upload image file higher than 2mb here, but the white screen was clearly visible for a couple of seconds and Splash API seems to cause frame skip from Choreographer log). Samsung J1 Android L class LauncherActivity : AppCompatActivity() { private var keepSplash = true private lateinit var splashScreen: SplashScreen override fun onCreate(savedInstanceState: Bundle?) { splashScreen = installSplashScreen().apply { // Behaves like observable, used to check if splash screen should be keep or not setKeepOnScreenCondition { keepSplash } setOnExitAnimationListener { sp -> sp.remove() // Remove splash screen } } super.onCreate(savedInstanceState) } fun fetchData() { //Fetching network data... keepSplash = false } Showing the AlertDialog seems not working unless I minimize the app and reopen it with setKeepOnScreenCondition. It seems to block the UI thread, is there other way to retain the splash but not a blocking UI one? Currently we need to show an AlertDialog if something went wrong but at the same time the splash screen will be retain until the dialog is dismiss.
How do I keep my android activity keep on going even if somebody switches from dark mode to day mode or vice versa (using Java)
The description of your problem doesn't make much sense. Normally, if you change the light/dark mode setting, Android will kill the existing instance of your Activity and create a new instance, so that the new instance can recreate all the UI elements with the proper style. You say that Android isn't killing the existing instance, but it is starting a new instance and this doesn't make sense. You should add logging in onCreate() and onDestroy() to see if this is really going on, or if you are seeing something else. Note that you can prevent Android from restarting your Activity by adding android:configChanges="uiMode" to the <activity> declaration in the manifest. Instead of killing and recreating your Activity, the Android framework will instead call onConfigurationChanged() on the existing instance of the Activity. You will then need to handle the change yourself.
The problem is that when I switch from dark mode to light mode (android dark mode and android light mode), the activity which was going on that works fine but a duplicate activity starts all over again. Now this does not matter when you are just working with visuals because the new activity covers the screen and old activity is not displayed but I am also working with sounds so the sounds playing in both the activities are heard. In short, when switching from dark mode to light (or vice versa), the ongoing activity continues while a duplicate activity of the very same one starts from the beginning. I don't want this new duplicate activity. How do I avoid it? I don't think my code is required here. I require the answer in Java.
Android TextInputLayout endIconDrawable appears gray instead of image
Use the endIconTint to set the color app:endIconTint="@color/redText" app:endIconTintMode="multiply"
TextInputLayout endIconDrawable displaying as gray instead of needed image. Only this image renders as gray. I tried the image as png and also imported svg as vector asset. Both are not working as expected. I tried setting image in TextInputLayout: <com.google.android.material.textfield.TextInputLayout android:id="@+id/chatFragment_TIL1" android:layout_width="match_parent" android:layout_height="50dp" app:boxBackgroundMode="outline" android:layout_toRightOf="@id/chatFragment_imageView2" android:layout_marginStart="15dp" app:boxCornerRadiusTopStart="@dimen/TIL_CornerRadius2" app:boxCornerRadiusTopEnd="@dimen/TIL_CornerRadius2" app:boxCornerRadiusBottomStart="@dimen/TIL_CornerRadius2" app:boxCornerRadiusBottomEnd="@dimen/TIL_CornerRadius2" app:endIconMode="custom" app:endIconDrawable="@drawable/ic_message_send_icon" style="@style/TextInputLayoutStyle" app:hintEnabled="false"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/chatFragment_TIET1" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPersonName" android:fontFamily="@font/inter_regular" android:textColor="@color/black_text_dark" android:hint="@string/chatFragment_Text1" android:textSize="@dimen/normalText1" /> </com.google.android.material.textfield.TextInputLayout> I am also changing it on text input change as below: if(s.length() > 0){ inputMessageTIL.setEndIconDrawable(R.drawable.ic_message_send_icon); } else { inputMessageTIL.setEndIconDrawable(R.drawable.ic_mic); } This is the vectordrawable code: <vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="32dp" android:height="32dp" android:viewportWidth="32" android:viewportHeight="32"> <path android:pathData="M16,16m-16,0a16,16 0,1 1,32 0a16,16 0,1 1,-32 0" android:fillColor="#6B4EFF"/> <path android:pathData="M22.5,9.5L14.25,17.75M22.5,9.5L17.25,24.5L14.25,17.75M22.5,9.5L7.5,14.75L14.25,17.75" android:strokeLineJoin="round" android:strokeWidth="1.5" android:fillColor="#00000000" android:strokeColor="#ffffff" android:strokeLineCap="round"/> </vector> This is the image I used in png format This is what I am getting now.. gray circle image.. Please help me. I can't use another image. Thanks a lot!
Git or Github pull, push errors solution in Android Studio Bumblebee | 2021.1.1
Error:- "Push failed, Invocation failed Unexpected end of file from server" Enter This command in terminal/CMD git config --local user.name 'your username' git config --local user.password 'your password' git config --global credential.helper store Solution:- Also make sure, "Use Credential help" is checked in setting > VCS > Git. Android Setting image
git config credential.helper store Enable "Use Credential Helper" in Settings -> Version Control -> Git. In Every project you have to config with this terminal code. *This is a temporary solution until find anything related to this issue
How to load an image with Coil from URI in jetpack compose
According to Network security configuration , I think it's the HTTP address, Create file res/xml/network_security_config.xml: <?xml version ="1.0" encoding ="utf-8"?> <network-security-config> <base-config cleartextTrafficPermitted="true" /> </network-security-config> AndroidManifest.xml: <?xml version="1.0" encoding="utf-8"?> <manifest ...> <uses-permission android:name="android.permission.INTERNET" /> <application ... android:networkSecurityConfig="@xml/network_security_config" ...> ... </application> </manifest>
I am using the latest version of Coil: implementation("io.coil-kt:coil-compose:2.0.0-rc01") I would like to load a barcode label image to my Jetpack Compose file for example like so: Box(modifier = Modifier.background(Color.DarkGray).fillMaxSize()) { AsyncImage( model = ImageRequest.Builder(LocalContext.current) .data("https://www.researchgate.net/profile/Adnan-Ghaffar/publication/313103370/figure/fig3/AS:456489858015234@1485847071322/An-example-of-barcode.png") .crossfade(true) .build(), contentDescription = "barcode image", contentScale = ContentScale.Crop, modifier = Modifier ) } This works fine the issue appears when I try to load an image from a URI like the follow one: http://api.labelary.com/v1/printers/8dpmm/labels/4x6/0/^xa^cfa,50^fo100,100^fdHello World^fs^xz But it does not work, for example code I tried: Box(modifier = Modifier.background(Color.DarkGray).fillMaxSize()) { AsyncImage( model = ImageRequest.Builder(LocalContext.current) .data("http://api.labelary.com/v1/printers/8dpmm/labels/4x6/0/^xa^cfa,50^fo100,100^fdHello World^fs^xz") .crossfade(true) .build(), contentDescription = "barcode image", contentScale = ContentScale.Crop, modifier = Modifier ) } More info on how to create a label .png on labelary
Ktor - Only apply bearer tokens for certain urls
You can filter requests by some condition that should include the Authorization header initially. For each other request, the second request with the Authorization header will be made if a server replied with 401 Unauthorized status. Here is an example configuration: val client = HttpClient { install(Auth) { bearer { sendWithoutRequest { request -> request.url.encodedPath.startsWith("/restricted") } // ... } } }
In my project, there are network requests that require authentication via bearer tokens and some requests that don't. Is there a way to specify the urls that do not need bearer tokens? If I just add the Auth plugin, then I always get a 401 response for the network calls that don't require bearer tokens. This is my implementation right now: interface MyService { ... companion object Factory { fun build(getToken: GetToken, login: Login, saveToken: SaveToken): MyService { return MyServiceImpl(httpClient = HttpClient(CIO) { install(JsonFeature) { serializer = KotlinxSerializer( kotlinx.serialization.json.Json { ignoreUnknownKeys = true } ) } install(Logging) { logger = Logger.DEFAULT level = LogLevel.HEADERS } install(Auth) { lateinit var tokenInfo: TokenInfo bearer { refreshTokens { getRefreshedTokens( tokenInfo = tokenInfo, login = login, saveToken = saveToken ) } loadTokens { tokenInfo = getToken.execute().firstOrNull() ?: TokenInfo( Constants.EMPTY_STRING, Constants.EMPTY_STRING ) BearerTokens( accessToken = tokenInfo.accessToken, refreshToken = tokenInfo.refreshToken ) } } } }) } ... } }
Kotlin inflate generic viewbinding class in parent
If I were to do this, I'd do it like this: class BaseDialogFragment<T: ViewBinding>(private val bindingInflater: (LayoutInflater, ViewGroup?, Boolean) -> T) : AppCompatDialogFragment() { var _binding: T? = null val binding: T get() = _binding ?: error("Must only access binding while fragment is attached.") override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = bindingInflater(inflater, container, false) return binding.root } override fun onDestroy() { super.onDestroy() _binding = null } } with usage like: class ChildClass: BaseDialog(ChildClassViewBinding::inflate) { } However, I would not do this in the first place (since there's a nice alternative). It can become messy pretty quickly to rely on inheritance for these kinds of things. What happens if you want to add some other features for a dependency injection framework, or some other common things you like to use? What if there's some features you like to use in some of your fragments but not all of them? And are you also creating base classes like this for Activity and non-Dialog Fragments? These problems are why there's a programming axiom: "composition over inheritance". Sometimes there's no choice but to use inheritance to avoid code duplication. But in the case of Fragments and Bindings, I don't think so. You can pass your layout reference to the super constructor, and use ViewBinding.bind() instead of inflate(). Since bindings rarely need to be accessed outside the onViewCreated function, you usually don't need a property for it. class ChildClass: AppCompatDialogFragment(R.layout.child_class_view) { override fun onViewCreated(view: View, bundle: Bundle?) { super.onViewCreated(view, bundle) val binding = ChildClassViewBinding.bind(view) //... } } If you do need a property for it, @EpicPandaForce has a library that makes it a one-liner and handles the leak-avoidance on destroy for you inside a property delegate. Library here Usage: class ChildClass: AppCompatDialogFragment(R.layout.child_class_view) { private val binding by viewBinding(ChildClassViewBinding::bind) }
Aim is to declare a base class abstract class BaseDialog<T : ViewBinding> : AppCompatDialogFragment() { lateinit var binding: T } and all child classes should extend this parent class class ChildClass: BaseDialog<ChildClassViewBinding>() { } Then I want to inflate the binding in parent class and save it to binding property This seems out of my scope of knowledge of kotlin Is this really possible to do?
Jetpack Compose Recomposition every state changes
This behaviour is totally expected. Compose is trying to reduce number of recompositions as much as possible. When you comment out MyText, the only view that depends on counter is Button content, so this is the only view that needs to be recomposed. By the same logic you shouldn't see VALUE1 logs more than once, but the difference here is that Column is inline function, so if it content needs to be recomposed - it gets recomposed with the containing view. Using this knowledge, you can easily prevent a view from being recomposed: you need to move part, which doesn't depends on the state, into a separate composable. The fact that it uses scrollState won't make it recompose, only reading state value will trigger recomposition. @Composable fun Screen(){ val scrollState = rememberScrollState() Box() { YourColumn(scrollState) MyText(scrollStateValue = scrollState.value) //Doing some UI staff in this component } } @Composable fun YourColumn(scrollState: ScrollState){ Column(modifier = Modifier .verticalScroll(scrollState) .padding(top = 50.dp)) { //Some Static Column Elements with images etc. } }
Here is my problem; When I add MyText composable in my Screen, I see all Logs (value1, value2, value3) which means it is recomposing every part of my code. However when I comment the MyText line, I see only value3 on Logcat How can I fix this ? I know it is not a big problem here but just imagine we have a scrollable Column here and we are trying to pass ScrollState.value to My Text component. Because of this situation, our list becomes so laggy. class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { Screen() } } } @Composable fun Screen(){ var counter by remember { mutableStateOf(0) } Log.i("RECOMPOSE","VALUE1") Column() { Text(text = "Just a text") Log.i("RECOMPOSE","VALUE2") Button(onClick = { counter = counter.plus(1) }) { Text(text = counter.toString()) Log.i("RECOMPOSE","VALUE3") } MyText(counter) } } @Composable fun MyText(counter:Int){ Text(text = counter.toString()) } EDIT There is main problem, with Scrollable Column; @Composable fun Screen(){ val scrollState = rememberScrollState() Box() { Column(modifier = Modifier .verticalScroll(scrollState) .padding(top = 50.dp)) { //Some Static Column Elements with images etc. } MyText(scrollStateValue = scrollState.value) //Doing some UI staff in this component } } @Composable fun MyText(scrollStateValue:Int){ Text(text = scrollStateValue.toString()) }
I am not able to access contents from External Storage in my React Native App
Please check / try the following Allow storage permissions for the app from the device setting. Try update manifest like below by adding android:requestLegacyExternalStorage="true" <manifest ... > <application android:requestLegacyExternalStorage="true" ... > ... </application> </manifest>
I am using react-native-fs to build a media player like app but I am unable to access directories outside my project folder, I have added these permissions : <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" /> I am also checking the read and write permission using the following code : PermissionsAndroid.check( PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE, ).then(granted => { if (!granted) { PermissionsAndroid.requestMultiple([ PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE, PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE, ]).then(result => { console.log(result); }); } }); RNFS.readDir() is throwing null error : const path = RNFS.ExternalStorageDirectoryPath; RNFS.readDir(path).then(result => { console.log('GOT RESULT', result); }); The error that is thrown is : [Error: Attempt to get length of null array]
How to wait for the end of the animation correctly?
I used the progress & listened to it's updates & as soon as it reaches 1f I'll call my function. Example: @Composable fun Splash() { LottieTest { // Do something here } } @Composable fun LottieTest(onComplete: () -> Unit) { val composition: LottieCompositionResult = rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.camera)) val progress by animateLottieCompositionAsState( composition.value, iterations = 1, ) LaunchedEffect(progress) { Log.d("MG-progress", "$progress") if (progress >= 1f) { onComplete() } } LottieAnimation( composition.value, progress, ) } Note: This is just the way I did it. The best way is still unknown(to me atleast). I feel it lacks the samples for that. Also, You can modify a lot from this & just concentrate on the core flow.
I know that I can track the moment when lottie animation is completed using progress. But the problem is that I want to start a new screen at the moment when the animation is completely finished. Here is the code of my animation @Composable fun AnimatedScreen( modifier: Modifier = Modifier, rawId: Int ) { Box( contentAlignment = Alignment.Center, modifier = modifier.fillMaxSize() ) { val compositionResult: LottieCompositionResult = rememberLottieComposition( spec = LottieCompositionSpec.RawRes(rawId) ) AnimatedScreenAnimation(compositionResult = compositionResult) } } @Composable fun AnimatedScreenAnimation(compositionResult: LottieCompositionResult) { val progress by animateLottieCompositionAsState(composition = compositionResult.value) Column { if (progress < 1) { Text(text = "Progress: $progress") } else { Text( modifier = Modifier.clickable { }, text = "Animation is done" ) } LottieAnimation( composition = compositionResult.value, progress = progress, modifier = Modifier.fillMaxSize(), contentScale = ContentScale.FillBounds ) } } And here is code of my screen where i want to wait for the end of the animation and then go to a new screen: @Composable fun SplashScreen( navController: NavController, modifier: Modifier = Modifier, viewModel: SplashScreenViewModel = getViewModel() ) { val resIdState = viewModel.splashScreenResId.collectAsState() val resId = resIdState.value if (resId != null) { AnimatedScreen(modifier = modifier, rawId = resId) } LaunchedEffect(true) { navigate("onboarding_route") { popUpTo(0) } } }
Unable to access the API key using BuildConfig
I end up reading the API value in local.properties in app's build.gradle and assigning it to BuildConfig. This is done under defaultConfig tag. Properties properties = new Properties() properties.load(project.rootProject.file('local.properties').newDataInputStream()) buildConfigField "String", "API_KEY", "\"${properties.getProperty('API_KEY')}\""
I'm using secrets-gradle-plugin to read the API keys that I put in my local.properties. I've added this code into the root build.gradle buildscript { dependencies { classpath "com.google.android.libraries.mapsplatform.secrets-gradle-plugin:secrets-gradle-plugin:2.0.0" } } For app build.gradle plugins { id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin' } android { compileSdk 31 ... } And this is my local.properties ## This file must *NOT* be checked into Version Control Systems, # as it contains information specific to your local configuration. # # Location of the SDK. This is only used by Gradle. # For customization when using a Version Control System, please read the # header note. # sdk.dir=/Users/xxx/Library/Android/sdk apiKey=YOUR_API_KEY Then when I tried to access it from any class/application BuildConfig.apiKey is not there. Am I missing any steps here? Been trying for few hours but doesn't found any way to make this work.
Only one class may appear in a supertype list
In Kotlin you can inherit only one class, but multiple interfaces. In your case Fragment and MainActivity are classes, you can't inherit both of them. I guess you don't need to inherit MainActivity class by fragment class ExaminationFragment, inheriting Fragment class is enough for displaying a screen: class ExaminationFragment : Fragment() { ... } Please see how to create Fragments. In the provided example ExampleFragment is inherited from Fragment class, and doesn't inherit from any Activity class.
I am running into trouble with having two superclasses. When I am adding the MainActivity() I am recieving the error: Only one class may appear in a supertype list. Any ideas on how I can work around this problem? class ExaminationFragment : Fragment(),MainActivity() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_examination, container, false) } }
How to resolve infinite loop causing by state change in android compose with firebase authentication
Navigation is also a side effect, after each frame of the animation you will again navigate to your destination. Change your block to: when (val response = viewModel.signInState.value) { is Response.Loading -> LinearProgressIndicator(modifier = Modifier.fillMaxWidth()) is Response.Success -> if (response.data) LaunchedEffect(response.data){ navController?.navigate(Screen.HomeScreen.route) } is Response.Error -> LaunchedEffect(Unit) { scaffoldState.snackbarHostState.showSnackbar("Error signing out. ${response.message}", "", SnackbarDuration.Short) } }
I have an application with sign in via email and password with firebase. I'm using jetpack compose with MVVM and clean architecture. When getting from firebase that login was done I'm getting true in the view model and then listening to this state change in the composable. The problem is I'm always get in the when statement of the sign in state and it cause an infinite loop that always navigating to the next composable. Copying here the specific line from the view: when (val response = viewModel.signInState.value) { is Response.Loading -> LinearProgressIndicator(modifier = Modifier.fillMaxWidth()) is Response.Success -> if (response.data) { navController?.navigate(Screen.HomeScreen.route) } is Response.Error -> LaunchedEffect(Unit) { scaffoldState.snackbarHostState.showSnackbar("Error signing out. ${response.message}", "", SnackbarDuration.Short) } } My View: @Composable fun LoginScreen( navController: NavController?, viewModel: LoginViewModel = hiltViewModel() ) { val scaffoldState = rememberScaffoldState() Scaffold(scaffoldState = scaffoldState) { Column ( modifier = Modifier .fillMaxHeight() .background( Color.White ), verticalArrangement = Arrangement.Top, horizontalAlignment = Alignment.CenterHorizontally, ){ var email = viewModel.email var pass = viewModel.password var passwordVisibility = viewModel.passwordVisibility TitleView(title = "SIGN IN", topImage = Icons.Filled.Person, modifier = Modifier) Spacer(modifier = Modifier.padding(20.dp)) Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Top ) { OutlinedTextField( modifier = Modifier .fillMaxWidth() .padding(horizontal = 20.dp), value = email.value, onValueChange = viewModel::setEmail, label = { Text( "Email")}, placeholder = { Text("Password") } ) OutlinedTextField( modifier = Modifier .fillMaxWidth() .padding(horizontal = 20.dp), value = pass.value, onValueChange = viewModel::setPassword, label = { Text( "Password")}, placeholder = { Text("Password") }, visualTransformation = if (passwordVisibility.value) VisualTransformation.None else PasswordVisualTransformation(), keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password), trailingIcon = { val image = if (passwordVisibility.value) Icons.Filled.Visibility else Icons.Filled.VisibilityOff IconButton(onClick = { viewModel.setPasswordVisibility(!passwordVisibility.value) }) { Icon(imageVector = image, "") } } ) Spacer(modifier = Modifier.padding(5.dp)) Button( modifier = Modifier .fillMaxWidth() .padding(horizontal = 20.dp) .border( width = 2.dp, brush = SolidColor(Color.Yellow), shape = RoundedCornerShape(size = 10.dp) ), onClick = { viewModel.signInWithEmailAndPassword() }, colors = ButtonDefaults.buttonColors( backgroundColor = Color.White ) ) { Text( text = "SIGN IN", textAlign = TextAlign.Center, fontSize = 20.sp, style = TextStyle( fontWeight = FontWeight.Thin ) ) } Spacer(modifier = Modifier.padding(5.dp)) Button( modifier = Modifier .fillMaxWidth() .padding(horizontal = 20.dp) .border( width = 2.dp, brush = SolidColor(Color.Yellow), shape = RoundedCornerShape(size = 10.dp) ), onClick = { viewModel.forgotPassword() }, colors = ButtonDefaults.buttonColors( backgroundColor = Color.White ) ) { Text( text = "FORGOT PASSWORD", textAlign = TextAlign.Center, fontSize = 20.sp, style = TextStyle( fontWeight = FontWeight.Thin ) ) } } } } when (val response = viewModel.signInState.value) { is Response.Loading -> LinearProgressIndicator(modifier = Modifier.fillMaxWidth()) is Response.Success -> if (response.data) { navController?.navigate(Screen.HomeScreen.route) } is Response.Error -> LaunchedEffect(Unit) { scaffoldState.snackbarHostState.showSnackbar("Error signing out. ${response.message}", "", SnackbarDuration.Short) } } when (val response = viewModel.forgotState.value) { is Response.Loading -> LinearProgressIndicator(modifier = Modifier.fillMaxWidth()) is Response.Success -> if (response.data) { LaunchedEffect(Unit){ scaffoldState.snackbarHostState.showSnackbar("Please click the link in the verification email sent to you", "", SnackbarDuration.Short) } } is Response.Error -> LaunchedEffect(Unit){ scaffoldState.snackbarHostState.showSnackbar("Error signing out. ${response.message}", "", SnackbarDuration.Short) } } } My View model: @HiltViewModel class LoginViewModel @Inject constructor( private val useCases: UseCases ) : ViewModel() { private val _signInState = mutableStateOf<Response<Boolean>>(Response.Success(false)) val signInState: State<Response<Boolean>> = _signInState private val _forgotState = mutableStateOf<Response<Boolean>>(Response.Success(false)) val forgotState: State<Response<Boolean>> = _forgotState private val _email = mutableStateOf("") val email = _email fun setEmail(email: String) { _email.value = email } private val _password = mutableStateOf("") val password = _password fun setPassword(password: String) { _password.value = password } private val _passwordVisibility = mutableStateOf(false) val passwordVisibility = _passwordVisibility fun setPasswordVisibility(passwordVisibility: Boolean) { _passwordVisibility.value = passwordVisibility } fun signInWithEmailAndPassword() { viewModelScope.launch { useCases.signInWithEmailAndPassword(_email.value, _password.value).collect { response -> _signInState.value = response } } } fun forgotPassword() { viewModelScope.launch { useCases.forgotPassword(_email.value).collect { response -> _forgotState.value = response } } } } My Sign in function: override suspend fun signInWithEmailAndPassword( email: String, password: String ) = flow { try { emit(Response.Loading) val result = auth.signInWithEmailAndPassword(email, password).await() if (result.user != null) emit(Response.Success(true)) else emit(Response.Success(false)) } catch (e: Exception) { emit(Response.Error(e.message ?: ERROR_MESSAGE)) } }
End of preview.

No dataset card yet

New: Create and edit this dataset card directly on the website!

Contribute a Dataset Card
Downloads last month
14