Inet 地址库显示:Java Android Studio 应用程序上的主线程错误

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

我一直在创建一个关于检查 x 个网站的 ip 的应用程序,我 imported:java。net.InetAddress 和 它将在 intelij 上运行但在 android studio 上,try/catch 块捕获了一些错误:android.os.NetworkOnMainThreadException。所以这是代码部分:

   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'

我从堆栈中看到了一些答案,例如:How to fix 'android.os.NetworkOnMainThreadException'? , https://www.tutorialspoint.com/how-to-fix-android-os-networkonmainthreadexception

.....

但它仍然不会显示网站的 IP 并再次显示错误。如果您对此问题有任何解决方案,请lmk。提前致谢!

更新:我试图放入一个布尔语句,但它使它变得更糟,抛出更多错误。语法这些块的格式可能是错误的吗?我应该在哪里修改代码?

您遇到问题是因为在 Android 中您只能在 MainThread 中访问视图,并且只能在 WorkerThread 中访问网络。

此外,您创建 AsyncTask 的方式也不正确。

我几年前就完全转向了 Kotlin,我已经有 3 年没有写 Java 了,但是这应该行得通:

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);
        };
    }
}

嗨,我按照安德烈的建议做了这个,它有点解决了问题和代码:

        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;
            }
        }
    }



}

但我仍然面临这个问题class

这是 XML 文件:

    <?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>

我已经尝试了很多修复互联网部分的解决方案,但仍然没有任何线索。如果您对此有任何想法或我哪里错了..谢谢!!1