I want change the text of a textView to match the title of a website.
For this, I'm connecting to https://www.google.com and getting its html source code. Then I fetch the title tag from it. (using JSoup)
The problem is that now I don't know how to change the textView. Since the networking is happening in a background thread, I don't have access to it. How and where should I do it?
Also, I know it connected successfully thanks to Log.w.
Here's what I have:
MainActivity
public class MainActivity extends AppCompatActivity {
Button btnConnect;
final String URL = "https://www.google.com";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnConnect = (Button) findViewById(R.id.btnConnect);
btnConnect.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// launch networking task
new EstablishConnectionTask().execute(URL);
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.awakened.tirafesi.awakenedprototype.MainActivity">
<Button
android:text="Establish Connection"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="@+id/btnConnect" />
<TextView
android:text="Placeholder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="87dp"
android:id="@+id/txtTitle" />
</RelativeLayout>
EstablishConnectionTask
public class EstablishConnectionTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String title;
try {
Document doc = Jsoup.connect(urls[0]).get();
title = doc.title();
} catch (IOException e) {
e.printStackTrace();
title = "NO";
}
return title;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.w("Title", s);
}
}