revolutionarybreak
revolutionarybreak

Reputation: 15

Inet Adress Library Shows: Main Thread Error On Java Android Studio App

I've Been creating an app about checking the ip of x websites and I've imported:java.net.InetAddress and It will work on intelij but on android studio the try/catch block catches some errors: android.os.NetworkOnMainThreadException. So this the code part:

   AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                submit.setOnClickListener(new View.OnClickListener() {
    
                    @Override
                    public void onClick(View v) {
    
                        InetAddress address = null;
                        try {
                            address = InetAddress.getByName(String.valueOf(hostnumber));
                        } catch (UnknownHostException e) {
                            e.printStackTrace();
                        }catch (Exception e) {
                            Toast.makeText(Lookup.this,"Problem"+e, Toast.LENGTH_SHORT).show();
                        }
    
                        output.setText((CharSequence) address);
    

                    }
                });
    
            }
        });


I've added the internet permission on manifest: <uses-permission android:name="android.permission.INTERNET" />

The try/catch block caught: 'android.os.NetworkOnMainThreadException'

I saw some answers from stack such as: How to fix 'android.os.NetworkOnMainThreadException'? , https://www.tutorialspoint.com/how-to-fix-android-os-networkonmainthreadexception

....

BUT still it wouldn't show the IPs of the websites and show the error again. If you have any solution to this problem please lmk. Thanks In Advance!

UPDATE: I tried to put a boolean statement but it made it even worse throwing some more errors. Is maybe the wrong format to syntax these blocks? where should I fix the code?

Upvotes: 0

Views: 491

Answers (2)

revolutionarybreak
revolutionarybreak

Reputation: 15

Hi I did this as Andre suggested and it kinda solved the problem and the code:

        EditText hostnumber;
    TextView output;
    Button submit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lookup);

        hostnumber = findViewById(R.id.hostnumber);
        output = findViewById(R.id.output);
        submit = findViewById(R.id.submit);
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                @SuppressLint("StaticFieldLeak") AsyncTask<String, Void, connection.Result<InetAddress>> task = new AsyncTask<String, Void, connection.Result<InetAddress>>() {
                    // NOTE: this method runs in a background thread, you cannot access the View from here
                    @Override
                    protected connection.Result<InetAddress> doInBackground(String... hostnumber) {
                        connection.Result<InetAddress> result;
                        try {
                            result = new connection.Result.Success(InetAddress.getByName(String.valueOf(hostnumber)));
                        } catch (UnknownHostException e) {
                            e.printStackTrace();
                            result = new connection.Result.Failure(e);
                        }catch (Exception e) {
                            result = new connection.Result.Failure(e);
                        }

                        return result;
                    }


                    @Override
                    protected void onPostExecute(connection.Result<InetAddress> result) {
                        if (result instanceof connection.Result.Success) {
                            output.setText((CharSequence) ((connection.Result.Success<InetAddress>) result).data);
                        } else if (result instanceof connection.Result.Failure) {
                           Throwable error = ((connection.Result.Failure<InetAddress>) result).error;
                            Toast.makeText(Lookup.this,"Please Check The Address!: " +error, Toast.LENGTH_SHORT).show();

                        }
                    }
                };

                task.execute(hostnumber.toString());
            };
        })
        ;}
}

class connection extends Activity {
    static class Result<T> {
        static class Success<T> extends Result<T> {
            public T data;
            public Success(T data) {
                this.data = data;
            }
        }
        static class Failure<T> extends Result<T> {
            public Throwable error;
            public Failure(Throwable error) {
                this.error = error;
            }
        }
    }



}

But I'm still facing the problem with this class

This is the XML FILE:

    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Lookup">

    <EditText
        android:id="@+id/hostnumber"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="98dp"
        android:ems="10"
        android:inputType="textUri|textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/submit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="61dp"
        android:text="Button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/hostnumber" />

    <TextView
        android:id="@+id/output"
        android:layout_width="100dp"
        android:layout_height="47dp"
        android:layout_marginStart="63dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="312dp"
        android:text="TextView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.186"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/submit" />


</androidx.constraintlayout.widget.ConstraintLayout>

I've tried a lot of solutions with Fixing the internet part but still no clue. If you can have any idea with this or where i'm wrong .. thanks!!1

Upvotes: 0

Andre Romano
Andre Romano

Reputation: 1012

You're having issues because in Android you can only access the View in the MainThread and you can only access the Network in a WorkerThread.

Also the way you're creating the AsyncTask is not correct.

I've fully switched to Kotlin years ago, and I don't write Java for a good 3 years, this however should work:

public class Testss extends Activity {
    static class Result<T> {
        static class Success<T> extends Result<T> {
            public T data;
            public Success(T data) {
                this.data = data;
            }
        }
        static class Failure<T> extends Result<T> {
            public Throwable error;
            public Failure(Throwable error) {
                this.error = error;
            }
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...

        submit.setOnClickListener(new View.OnClickListener() {
            AsyncTask<String, Void, Result<InetAddress>> task = new AsyncTask<String, Void, Result<InetAddress>>() {
                // NOTE: this method runs in a background thread, you cannot access the View from here
                @Override
                protected Result<InetAddress> doInBackground(String... hostnumber) {
                    Result<InetAddress> result;
                    try {
                        result = new Result.Success(InetAddress.getByName(String.valueOf(hostnumber)));
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                        result = new Result.Failure(e);
                    }catch (Exception e) {
                        result = new Result.Failure(e);
                    }

                    return result;
                }

                // NOTE: this method runs in the mainthread
                @Override
                protected void onPostExecute(Result<InetAddress> result) {
                    if (result instanceof Result.Success) {
                        output.setText((CharSequence) ((Result.Success<InetAddress>) result).data);
                    } else if (result instanceof Result.Failure) {
                        Throwable error = ((Result.Failure<InetAddress>) result).error
                        Toast.makeText(Lookup.this,"Problem"+error, Toast.LENGTH_SHORT).show();
                    }
                }
            };
            
            task.execute(hostnumber);
        };
    }
}

Upvotes: 1

Related Questions