0

I am trying to make a simple android app that makes a request to google, the expected behavior that my app should make a connection to google and then stop, what I got this error

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 4431
    java.lang.IllegalStateException: Could not execute method for android:onClick
        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:414)
        at android.view.View.performClick(View.java:7339)
        at android.widget.TextView.performClick(TextView.java:14275)
        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
        at android.view.View.performClickInternal(View.java:7305)
        at android.view.View.access$3200(View.java:846)
        at android.view.View$PerformClick.run(View.java:27787)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7078)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409)
        at android.view.View.performClick(View.java:7339) 
        at android.widget.TextView.performClick(TextView.java:14275) 
        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119) 
        at android.view.View.performClickInternal(View.java:7305) 
        at android.view.View.access$3200(View.java:846) 
        at android.view.View$PerformClick.run(View.java:27787) 
        at android.os.Handler.handleCallback(Handler.java:873) 
        at android.os.Handler.dispatchMessage(Handler.java:99) 
        at android.os.Looper.loop(Looper.java:214) 
        at android.app.ActivityThread.main(ActivityThread.java:7078) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964) 
     Caused by: android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1513)
        at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:117)
        at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:105)
        at java.net.InetAddress.getAllByName(InetAddress.java:1154)
        at com.android.okhttp.Dns$1.lookup(Dns.java:39)
        at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:196)
        at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:144)
        at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:89)
        at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:190)
        at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:142)
        at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:104)
        at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:392)
        at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:325)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:488)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:131)
        at com.example.myapplication.HttpRequest.request(HttpRequest.java:25)
        at com.example.myapplication.MainActivity.onClick(MainActivity.java:64)
        at java.lang.reflect.Method.invoke(Native Method) 
        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409) 
        at android.view.View.performClick(View.java:7339) 
        at android.widget.TextView.performClick(TextView.java:14275) 
        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119) 
        at android.view.View.performClickInternal(View.java:7305) 
        at android.view.View.access$3200(View.java:846) 
        at android.view.View$PerformClick.run(View.java:27787) 
        at android.os.Handler.handleCallback(Handler.java:873) 
        at android.os.Handler.dispatchMessage(Handler.java:99) 
        at android.os.Looper.loop(Looper.java:214) 
        at android.app.ActivityThread.main(ActivityThread.java:7078) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964) 

I am working on android studio 4.1.2 with API 30,I am running the app on my phone with android 9 Pie. My app has one button that makes a request, the that being executed is right here:

public void onClick(View view) {
    try {
        URL url = new URL("http://www.google.com/");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.connect();
        //do something
        conn.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

I have tried solutions that I found on internet but nothing work,I tried to edit my AndroidManifest.xml and I ended with this:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication">
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:networkSecurityConfig="@xml/network_security_config"
        android:usesCleartextTraffic="true"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyApplication">
        <activity android:name=".MainActivity2"></activity>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

I created a file network_security_config.xml:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">google.com</domain>
    </domain-config>
</network-security-config>

I am new to mobile development and I don't understand everything in the xml fils so maybe there is obvious mistake but I don't see it.

Thank you for your help.

obeda
  • 82
  • 10

1 Answers1

1

According to your error log, your problem is you're attempting to connect to the internet on the main thread. Android does not allow you to setup an internet connection on the main thread because that would freeze up everything else while it makes the connection. You need to connect on a different thread.

EDIT: In light of AsyncTask being depreciated, the recommended alternatives appear to be using the interfaces contained in java.util.concurrent to make threads and/or threadpools or the coroutine libraries for Kotlin. Be sure to check the documentation and make a thread that establishes the connection in the background.

Nordii
  • 479
  • 1
  • 5
  • 15
  • As `AsyncTask` is now deprecated I wouldn't recommend this approach. However the diagnosis seems correct. – Henry Twist Apr 08 '21 at 22:14
  • Thank you now I understand the problem but is there any better solution other than AsyncTask – obeda Apr 08 '21 at 22:32
  • @HenryTwist Thanks for letting me know. Wasn't aware of the depreciation. – Nordii Apr 08 '21 at 22:50
  • 1
    No problem, the current recommendation is to use either the Java concurrent or Kotlin coroutines libraries. Maybe update your answer @Nordii to say that instead? – Henry Twist Apr 08 '21 at 23:44