[英]Why is my code not working in a AsyncTask using the JSoup library for my Android activity?
public class ConnectionTest extends AsyncTask<Void, Void, Void> {
String connection;
String loginFormUrl = "https://intranet.tam.ch/";
@Override
protected Void doInBackground(Void... voids) {
try{
Connection.Response loginForm = Jsoup.connect(loginFormUrl).method(Connection.Method.GET)
.execute();
connection = loginForm.toString();
System.out.print(title);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
My Activity should just display the connection in a TextView. 我的活动应该只在TextView中显示连接 。 I have also tried making a Thread and running it in the new Thread but it also won't work.
我也尝试过制作一个线程并在新线程中运行它,但是它也无法正常工作。
Here is my Activity 这是我的活动
public class Test extends AppCompatActivity {
TextView textView;
ConnectionTest connectionTest = new ConnectionTest();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
connectionTest.getWebsite();
textView = findViewById(R.id.sdweedew);
textView.setText(connectionTest.connection);
}
} }
please check this code 请检查此代码
private void getWebsite() {
new Thread(new Runnable() {
@Override
public void run() {
final StringBuilder builder = new StringBuilder();
try {
Document doc = Jsoup.connect("https://intranet.tam.ch/").get();
String title = doc.title();
Elements links = doc.select("a[href]");
builder.append(title).append("\n");
for (Element link : links) {
builder.append("\n").append("Link : ").append(link.attr("href"))
.append("\n").append("Text : ").append(link.text());
}
} catch (IOException e) {
builder.append("Error : ").append(e.getMessage()).append("\n");
}
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText(builder.toString());
}
});
}
}).start();
} }
Change your activity code like this, 像这样更改您的活动代码,
I've used a TextView
to display the status of the connection. 我使用了
TextView
来显示连接状态。
public class MainActivity extends AppCompatActivity {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
textView = findViewById(R.id.sdweedew);
new ConnectionTest().execute();
}
class ConnectionTest extends AsyncTask<Void, Void, String> {
String loginFormUrl = "https://intranet.tam.ch/";
@Override
protected String doInBackground(Void... voids) {
try {
Connection.Response loginForm = Jsoup.connect(loginFormUrl).method(Connection.Method.GET)
.execute();
return loginForm.statusMessage();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
if (textView != null) {
textView.setText(s);
}
super.onPostExecute(s);
}
}
}
And remember to add Internet permission in manifest file. 并记住在清单文件中添加Internet权限。
<uses-permission android:name="android.permission.INTERNET" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.