Android jsoup "Unfortunately Stop" - android

I have problem with jsoup. Every time I run application I got Unfortunately Stop. I tried all the ways and still getting it. I don't know what the wrong and this is simple from the code and I tried thread and didn't worked.
public class MainActivity extends Activity {
String result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new MyInnerClass().execute();
}
private class MyInnerClass extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try{
Document document = Jsoup.connect("http://google.come").get();
}catch(Exception e){Log.d("doinbackground exception", e.toString());}
return "Done";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
final TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(result);
}
}
}

Make correction here
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
final TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(result);
}
First the get the tv from your activity_main layout and than do setText to it
TextView tv= (TextView) findViewById(R.id.yourTextIDDefinedIn activity_main);
tv.setText(result);

i found the solution :
Press check box for android jsoup in :
(properties --> Java build path --> Order and export) .
Thanks guys.

Related

retrieving a specific text from a webpage android studio

I would like to build an app and in the app i want to pull a specific text from a website. So lets say that we want to retrieve and store the words "Connect with friends and the world around you on Facebook" from facebook.com. which is easy to get if i want to get the whole text from a specific website. Now lets say that we would like to get the word connect only or friends only from the website and store it into a string and print it.
what im doing is a currency app and getting the number http://www.hawlergov.org/en/currency.php and retrieving 128,800.
the number then prints out on the textView
I Answered my own question by splitting the string like this!
public class MainActivity extends AppCompatActivity {
TextView text;
TextView text2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.textView9);
text2 = (TextView) findViewById(R.id.textView8);
Button btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new doit().execute();
}
});
}
public class doit extends AsyncTask<Void, Void, Void> {
String words;
String currentString;
String date;
#Override
protected Void doInBackground(Void... params) {
try {
Document doc = Jsoup.connect("http://www.hawlergov.org/en/currency.php").get();
words = doc.text();
currentString = words;
} catch (Exception e) {
e.printStackTrace();
}
String first = words;
String roar = first.substring(718, 730);
words=roar;
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
String currentDate = new SimpleDateFormat("MM-dd-yyyy", Locale.getDefault()).format(new Date());
text2.setText(currentDate);
text.setText(words);
}
}
here is the example

Parse html in android app

When I'm trying to get the site title stackoverflow all goes well, but when I try to get the title beastinvest.su nothing happens. What is the reason?
public class MainActivity extends Activity {
/** Called when the activity is first created. */
Button butTest;
TextView textView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
butTest = (Button)findViewById(R.id.button);
textView = (TextView)findViewById(R.id.textView);
new MyParser().execute("http://beastinvest.su/");
}
public class MyParser extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... links) {
Document doc = null;
String title = null;
try {
doc = Jsoup.connect(links[0]).get();
title = doc.title();
textView.setText(title);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
}
Sorry for my bad English
the problem is that the site AntiDDOS - query returns "To visit this site requires cookies and javacript your browser."
Provided site (beastinvest.su) has title in Russian and contains <meta charset="windows-1251". I suppose that Jsoup uses UTF-8 encoding by default during parsing routine.
Hi use below code,
public class MainActivity extends Activity {
/** Called when the activity is first created. */
Button butTest;
TextView textView;
String title;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
butTest = (Button)findViewById(R.id.button);
textView = (TextView)findViewById(R.id.textView);
new MyParser().execute("http://beastinvest.su/");
}
public class MyParser extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... links) {
Document doc = null;
try {
doc = Jsoup.connect(links[0]).get();
title = doc.title();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
}
public void onPostExecute(String result) {
textView.setText(title);
}

Progress dialog not dismissing in async task

The progress dialog in AsyncTask does not dismiss, even though progressDialog.dismiss is run in onPostExecute().
I have tried implementing many answers to related questions on SO, with no success so far.
I am sure that I must be overlooking something very basic, but I am stuck.
Any pointers to an explanation and code snippet would be great, Thanks.
Main
public class Main extends Activity {
String result;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
asyncTask task = new asyncTask("Loading ...", this);
try {
result = task.execute("Question").get();
}
catch (Exception e) {
Log.e("Error: ", e.toString());
}
}
}
asyncTask
public class asyncTask extends AsyncTask<String, Void, String> {
private ProgressDialog progressDialog;
private String message;
private Context context;
public asyncTask(String msg, Context ctx) {
this.context = ctx;
message = msg;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.show(context, "", message, true, false);
}
#Override
protected String doInBackground(String... params) {
int count = 100000;
for (int i = 0; i < count; i++) {
// waste time
}
return "Answer";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
}
}
Actually your are doing :
progressDialog.show(context, "", message, true, false);
instead it should be like :
progressDialog = ProgressDialog.show(context, "", message, true, false);
You have to statically call show method and assign it to your progressDialog
Make this changes in your onPostExecute
#Override
protected void onPostExecute(String result) {
try{
if(progrssDialog.isShowing()){
progressDialog.dismiss();
}
}
catch(Exception e){
e.printStackTrace();
}
finally
{
progressDialog.dismiss();
}
}
A common issue i have found is the Variable Scope.
Most times , the ProgressDialog will be defined inside a Method , which wont be accessable outside that method.
You need to Declare it like so ,
Public Class MainActivity extends Activity {
ProgressDialog progressDialog;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private class asyncTask extends AsyncTask<String, Void, String> {
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
}
}
replace
task.execute("Question").get();
with
task.execute("Question");
by calling .get() you forcing main thread to wait. It will/can hang your UI.
progressDialog.dismiss();
put this in doInBackground() method before Return Statement.

