Android debugger and JSOUP: Source not found - java

I am trying to retrieve a website's html code and parse it to get the site's text. For some reason the class I have below runs fine when I comment out the jsoup library part of the code, but otherwise I get this weird error "source code not found", and the debug section does not hit any of the breakpoints. Not even those before any jsoup code. It jumps right to the error as soon as I hit the button on the emulator. I have the jsoup jar file added to my eclipse project as an external JAR in my java build path. What am I doing wrong?
BTW: I have jsoup 1.6.2
public class AndroidActivity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText eText = (EditText) findViewById(R.id.address);
final TextView tView = (TextView) findViewById(R.id.pagetext);
// TODO Auto-generated method stub
class TareaAsincrona extends AsyncTask<String, Void ,String>
{
#Override
protected void onPreExecute()
{
}
#Override
protected void onPostExecute(String X)
{
}
#Override
protected String doInBackground(String... urls)
{
try
{
// Perform action on click
URL url = new URL(eText.getText().toString());
URLConnection conn = url.openConnection();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
String Codigo_Fuente ="";
while ((line = rd.readLine()) != null)
{
Codigo_Fuente= Codigo_Fuente + line;
//Codigo_Fuente.add(line);//android.text.Html.fromHtml(line).toString());
}
Document doc = Jsoup.parse(Codigo_Fuente);
return doc.body().text();
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
}
}
final Button button = (Button) findViewById(R.id.ButtonGo);
button.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View arg0)
{
new TareaAsincrona().execute();
}
});
}
}

Did you add the library to the "libs" folder too?

Related

Asking the user for a URL to receive a JSON

Just as a practicing exercise i'm trying to make an app that fetches a JSON from a URL.
I found the following code in other thread here in stackoverflow and it works just fine. My problem is that the URL is hardcoded, and i need it to be an input by the user. What should i change/add?
public class MainActivity extends AppCompatActivity {
Button btnHit;
TextView txtJson;
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnHit = (Button) findViewById(R.id.btnHit);
txtJson = (TextView) findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonTask().execute("Url address here");
}
});
}
private class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line+"\n");
Log.d("Response: ", "> " + line); //here u ll get whole response..... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()){
pd.dismiss();
}
txtJson.setText(result);
}
}
}
This is the thread where i got that code from:
Get JSON Data from URL Using Android?
Create a constructor in your async Task
private class JSONTask extends AsyncTask<String, String, String> {
String url;
public JSONTask(String url){
this.url=url;
}
use the url string in place of params[0]
And wherever you call your async task do it like this
new JSONTask(textView.getText()).execute()
This should solve it.
Else you can directly use the do in background variable params.
So the problem is that you are using a TextView. TextView does not recieve inputs.
EditText does.
Make these Changes:
TextView txtJson;
In your OnCreate change this:
txtJson = (EditText) findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonTask().execute(txtJson.getText());
}
});
Now in your xml file change the Button to EditText.
Hope this helps.

Android HTTP API call

I am pretty fresh with Android Studio, and I am trying to call MVC Api service with api key and app id.
However, whenever i try the one with api key and app id, it always throws "Trust anchor for certification path not found." while it works good when i try the one without api key.
Can you give me a advice? Thank you.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button)findViewById(R.id.button);
tv = (TextView)findViewById(R.id.textView);
btn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
new JSONTask().execute("");
}
});
}
public class JSONTask extends AsyncTask<String, String, String>
{
#Override
protected String doInBackground(String... params) {
try{
StringBuilder result = new StringBuilder();
URL url2 = new URL(url);
HttpURLConnection conn = (HttpURLConnection) url2.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Apikey",key);
conn.addRequestProperty("AppID",id);
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}
catch (IOException e)
{
Log.e("MYAPP", "exception", e);
return "error";
}
}
protected void onPostExecute(String result)
{
super.onPostExecute(result);
tv.setText(result);
}
}
This kind of exceptions mostly occur because of the misconfiguration of a web service. Check out this article. It's fully described why you are getting this exception.

android WebView cant render my native language

Hello I am trying to load HTML (From String)
Here is the RSS feed (I am getting a link from there and after that HTML string from specific class ):
http://www.naec.ge/index.php?option=com_rsssyndicator&feed_id=1&format=raw
As you can see it is encoded in utf-8, but still I can't render it, it gives me this result: android web view result
Here are the code fragments :
class parseText extends AsyncTask<String,Void,String>
{
protected String doInBackground(String... params)
{
try {
org.jsoup.nodes.Document doc = Jsoup.connect(url).get();
System.out.println("hey kurwo "+doc.getElementsByClass("article-content"));
data = doc.getElementsByClass("article-content").toString();
} catch (IOException e) {
e.printStackTrace(); System.out.println("jeban!!");
}
return null;
}
#Override
protected void onPostExecute(String s) {
System.out.println("chiken boneZZZ");
view.loadData(data,"text/html","UTF-8");
super.onPostExecute(s);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
}
}
Also this, I don't think there is any problem :
public class NewsDetails extends Activity
{
static String url;
WebView view;
TextView info;
static String data;
String address;
Bundle bundle;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detailed_news_layout);
bundle = getIntent().getExtras();
url = bundle.getString("Link");
view = (WebView) findViewById(R.id.webview);
new parseText().execute();
}
here is a deal you have to use loaddatawithbaseurl instead of loadData(), here is example : this will not work view.loadData(data,"text/html","utf-8");
this will work :
view.loadDataWithBaseURL(null, data, "text/html", "UTF-8", null);

