package com.example.application;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import com.example.androidtablayout.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class PhotosActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
String htmlCode = "";
Document doc;
try {
//Problem start
doc = Jsoup.connect("http://www.example.com/").get();
Element content = doc.select("a").first();
String variable = content.text();
// Problem end
TextView t = new TextView(this);
t=(TextView)findViewById(R.id.textView3);
t.setText(variable);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.photos_layout);
}
}
My problem is with JSoup framework. Between of “Problem” lines. I take the “Unexpectedly Stopped Error”.
When I put the “htmlCode” variable like this
t.SetText(htmlCode);
It is work but i get all of html source code .
What is the main problem , i can’t get it.
There’s a lot wrong with your code:
super.onCreate()should always be the very first call in your ownonCreate()You call
setContentView()at the very end but try tofindViewById()before that in the catch clause. At that point, yourActivityhas no content view yet, sofindViewById()will returnnull— the resultingNullPointerExceptionis most likely why your code crashes.You do IO on the UI thread. Don’t do that, Android will force-quit your app because IO is unpredictable and your app will be unresponsive, this is even worse with network IO. Check out AsyncTask on how to do IO off the UI thread and then asynchronously update your
TextView.Also, check out logcat. For most crashes, it will contain a stacktrace that will pinpoint where things went wrong.
Here’s a reworked version of your code that follows some of the advice I’ve given.
Please note that I did not have the time to fix the most important issue: This code still does IO on the UI thread. It should use an AsyncTask instead!