Refresh Game Score TextView using AsyncTask

I am writing a board game in Android where the UI consists of textViews for the scores (CPUScore and PlayerScore). The problem I have is that the UI does not update the score from its initial value when onCreate is called. I have looked at similar questions and the solution most suggested is to use AsyncTask to update the UI thread in the background. However I did not find a solution that dealt explicitly with how to use textViews in AsyncTask.
Here is my attempt:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//....
setContentView(R.layout.main_layout);
//.....
//------------ textViews declared here don't refresh -------------------
TextView playerScoreForm = (TextView) findViewById(R.id.PlayerTotalScore);
playerScoreForm.setText(Integer.toString(PlayerTotal));
playerScoreForm.invalidate();
TextView CPUScoreForm = (TextView) findViewById(R.id.CPUTotalScore);
CPUScoreForm.setText(Integer.toString(CPUTotal));
CPUScoreForm.invalidate();
//--------------------------------------------------------------------------
//AsyncTask method:
new updatePlayerScore().execute(PlayerTotal);
new updateCPUScore().execute(CPUScoreForm);
}
The AsyncTask subclasses:
private class updatePlayerScore extends AsyncTask<TextView, Void, Void> {
#Override
protected TextView doInBackground(TextView... params) {
// what to put here??
}
return playerScoreForm;
}
#Override
protected void onProgressUpdate(Integer... values) {
//??
}
protected void onPostExecute(Integer result) {
playerScoreForm.setText(Integer.toString(result));
}
}
private class UpdateCPUScore extends AsyncTask<TextView, Integer, Integer> {
// same syntax as updatePlayerScore
}
Question:
how do I transfer the textViews that I declared in the onCreate method to the AsyncTask method? I am stumped. I am fairly new to Android development.
a) I'm pretty sure you shouldn't need to invalidate the TextViews after you set them; Android should do that automagically.
b) In theory you'd set your TextView references to be member variables and then reference them in onPostExecute instead of passing them into doInBackground. doInBackground in turn will take whichever bits of data enable you to calculate the new score. What you would do on doInBackground is whatever action would cause a new score to be calculated. The return value from doInBackground gets passed into onPostExecute. You would then update the TextView (now a member variable) with this data in onPostExecute. Does that make sense? You haven't actually posted any code here that would update those score values.
See here for a quick example.
private TextView myScoreView; //initialized in onCreate as you do above.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//....
setContentView(R.layout.main_layout);
//.....
myScoreView = (TextView) findViewById(R.id.PlayerTotalScore);
myScoreView.setText(Integer.toString(PlayerTotal));
new updatePlayerScore().execute(1,2); //parameters for calculation
}
private class updatePlayerScore extends AsyncTask<Integer, Integer, Integer> {
#Override
protected TextView doInBackground(Integer... params) {
int score = params[0] + 2 * params[1];
return score;
}
#Override
protected void onProgressUpdate(Integer... values) {
//if you want to provide some indication in the UI that calculation
//is happening, like moving a progress bar, that's what you'd do here.
}
#Override
protected void onPostExecute(Integer scoreCalculationResult) {
myScoreView.setText(Integer.toString(scoreCalculationResult));
}
}
Edit: If you don't want to do the calculation logic in doInBackgroundThread, you probably just want to use:
runOnUiThread(new Runnable(){
#Override
public void run(){
myScoreView.setText(PlayerScoreValue);
}
});
Or:
myScoreView.post(new Runnable(){
#Override
public void run(){
myScoreView.setText(PlayerScoreValue);
}
});
You can pass the TextView in the constructor of the AsyncTask and update it from the onPostExecute method
private class updatePlayerScore extends AsyncTask<Void, Void, Integer> {
private TextView view;
public updatePlayerScore(TextView textView){
this.view = textView;
}
#Override
protected Integer doInBackground(Void... params) {
int score = 0;
//do you calculation the
return score;
}
protected void onPostExecute(Integer result) {
view.setText(Integer.toString(result));
}
}
note: if you Activity configuration change for any reason i.e the user rotate the device and the you AsyncTask hasn't finish it task the update of you TextView will not be updated so you should retain an instance of you AsyncTask and update the the TextView

