user12180120
user12180120

Reputation:

How to use "getActivity()" in fragment using kotlin

i want solve this problem.

this java code

Activity activity = getActivity();
            if (null != activity) {
                activity.finish();
            }

How I can use this code using kotlin?

 val activity: Activity = getActivity()
            activity.finish()

when I convert this code to kotlin like above code.

getActivity() -> get error.

Anyone can help?

Upvotes: 1

Views: 12913

Answers (4)

qtmfld
qtmfld

Reputation: 3187

I had the same question, when I was new to Kotlin.

In Java:

Activity a = getActivity();
if (null != a) {
  a.finish();
}

In Kotlin:

let a = activity
a?.finish()

or just

activity?.finish()

Interoperability between Java and Kotlin

It is clarified in Calling Java code from Kotlin:

Getters and Setters

Methods that follow the Java conventions for getters and setters (no-argument methods with names starting with get and single-argument methods with names starting with set) are represented as properties in Kotlin. ... [Emphasis added]

Accordingly, Java method getActivity() will be just a property activity in Kotlin.

In addition, the null-check if (null != a) { ... } will be just a?, which Gregory's answer has clarified.

Upvotes: 3

Gregory Nowik
Gregory Nowik

Reputation: 176

Getting activity from a fragment in Kotlin is optional (might be null) so the type must be Activity? then you have to safecall it like activity?.finish() and it won't crash with an NPE if activity is null.

Also, you can use property syntax and just call activity instead of getActivity().

https://kotlinlang.org/docs/reference/null-safety.html

Upvotes: 3

chand mohd
chand mohd

Reputation: 2550

Kotlin:

activity?.finish() // ? operator prevent of NPE 

Upvotes: 1

Mohamed AbdelraZek
Mohamed AbdelraZek

Reputation: 2799

For Fragment use activity instead of getActivity

Upvotes: 6

Related Questions