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'
}
Related
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
I am trying to use Firebase Realtime database in Kotlin.
I have followed this tutorial but I think that something is wrong, because I get an error before compiling when I want to retrieve an instance of the database (Unresolved reference DataBasereference (or database if I uncomment the first line of the function tryToRead).
This is the code:
MainActivity.kt
package com.example.spesapp
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.google.firebase.ktx.Firebase
class MainActivity : AppCompatActivity() {
private lateinit var database: DataBasereference //Here I see "Unresolved reference"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun tryToRead(){
//val database = Firebase.database
val myref = database.getReference
}
}
Gradle (module level)
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
id 'com.google.gms.google-services'
}
android {
compileSdk 32
defaultConfig {
applicationId "com.example.frangelapp"
minSdk 21
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
}
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'
implementation platform('com.google.firebase:firebase-bom:30.0.1')
implementation 'com.google.firebase:firebase-analytics-ktx'
implementation 'com.google.firebase:firebase-auth-ktx'
implementation 'com.google.firebase:firebase-firestore-ktx'
implementation 'com.google.firebase:firebase-firestore'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
Gradle (Project level)
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
// Check that you have the following line (if not, add it):
google() // Google's Maven repository
}
dependencies {
// Add this line
classpath 'com.google.gms:google-services:4.3.10'
}
}
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
}
I don't know what is the error. The tutorial seemed to be very easy, but I am facing with this problem.
Thanks in advance
You get the following error:
Unresolved reference DataBasereference
Because you have not added the Realtime Database dependency in your project. To solve this, simply add:
implementation 'com.google.firebase:firebase-database-ktx'
Inside your build.gradle file.
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()
}
It seems that my Android Studio is not recognizing the 'androidx.core:core-ktx:1.2.0' package. Android Studio version: 3.6.1
My gradle.properties:
android.useAndroidX=true
# Automatically convert third-party libraries to use AndroidX
android.enableJetifier=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official
My app module build.gradle:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 29
defaultConfig {
applicationId "cz.nn.example.myapplication"
minSdkVersion 25
targetSdkVersion 29
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.toString()
targetCompatibility = JavaVersion.VERSION_1_8.toString()
}
kotlinOptions {
jvmTarget = "1.8"
}
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.core:core-ktx:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
}
When I try to use extension functions like:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val manager = systemService<NotificationManager>()
SharedPreferences.edit {
}
}
}
functions systemService<NotificationManager>() and edit are not recognized. What am I doing wrong?
TL;DR
You are using them wrongly
First of all SharedPreferences.edit() extension function is not static and needs an instance of SharedPreferences to be used on. Try this:
val prefs = getSharedPreferences("com.example.yourapp", Context.MODE_PRIVATE)
prefs.edit { putString("myString", "myValue") }
Secondly, the method is called getSystemService, not systemService. So, this will work:
val manager = getSystemService<NotificationManager>()
I added it when I made the project. AndroidX Artifact(checkBox) has not been mqt communication since then. What is the problem?
Androidx is used to use BiometricPrompt.
Below is my mqtt code.↓
private lateinit var mqttAndroidClient: MqttAndroidClient
val CLINET_ID: String = MqttClient.generateClientId()
fun connect(applicationContext : Context) {
val context: Context = applicationContext
mqttAndroidClient = MqttAndroidClient ( context.applicationContext,"tcp://13.124.231.98:1883",
CLINET_ID )
try {
val token = mqttAndroidClient.connect()
token.actionCallback = object : IMqttActionListener {
override fun onSuccess(asyncActionToken: IMqttToken) {
Log.i("Connection", "success ")
//connectionStatus = true
// Give your callback on connection established here
// publish("test", "open")
}
override fun onFailure(asyncActionToken: IMqttToken, exception: Throwable) {
//connectionStatus = false
Log.i("Connection", "failure")
// Give your callback on connection failure here
exception.printStackTrace()
}
}
} catch (e: MqttException) {
// Give your callback on connection failure here
e.printStackTrace()
}
}
Errors in the code above -> val token = mqttAndroidClient.connect()
My Build
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.myapplication"
minSdkVersion 28
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-
rules.pro'
}
}
buildToolsVersion '28.0.3'
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.0.0-beta01'
implementation 'androidx.core:core-ktx:1.2.0-rc01'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
//fingerPrint
implementation 'androidx.biometric:biometric:1.0.0-beta01'
//mqtt
implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.2'
implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.0-alpha4'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha4'
}
Is it a version problem?
I tried BiometricPrompt. in the version other than androidx to solve this problem, but an error occurred in the code that generated the Fragment and failed to resolve it.
Finally, I thought it would be good to run mqtt on Androidx, so I tried several times but failed.
If you've had a similar experience with me and you've solved it, help.
You should add the following dependencies to with androidx
androidx.legacy:legacy-support-v4:1.0.0
androidx.localbroadcastmanager:localbroadcastmanager:1.0.0
Find the conversion of the issue in GitHub here