ComposeView is very slow when opening the fragment for the first time - android

I added compose to an existing project.
I rewrote a fragment ui with compose, and when I'm starting the
fragment it takes a long time to start.
Adding a fragment from another fragment:
val fragment = FragmentWithComposeUi()
requireActivity().addFragment(fragment, R.id.fragment_container, "FragmentWithComposeUi")
addFragment() function to add the fragment.
fun FragmentActivity.addFragment(fragment: Fragment, container: Int, tag:String) {
val currentFragment = supportFragmentManager.findFragmentByTag(tag)
if (currentFragment == null) {
supportFragmentManager.beginTransaction()
.setReorderingAllowed(true)
.add(container, fragment, tag)
.addToBackStack(tag)
.commit()
}
}
FragmentWithComposeUi class :
class FragmentWithComposeUi: Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return ComposeView(requireContext()).apply{
setContent {
//some ui
}
}
}
build.gradle
I tried using the new compose version 1.3.0-alpha01 either, it doesn't help.
buildscript {
ext {
compose_version = '1.1.1'
compose_compiler_version = '1.2.0'
}
repositories {
mavenCentral()
}
dependencies {
//
}
}
plugins {
id 'com.android.application' version '7.2.0' apply false
id 'com.android.library' version '7.2.0' apply false
id 'org.jetbrains.kotlin.android' version '1.7.0' apply false
}
task clean(type: Delete) {
delete rootProject.buildDir
}
build.gradle/app
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
id 'kotlin-kapt'
}
android {
compileSdk 32
defaultConfig {
applicationId "com.e...."
minSdk 26
targetSdk 32
versionCode 1
versionName "1.0"
multiDexEnabled = true
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
useSupportLibrary true
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
viewBinding {
enabled = true
}
packagingOptions {
resources {
excludes += '/META-INF/{AL2.0,LGPL2.1}'
}
resources.excludes.add("META-INF/*")
}
buildFeatures {
compose true
}
composeOptions {
kotlinCompilerExtensionVersion compose_compiler_version
}
}
dependencies {
implementation 'androidx.core:core-ktx:1.6.0'
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.5.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
implementation("androidx.multidex:multidex:2.0.1")
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'androidx.lifecycle:lifecycle-reactivestreams-ktx:2.5.0'
androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.1'
//compose
implementation 'androidx.activity:activity-compose:1.3.1'
implementation "androidx.compose.ui:ui:$compose_version"
implementation "androidx.compose.material:material:$compose_version"
implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
implementation "androidx.compose.runtime:runtime-livedata:$compose_version"
...
}
Any reasons why it happens?
Thanks !

Related

The PhilJay's MPAndroidChart pieChart graph is not displayed

I want to display a simple pie chart with PhilJay's MPAndroidChart library in a fragment but the application crashed. I added the dependencies in the project and module Gradle files and assigned the PieChart object in the OnCreateView method and created four values for its display.
My Gradle Poyect file:
buildscript {
repositories {
google()
mavenCentral()
**maven { url 'https://jitpack.io' }**
}
dependencies {
def nav_version = "2.5.1"
classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"
}
}
plugins {
id 'com.android.application' version '7.3.1' apply false
id 'com.android.library' version '7.3.1' apply false
id 'org.jetbrains.kotlin.android' version '1.7.20' apply false
}
My Gradle Module File:
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
id 'androidx.navigation.safeargs.kotlin'
id 'kotlin-parcelize'
}
android {
namespace 'com.alquemis'
compileSdk 33
defaultConfig {
applicationId "com.alquemis"
minSdk 23
targetSdk 33
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
}
kotlinOptions {
jvmTarget = '1.8'
}
buildFeatures{
viewBinding true
}
}
dependencies {
implementation 'androidx.core:core-ktx:1.9.0'
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.8.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
// Fragment
implementation 'androidx.fragment:fragment-ktx:1.5.5'
//Navigation Components
implementation 'androidx.navigation:navigation-fragment-ktx:2.5.3'
implementation 'androidx.navigation:navigation-ui-ktx:2.5.3'
// Coroutines
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.1'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.1'
// Coroutine Lifecycle Scopes
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.5.1"
implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.5.1"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.5.1"
// Graficos
**implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'**
// Data Store
implementation "androidx.datastore:datastore-preferences:1.0.0-alpha01"
}
My Fragment Code:
class MainMenuFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val view: View = inflater.inflate(R.layout.fragment_main_menu, container, false)
val pieChartServices: PieChart = view.findViewById(R.id.pieChartServices)
val btnService: Button = view.findViewById(R.id.btnService)
val pieChartEntry: ArrayList<PieEntry> = ArrayList()
pieChartEntry.add(PieEntry(3f,"Esperando"))
pieChartEntry.add(PieEntry(2f,"Respondidas"))
pieChartEntry.add(PieEntry(2f,"Calificadas"))
pieChartEntry.add(PieEntry(1f,"Comentario"))
val pieDataSet = PieDataSet(pieChartEntry,"Servicios")
val piedata = PieData(pieDataSet)
piedata.setDrawValues(true)
pieChartServices.data = piedata
pieChartServices.invalidate()
btnService.setOnClickListener {
exitProcess(0)
}
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
}
}

