如何解决Inet地址库显示:Java Android Studio应用程序上的主线程错误
我一直在创建有关检查x网站IP的应用程序,并且我已经导入:java.net.InetAddress和它将在intelij上运行,但是在android studio上,try / catch块捕获一些错误:android.os.NetworkOnMainThreadException。所以这是代码部分:
# train the model and write logs to .txt file
with open(model_dest_dir + 'Deepspeech_progress.txt','w') as f:
train_model_proc = subprocess.Popen(train_cmds,cwd = '//DeepSpeech/',env = export_dict,stdout = subprocess.PIPE,stderr = subprocess.STDOUT,universal_newlines = True)
for line in train_model_proc.stdout:
sys.stdout.write(line)
f.write(line)
train_model_proc.wait() # wait for Popen to finish
f.close()
我从堆栈中看到了一些答案,例如:How to fix 'android.os.NetworkOnMainThreadException'?,https://www.tutorialspoint.com/how-to-fix-android-os-networkonmainthreadexception
....
但是仍然不会显示网站的IP地址并再次显示错误。如果您有解决此问题的任何方法,请lmk。在此先感谢!
更新:我试图放入一个布尔型语句,但是它抛出了更多的错误,甚至更糟。这些块的语法格式是否错误?我应该在哪里修复代码?
解决方法
您遇到了问题,因为在Android中,您只能访问MainThread中的View,而只能访问WorkerThread中的Network。
同样,您创建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,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);
};
}
}
,
您好,我按照安德烈(Andre)的建议进行了此操作,它可以解决问题和代码:
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,connection.Result<InetAddress>> task = new AsyncTask<String,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;
}
}
}
}
但是我仍然遇到此类问题
这是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>
我已经尝试了许多解决Internet部分问题的解决方案,但是仍然没有任何线索。如果您对此有任何想法,或者我错了..谢谢!1