android asynctask edittext

I have a piece of code that querys my webserver xml parses the data that comes back and fills textfields on my GUi with the relevant data. Before i had this within my oncreate function and the code worked fine. However i wanted to show a loading dialogue to the user so i moved the web server and xml parsing operatons to an asynctask. The problem rises now when i go to populate my GUI text fields with my parsed data and i get an error thrown. Can anyone see what i am doing wrong
new BackgroundAsyncTask().execute(); /// called from the oncreate function
and my background task code is as follows
public class BackgroundAsyncTask extends
AsyncTask<Void, Integer, Void> {
int myProgress;
#Override
protected void onPostExecute(Void result) {
MyDialog.dismiss();
}
#Override
protected void onPreExecute() {
MyDialog = ProgressDialog.show(attraction_more_info.this, " " , " Loading. Please wait ... ", true);
}
#Override
protected Void doInBackground(Void... params) {
xml query and parse stuff on here ...
// Populate page now
TextView titlefield = (TextView) findViewById(R.id.att_title);
TextView add1field = (TextView) findViewById(R.id.att_address1);
TextView add2field = (TextView) findViewById(R.id.att_address2);
TextView townfield = (TextView) findViewById(R.id.att_town);
TextView postcodefield = (TextView) findViewById(R.id.att_postcode);
TextView phonefield = (TextView) findViewById(R.id.att_phone);
WebView webview = (WebView) findViewById(R.id.webview1);
MY ERRORS START HERE
titlefield.setText(attraction_name);
add1field.setText(attraction_address1);
add2field.setText(attraction_address2);
townfield.setText(attraction_town);
postcodefield.setText(attraction_postcode);
phonefield.setText(attraction_phone);
webview.loadData(attraction_description, "text/html", null);
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
}
}
Can anyone help me out?
You can't update UI elements from a non-UI thread. Try moving all the setText() calls and webview.loadData() to onPostExecute()
you'll have to save the query results in the class object to do that
Try this,
add1field.post(new Runnable() {
public void run() {
add1field.setText(attraction_address1);
}
});

Categories

Resources