geting a java.lang.NullPointerException and i don't know where is the problem [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 9 months ago.
hey there i'm getting NullPointer Exception but I can't find where is the problem
my MainActivity.kt
class MainActivity : AppCompatActivity(), INotesRVAdapter {
lateinit var viewModel: NoteViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setTheme(R.style.AppTheme)
setContentView(R.layout.activity_main)
supportActionBar!!.title = "My Tasks"
rvTask.layoutManager = LinearLayoutManager(this)
val adapter = NotesRVAdapter(this,this)
rvTask.adapter = adapter
viewModel = ViewModelProvider(this,ViewModelProvider.AndroidViewModelFactory.getInstance(application)).get(NoteViewModel::class.java)
viewModel.allTask.observe(this, Observer { list->
list?.let {
adapter.updateList(it)
}
})
}
override fun onItemClicked(note: Note) {
viewModel.deleteTask(note)
Toast.makeText(this , " ${note.text} Task Completed",Toast.LENGTH_SHORT).show()
}
fun submitData(view: View) {
val noteText = etTask.text.toString()
if (noteText.isNotEmpty()){
viewModel.insertTask(Note(noteText))
Toast.makeText(this , "$noteText Added",Toast.LENGTH_SHORT).show()
}
}
}
my build.gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
android {
compileSdkVersion 32
defaultConfig {
applicationId "com.example.notesapp"
minSdkVersion 16
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildFeatures {
viewBinding = true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
packagingOptions {
exclude 'META-INF/atomicfu.kotlin_module'
}
kotlinOptions {
jvmTarget = "1.8"
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
var roomVersion = "2.4.2"
implementation "androidx.appcompat:appcompat:$rootProject.appCompatVersion"
implementation "androidx.activity:activity-ktx:$rootProject.activityVersion"
// To use Kotlin annotation processing tool (kapt)
kapt("androidx.room:room-compiler:$roomVersion")
// Dependencies for working with Architecture components
// You'll probably have to update the version numbers in build.gradle (Project)
// Room components
implementation "androidx.room:room-ktx:$roomVersion"
kapt "androidx.room:room-compiler:$roomVersion"
androidTestImplementation "androidx.room:room-testing:$roomVersion"
// Lifecycle components
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$rootProject.lifecycleVersion"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$rootProject.lifecycleVersion"
implementation "androidx.lifecycle:lifecycle-common-java8:$rootProject.lifecycleVersion"
// Kotlin components
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
api "org.jetbrains.kotlinx:kotlinx-coroutines-core:$rootProject.coroutines"
api "org.jetbrains.kotlinx:kotlinx-coroutines-android:$rootProject.coroutines"
// UI
implementation "androidx.constraintlayout:constraintlayout:$rootProject.constraintLayoutVersion"
implementation "com.google.android.material:material:$rootProject.materialVersion"
// Testing
testImplementation "junit:junit:$rootProject.junitVersion"
androidTestImplementation "androidx.arch.core:core-testing:$rootProject.coreTestingVersion"
androidTestImplementation ("androidx.test.espresso:espresso-core:$rootProject.espressoVersion", {
exclude group: 'com.android.support', module: 'support-annotations'
})
androidTestImplementation "androidx.test.ext:junit:$rootProject.androidxJunitVersion"
}
So after reading documentation i found that my room dependency needs to be upgraded and SDK also so after doing this app successfully instaled

implementation of cometchat sdk into kotlin project

I have been trying to implement comet Chat sdk into my project. I followed the documentation for kotlin but each time i try to initialize comet chat i get several errors. Here are my codes. 1. Main Activity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initCometChat()
}
private fun initCometChat() {
private val appID = "208314db190ca55b"
private val region = "us"
val appSettings = AppSettingsBuilder().subscribePresenceForAllUsers().setRegion(region).build()
CometChat.init(this, appID, appSettings, object : CallbackListener<String>() {
override fun onSuccess(successMessage: String) {
}
override fun onError(e: CometChatException) {
}
})
}
project level build gradle
plugins {
id 'com.android.application' version '7.1.1' apply false
id 'com.android.library' version '7.1.1' apply false
id 'org.jetbrains.kotlin.android' version '1.6.10' apply false
}
task clean(type: Delete) {
delete rootProject.buildDir
}
The CometChat.init() function returns an error marked with red. I am new to kotlin and so i do not know how sdks work. Please help me. Thank you
app level build gradle
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
}
android {
compileSdk 31
defaultConfig {
applicationId "com.chat.comet"
minSdk 21
targetSdk 31
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
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.appcompat:appcompat:1.4.1'
implementation 'com.google.android.material:material:1.5.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
implementation 'com.cometchat:pro-android-chat-sdk:3.0.4'
}

Dagger Hilt cannot create an instance of ViewModel having a constructor with arguments

After going through documentations and trying solutions of similar questions here on stackoverflow, nothing seems to fix the issue.
I tried altering all related dependencies, trying additional dependencies and tweaking the versions. Gradle builds successfully but there is a runtime error that through trial and error, the only method I found that could fix it was removing the argument from the ViewModel which is not desirable for me as the same setup used to work in my older projects.
RuntimeException
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example, PID: 17527
java.lang.RuntimeException: Cannot create an instance of class com.example.ui.MainViewModel
at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.kt:188)
build.gradle(:app)
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
id 'kotlin-kapt'
id 'dagger.hilt.android.plugin'
id 'com.google.devtools.ksp' version '1.6.10-1.0.2'
}
kotlin {
sourceSets {
debug {
kotlin.srcDir("build/generated/ksp/debug/kotlin")
}
release {
kotlin.srcDir("build/generated/ksp/release/kotlin")
}
}
}
android {
compileSdk 31
defaultConfig {
multiDexEnabled = true
applicationId "com.example"
minSdk 23
targetSdk 31
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
useSupportLibrary true
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
coreLibraryDesugaringEnabled true
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
freeCompilerArgs += '-Xopt-in=kotlin.RequiresOptIn'
}
buildFeatures {
compose true
}
composeOptions {
kotlinCompilerExtensionVersion compose_version
}
packagingOptions {
resources {
excludes += '/META-INF/{AL2.0,LGPL2.1}'
}
}
}
dependencies {
implementation 'androidx.core:core-ktx:1.7.0'
implementation "androidx.compose.ui:ui:$compose_version"
implementation 'androidx.compose.material3:material3:1.0.0-alpha04'
implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.4.0'
implementation 'androidx.activity:activity-compose:1.4.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"
debugImplementation "androidx.compose.ui:ui-test-manifest:$compose_version"
//lifecycle
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0"
implementation "androidx.lifecycle:lifecycle-viewmodel-compose:2.4.0"
//Hilt
implementation "com.google.dagger:hilt-android:$hilt_version"
kapt "com.google.dagger:hilt-compiler:$hilt_version"
implementation "androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha03"
kapt "androidx.hilt:hilt-compiler:1.0.0"
//Coroutines
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.0'
//DataStore
implementation "androidx.datastore:datastore-preferences:1.0.0"
//Desugaring
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5'
//Compose Destinations
implementation "io.github.raamcosta.compose-destinations:core:1.2.1-beta"
ksp "io.github.raamcosta.compose-destinations:ksp:1.2.1-beta"
build.gradle(Project)
buildscript {
ext {
compose_version = '1.2.0-alpha02'
hilt_version = "2.40.5"
}
dependencies {
classpath "com.google.dagger:hilt-android-gradle-plugin:$hilt_version"
}
}// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
id 'com.android.application' version '7.2.0-beta01' apply false
id 'com.android.library' version '7.2.0-beta01' apply false
id 'org.jetbrains.kotlin.android' version '1.6.10' apply false
id 'org.jetbrains.kotlin.jvm' version '1.6.10' apply false
}
task clean(type: Delete) {
delete rootProject.buildDir
}
MainViewModel.kt
#HiltViewModel
class MainViewModel #Inject constructor(
private val dataStoreRepository: DataStoreRepository
) : ViewModel() {...}
MainActivity.kt
#AndroidEntryPoint
class MainActivity : ComponentActivity() {
private val mainViewModel: MainViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
DestinationsNavHost(navGraph = NavGraphs.root)
}
}
}
Did you create module class? like below:
#Module
#InstallIn(SingletonComponent::class)
class RepositoryModule {
#Provides
#Singleton
fun provideDataStoreRepository(): DataStoreRepository = DataStoreRepository()
}

