0

I´m trying to get variables from one Class to another after an API request with okhttp.

API Request (in my MainActivity): (with the normal class class MainActivity : AppCompatActivity(){ )

fun fetchJson() {
            val url = "https://......./api/.../....."

            val request = Request.Builder().url(url).build()

            val client = OkHttpClient()
            client.newCall(request).enqueue(object: Callback{

                override fun onResponse(call: Call, response: Response) {
                    val body = response?.body?.string()
                     println(body)
                    val gson = GsonBuilder().create()

                    val ApiStats = gson.fromJson(body, ApiStats::class.java)

                }

                override fun onFailure(call: Call, e: IOException) {
                    println("API execute failed")
                }
            })

        }

And the result will be "saved" in a extra Class:

class ApiStats(val apple: String)

And now I want to get the val in my MainActivity class which already mentioned before

I have already seen the possibility with a fun but it didn't seems to work for me...

I have also tried this: class MainActivity(val apiStats: ApiStaats) : AppCompatActivity()

But when I start the app it crashes the process

2020-02-25 13:36:53.466 10543-10543/example.spectre.vision E/AndroidRuntime: FATAL EXCEPTION: main
    Process: example.spectre.vision, PID: 10543
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{example.spectre.vision/example.spectre.vision.MainActivity}: java.lang.InstantiationException: java.lang.Class<example.spectre.vision.MainActivity> has no zero argument constructor
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3194)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
     Caused by: java.lang.InstantiationException: java.lang.Class<example.spectre.vision.MainActivity> has no zero argument constructor
        at java.lang.Class.newInstance(Native Method)
        at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
        at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1243)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3182)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016) 
        at android.os.Handler.dispatchMessage(Handler.java:107) 
        at android.os.Looper.loop(Looper.java:214) 
        at android.app.ActivityThread.main(ActivityThread.java:7356) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
 ```
B25Dec
  • 2,301
  • 5
  • 31
  • 54

3 Answers3

0

Try this one ==> class MainActivity : AppCompatActivity()

class MainActivity(val apiStats: ApiStaats : AppCompatActivity()

a constructor does not init at the class level and also check your manifest and if you want to pass param in-class use

 class MainActivity : AppCompatActivity(){
 companion object{
            fun xyzFunction(){
               //Some stuff 
            }
        }
}
  • thanks for the fast answer but i didnt get it... maybe my describtion was a litte bit confusing In the main file for my app ( all the other code ) ==> First code box is the API request and starts with the normal class MainActivity : AppCompatActivity(){ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) ...} and the result will "save" in the class ApiStats(val apple: String) and now i want to get the val apple in my main class btw i misst one "(" by the things i also tried –  Feb 25 '20 at 13:05
0

As the exception says: java.lang.InstantiationException: java.lang.Class example.spectre.vision.MainActivity has no zero argument constructor

MainActivity needs a zero(No) argument constructor for instantiation.

You should not put anything in the MainActivity's constructor or overload the constructor, as it is not recommended. Only Android OS can instantiate Android Components(Activitie,Services,Broadcast receivers,Content providers), fragments.

You can create a member variable in MainActivity and use the variable in your api callback.

Check this : Do fragments really need an empty constructor?

class MainActivity: AppCompatActivity(){

var apiStats: ApiStats? = null

}

Bheem
  • 189
  • 2
  • 9
  • okay i got that with the error but not really how to correct that... I knwo a member variable from java but i dont know how to create one in kotlin and maybe you can explain me your idea a litte bit more... because i didnt get it thx –  Feb 25 '20 at 14:20
0

The reason you can't put the property in the Activity constructor is that Android requires all Activities to have no arguments in the constructor. This is not a typical Java or Kotlin requirement, but Android uses the empty constructor to create instances of your Activity via reflection. You can put the property in the body of the class like this:

class MyActivity: AppCompatActivity() {
    var apiStats: ApiStats? = null

    //...
}

Then there's the matter of getting that data back from your other object. Replace this line:

val ApiStats = gson.fromJson(body, ApiStats::class.java)

with

apiStats = gson.fromJson(body, ApiStats::class.java)

You will probably want to follow that line with other code that updates the UI or something.

Tenfour04
  • 83,111
  • 11
  • 94
  • 154