Android : AsynkTask and HttpConnection errors

i'm new in java and android programming , and by following some tutorial i've tried to make an Android App that have to make a Http request to a php page for reading the output string. I get the following errorr in doInBackground method :
Multiple markers at this line
- Exception MalformedURLException is not compatible with throws clause in
AsyncTask<Void,String,String>.doInBackground(Void[])
- Exception IOException is not compatible with throws clause in AsyncTask<Void,String,String>.doInBackground(Void[])
- Exception IOException is not compatible with throws clause in AsyncTask<Void,String,String>.doInBackground(Void[])
- implements android.os.AsyncTask<java.lang.Void,java.lang.String,java.lang.String>.doInBackground
- Exception MalformedURLException is not compatible with throws clause in
AsyncTask<Void,String,String>.doInBackground(Void[])
Any idea ?
Thank You
That's the MainActivity.java code :
public class MainActivity extends Activity {
Button button;
TextView finalResult;
public class ConnessioneAsyncTask extends AsyncTask<Void,String,String>{
#Override
public String doInBackground(Void... v) throws IOException, MalformedURLException{
try{
URL url = new URL("http://myUrl");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
BufferedReader read = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = read.readLine();
String html = "";
while (line != null){
html += line;
line = read.readLine();
}
return html;
}
catch(MalformedURLException ex){
System.out.println(ex.getMessage());
}
catch(Exception ee){
System.out.println(ee.getMessage());
}
}
#Override
public void onPreExecute(){
}
#Override
public void onPostExecute(String result){
finalResult.setText(result);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.asynkButton);
finalResult = (TextView) findViewById(R.id.textView1);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
ConnessioneAsyncTask runner = new ConnessioneAsyncTask();
runner.execute();
}
});
}
}
doInBackground Method does not declare any throws clause and you are trying to add throws declaration. you need to handle all exception with in your code only instead of declaring it using throws clause. Here is javadoc for the doInBackground method. So in a nutshell you need to remove throws clause in order to make it valid.

android network connection faliure

I'm having a hard time to connect the application to the internet and retrieve the html source.
Been looking all over for a solution and didn't find. Hope someone could help.
Here is my code:
public class Main extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText et = (EditText) findViewById(R.id.editText1);
final Button b = (Button) findViewById(R.id.button1);
final TextView tv = (TextView) findViewById(R.id.textView1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
URL url=null;
url = new URL(et.getText().toString());
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
tv.append(line);
}
} catch (Exception e) {
}
}
});
}
I've also added INTERNET permission..
You need to move the code which connects to the internet and fetches data to an AsyncTask. This is because of the NetworkOnMainThreadException. This exception is thrown when an application attempts to perform a networking operation on its main thread.
Though there is a workaround available by using the StrictMode.ThreadPolicy, it highly advisable not to do that.
Here is a excerpt from the docs.
NetworkOnMainThreadException:-
This is only thrown for applications
targeting the Honeycomb SDK or higher. Applications targeting earlier
SDK versions are allowed to do networking on their main event loop
threads, but it's heavily discouraged.
See this question for more info.
Because you are doing this on UI therad.
Try this:
public class Main extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText et = (EditText) findViewById(R.id.editText1);
final Button b = (Button) findViewById(R.id.button1);
final TextView tv = (TextView) findViewById(R.id.textView1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Thread th = new Thread() {
#Override
public void run() {
try {
URL url=null;
url = new URL(et.getText().toString());
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
tv.append(line);
}
} catch (Exception e) {
}
}
};
th.start();
}
});
}
i will suggest you to use AsyncTask
Do this
On ButtonClick
RequestClient reqClient = new RequestClient(ActivityName.this);
String AppResponse = null;
AppResponse = reqClient.execute().get();
RequestClient
public class RequestClient extends AsyncTask<String, Void, String> {
Context context;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
HttpClient httpclient = new DefaultHttpClient(); // Create HTTP Client
HttpGet httpget = new HttpGet("http://yoururl.com"); // Set the action you want to do
HttpResponse response = httpclient.execute(httpget); // Executeit
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent(); // Create an InputStream with the response
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) // Read line by line
sb.append(line + "\n");
String resString = sb.toString(); // Result is here
is.close(); // Close the stream
} catch (Exception e) {
Log.d("ANDRO_ASYNC_ERROR", "Error is " + e.toString());
}
Log.d("ANDRO_ASYNC_RESPONSE", responseString.trim());
client.getConnectionManager().shutdown();
return responseString.trim();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}

Categories

Resources