PreviewActivity is not an Activity subclass or alias Arctic Fox Stable and Compose 1.0.0

I just created a project and chose Compose Activity. When I try to click and run the Preview I get the following error:
androidx.compose.ui.tooling.PreviewActivity is not an Activity subclass or alias
Default code:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
DemoComposeTheme {
// A surface container using the 'background' color from the theme
Surface(color = MaterialTheme.colors.background) {
Greeting("Android")
}
}
}
}
}
#Composable
fun Greeting(name: String) {
Text(text = "Hello $name!")
}
#Preview(showBackground = true)
#Composable
fun DefaultPreview() {
DemoComposeTheme {
Greeting("Android")
}
}
With the default gradle configuration:
plugins {
id 'com.android.application'
id 'kotlin-android'
}
android {
compileSdk 30
defaultConfig {
applicationId "com.personaldemo.democompose"
minSdk 28
targetSdk 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
useSupportLibrary true
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
useIR = true
}
buildFeatures {
compose true
}
composeOptions {
kotlinCompilerExtensionVersion compose_version
kotlinCompilerVersion '1.5.10'
}
packagingOptions {
resources {
excludes += '/META-INF/{AL2.0,LGPL2.1}'
}
}
}
dependencies {
implementation 'androidx.core:core-ktx:1.6.0'
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.4.0'
implementation "androidx.compose.ui:ui:$compose_version"
implementation "androidx.compose.material:material:$compose_version"
implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.1'
implementation 'androidx.activity:activity-compose:1.3.0'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"
}

Categories

Resources