I need to pass intent from java activity to Kotlin activity:
Java activity ProfileActivity.class:
Intent selectGameIntent = new Intent(ProfileActivity.this, kotlin.jvm.JvmClassMappingKt.getKotlinClass(CreateNewPollUserActivity.class).getClass());
startActivity(selectGameIntent);
And this is my Kotlin activity:
class CreateNewPollUserActivity: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_create_new_poll_user)
val max = 45
val min = 10
val total = max - min}}
When i run it i have an error:
cannot find symbol
import com.myvote.Profile.ToolbarOption.CreateNewPollUserActivity;
any ideas how send intent from java activity to Kotlin activity?
add this in build.gradle project
buildscript {
ext.kotlin_version = '1.5.21'
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
And on top of build.gradle module file
apply plugin: 'kotlin-android'
This is the way to use call Kotlin class from Java class
Intent selectGameIntent = new Intent(ProfileActivity.this,
CreateNewPollUserActivity.class);
startActivity(selectGameIntent);
In your code, Probably the problem lays not in the Java-Kotlin relation, but in something else. Please check your code/project.
For this aim, you need to do several steps:
1-build.gradle project
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.10'
2- build.gradle app
plugins {
id 'com.android.application'
id 'kotlin-android'
}
3- Introduction the class and fun:
kotlin kt:
class CountTime(val activity: Activity) {
fun seeNext(t: String, c: String, ico: Int, i: Int) {
java MainActivity
CountTime countTime = new CountTime(this);
countTime.seeNext(t,c,ico,i);
and if there is a companion object
.Companion.getInstance();
Related
the setup:
Module 1 an external dependency that has Class A
Module 2 depends on Class A but may in the future depends on another module/class entirely
an APP depends on Module 2
I tried to add a typealias in Module 2 to Class A. it exposes the class "correctly" (lets say it is com.moduleTwo.ClassA instead of com.moduleOne.ClassA) but it makes it so that APP also needs to have a dependency on Module 1 or it doesn't compile with:
Cannot access class 'com.moduleOne.ClassA'. Check your module classpath for missing or conflicting dependencies
How can one make Module 2 expose an alias to Class A without adding Module 1 to APP build.gradle? Is there a way to "inject" the dependency to APP?
If I understood correctly you would like to replace a module without having app's code depending on external libraries.
When your app's code depends on only the abstraction and not concrete implementation you can replace those dependencies at any time.
The piece of code below shows that User in app module depends on interface A but the real implementation of A may vary.
// library module A
interface A {
fun doWork()
}
// library module B implements modules A & External
class B(private val external : External) : A {
override fun doWork() {
val result = external.getExternalStuff()
// more work with result
}
}
object Factory {
fun createB(params...): B {
val external = External(paramX)
// ...
return B(external)
}
}
// library module C implements module A
class C : A {
override fun doWork() {
println("C works")
}
}
// app
// User knows only 'A'
class User(private val a: A) {
fun help() {
a.doWork()
}
}
// Version 1: App implements modules A & B
// app module will know nothing about External
// but some factory or builder class to create B
fun appStarts() {
val a = Factory.createB(params...)
val user = User(a)
user.help()
}
// Version 2: App implements modules A & C
fun appStarts() {
val a = C()
val user = User(a)
user.help()
}
Hope this helps.
Trying to execute the below code :
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Test().list.contains(1)
}
}
public class Test {
ArrayList<Integer> list;
public ArrayList<Integer> getList() {
return list;
}
}
and compilation fails at Test().list.contains(1) with message :
Task :app:compileDebugKotlin FAILED
e: /Users/sreejithcr/Documents/MyApplication/app/src/main/java/com/wxample/myapplication/MainActivity.kt: (13, 31): Overload resolution ambiguity:
public open fun contains(#Nullable element: Int!): Boolean defined in java.util.ArrayList
public open fun contains(#Nullable element: Int!): Boolean defined in java.util.ArrayList
What i understand is compiler finds 2 contains() with exact same signature and not sure which one to call.
gradle config :
ext.kotlin_version = '1.3.41'
classpath 'com.android.tools.build:gradle:3.4.2'
It is an issue with Android Studios API 29 R2
https://issuetracker.google.com/issues/139041608#comment3
Go Tools -> SDK Manager -> Uninstall Android 9.+, then install it again as Google rolled back R2 so you'll be back to R1
As I read through your code I noticed some conflicts:
First, Test needs a public constructor, which creates the ArrayList, sth. like:
public Test(){
list = new ArrayList<>();
}
Second, make the variable list private, access should only be granted through getter/setter.
Third, in method onCreate() try:
new Test().getList().contains(1);
I have a module, UserModule that takes in a string and provides a user object.
UserModule:
#Module
class UserModule(val name: String) {
#Provides
fun provideUser() : User = User(name = name)
}
And a ViewModelComponent that has UserModule as one of its components
ViewModelComponent:
#Singleton
#Component(modules = [UserModule::class])
interface ViewModelComponent {
fun inject(activity: MainActivity)
}
Normally I would provide the component in my application like this:
class MainApplication : Application() {
lateinit var component: AppComponent
override fun onCreate() {
super.onCreate()
component = DaggerAppComponent.builder()
.userModule(UserModule("Name"))
.build()
}
}
And reference it in my activity like this:
class MainActivity : AppCompatActivity() {
#Inject lateinit var user: User
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
(application as MainApplication).component.inject(this)
}
However, this assumes that the value of UserModule name is known at runtime and is hardcoded into MainApplication, however, in reality, the value of name is obtained from MainActivity.
The only solution I can think of is to build the dependency graph in MainActivity so I am able to pass name like this:
class MainActivity : AppCompatActivity() {
#Inject lateinit var user: User
val newUserName = "NewName"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
component = DaggerAppComponent.builder()
.userModule(UserModule(newUserName))
.build()
component.inject(this)
}
This solution seems very unefficient but it is the only way I can inject dynamic parameters in Dagger 2. Is there a better way to achieve this
I just ran into this issue aswell, first solution that I thought of was to create some "static holder" class that would hold dynamic parameters and it would be developers responsibility to update this holder at the right time - before injection happens I guess. I didnt actually try it though and it doesnt seem to be too clean either.
Anway after a bit of googling I found this article: https://proandroiddev.com/dagger-2-module-parameters-7c820d944a which seems to be more "dagger oriented" solution, didnt try that either, but it's something you can start with.
I would only comment this but I dont have required reputation...
I'm making an Android app coding in Java just like everybody else's do. Since Android Studio 3.o Canary was released and adding support for Kotlin, I took a chance to give a try. Downloaded the plugins and setup the Gradle file correctly.
But once the activity is converted into Kotlin and synced, an error occured.
Below is my build.gradle,
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
and,
ext.kotlin_version = '1.1.3'
Dependencies, [
So, Im thinking to go back to Java until the issue is solved.
The Kotlin code are,
class Welcome : AppCompatActivity() {
internal var rujuk = FirebaseDatabase.getInstance().reference /*3rd step, DB reference*/
/*4th, initially write under onStart method, then CnP here, value inside child() should be same as in DB.*/
internal var referKpdTeksView = rujuk.child("intro")
#BindView(R.id.buku) internal var buku: ImageView? = null
#BindView(R.id.wel) internal var teksTajuk: TextView? = null /*1st step, declare variable for each Text*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_welcome)
ButterKnife.bind(this)
rujuk.keepSynced(true)
Glide.with(this).load("https://firebasestorage.googleapis.com/v0/b/travel-and-go-93552.appspot.com/o/buku.png?alt=media&token=bad59236-e4ff-44e0-81ac-32adf9c1aea4").diskCacheStrategy(DiskCacheStrategy.SOURCE).into(buku!!)
}
#OnClick(R.id.enterButton)
fun g() {
val EnterButton = Intent(this#Welcome, CountryList::class.java)
startActivity(EnterButton)
}
/*5th step, create onStart method*/
override fun onStart() {
super.onStart()
/*DB reference 4th step
* Syntax;
* DatabaseReference.addValueEventListener(new ValueEventListener)*/
referKpdTeksView.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val ayat = dataSnapshot.getValue(String::class.java)
teksTajuk!!.text = ayat
}
override fun onCancelled(databaseError: DatabaseError) {
}
})
}
}
and the error is,
Error:Failed to delete original file 'C:\Users\MohdA\AppData\Local\Temp\gradle_download1285409691272083864bin' after copy to 'C:\Users\MohdA.gradle\caches\modules-2\files-2.1\com.android.databinding\compilerCommon\2.3.3\1f0e06d55f3f72f3192b6e026d9a5a557d9e2ea6\compilerCommon-2.3.3.jar'
In intellij i resolved by going through show history , project right click local history then show history
I decided to use Parceler because it looks like a great library and it is very well supported by the author. I am using Parceler to wrap an object and pass it to another Activity in a Bundle. When I attempt to unwrap the object I am getting the error: android.os.Bundle cannot be cast to org.parceler.ParcelWrapper
My FirstActivity code:
User user = responseData.getUser();
Bundle bundle = new Bundle();
bundle.putParcelable("User", Parcels.wrap(user));
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("User", bundle);
startActivity(intent);
My SecondActivity code:
User user = Parcels.unwrap(this.getIntent().getParcelableExtra("User"));
I suspect this is just a newbie mistake. Any constructive assistance is appreciated!
You just need put wrapped object as argument for putExtra, not Bundle. Here is solution:
User user = responseData.getUser();
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("User", Parcels.wrap(user));
startActivity(intent);
On SecondActivity, in its onCreate() method do:
User user = (User) Parcels.unwrap(getIntent().getParcelableExtra("User"));
In kotlin you can do it as follows:
val user = responseData.getUser()
val bundle = Bundle()
bundle.putParcelable("User", Parcels.wrap(user))
val intent = Intent(this#FirstActivity, SecondActivity::class.java)
intent.putExtra("User", bundle)
startActivity(intent)
and in the second activity, where you are going to get the data you can do it as follows:
val user: User = Parcels.unwrap(data?.getParcelableExtra("User"))
NOTE: When using this library you need to use Parcels.wrap andParcels.unwrap
Although, I would recommend that if you use Kotlin you use #Parcelize annotation, since its implementation is very easy and your code is very clean.
If you want to implement #Parcelize you can do it as follows:
first, in your build.gradle file add the following:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
// ... other codes
// Add this code
androidExtensions {
experimental = true
}
}
second, create your data class User with the necessary properties:
#Parcelize
data class User(
val userId: Int,
val name: String,
// more properties
) : Parcelable