I'm trying to use jsoup to display temperature of Boston from a website as a toast message in an android app. My Java program looks like this:
public static void showWeather() throws IOException
{
Document doc = Jsoup.connect("http://www.wunderground.com/US/ma/boston.html?MR=1").get();
Elements languages = doc.select("#tempActual span.b ");
for(Element langElement: languages)
{
//System.out.println(" The temperature in Boston: "+langElement.text()+ " F");
}
}
The Java program works Okay and prints the temperature of Boston to the screen. I want to use this method to try to display the temperature as a toast in a simple android app, but when I try to run to method (without the print statement of course) in the onCreate method in my android activity, the program closes automatically. Here's my onCreate method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addKeyListener();
try {
showWeather();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Can anybody please tell how to run this java program in my android activity? I don't know how to treat the try/catch clause properly. I tried put toast in the catch clause but to no avail. Please help.
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
Reference:
http://developer.android.com/reference/android/os/AsyncTask.html
Usage
AsyncTask must be subclassed to be used. The subclass will override at least one method (doInBackground(Params...)), and most often will override a second one (onPostExecute(Result).)
Here is an example of subclassing:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
Once created, a task is executed very simply:
new DownloadFilesTask().execute(url1, url2, url3);
Related
I'm trying to check existence of 2000 files in Asynctask.
In the initial execution, it works well.
But if I restart app about 10 times , loading speed slows down.
As I am a beginner developer, I lack understanding of Asynctask.
Please give me some advices.
This is my splash activity
public class SplashActivity extends AppCompatActivity {
getFirstData gfd;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
gfd = new getFirstData(this, (TextView) findViewById(R.id.textView18));
gfd.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, this);
}
#Override
protected void onDestroy() {
try
{
if (gfd.getStatus() == AsyncTask.Status.RUNNING)
{
gfd.cancel(true);
}
else
{
}
}
catch (Exception e)
{
}
super.onDestroy();
}
}
And this is my asynctask code
public class getFirstData extends AsyncTask<Context,Integer,Void> {
private PowerManager.WakeLock mWakeLock;
private Context context;
private TextView textview;
getFirstData(Context context,TextView tv){
this.context=context;
this.textview=tv;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
PowerManager pm = (PowerManager) this.context.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
mWakeLock.acquire();
}
#Override
protected Void doInBackground(Context...contexts) {
Database.addDB();
for (int i = 0; i < Database.db_list.size(); i++) {
File filetemp = Database.getFilename(i, ".pdf", Database.db_list);
if (filetemp.exists()) {
Database.db_list.get(i).isDownloaded = true;
}
publishProgress(Database.db_list.size(),i);
}
return null;
}
#Override
protected void onProgressUpdate(Integer... params) {
super.onProgressUpdate(params);
textview.setText("Load("+params[1]*100/params[0]+"%)");
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Intent intent = new Intent(this.context, MainActivity.class);
this.context.startActivity(intent);
((Activity)this.context).finish();
}
}
AsyncTask cancel method doesn't immediately stop your AsyncTask, instead it'll only 'cancel' after doInBackground completes. (Reference)
Calling this method will result in onCancelled(java.lang.Object) being invoked on the UI thread after doInBackground(java.lang.Object[]) returns. Calling this method guarantees that onPostExecute(Object) is never subsequently invoked, even if cancel returns false, but onPostExecute(Result) has not yet run. To finish the task as early as possible, check isCancelled() periodically from doInBackground(java.lang.Object[]).
If you want your AsyncTask to end as quickly as possible, just make a check every 10 (or whatever value you deem suitable) iterations. Something along the following lines should work.
#Override
protected Void doInBackground(Context...contexts) {
Database.addDB();
for (int i = 0; i < Database.db_list.size(); i++) {
File filetemp = Database.getFilename(i, ".pdf", Database.db_list);
if (filetemp.exists()) {
Database.db_list.get(i).isDownloaded = true;
}
publishProgress(Database.db_list.size(),i);
if (i%10==0 && isCancelled()) {
break;
}
}
return null;
}
I see you actually read the manual! Good work!
While its a good effort, unfortunately, the basic approach really just won't work.
I'm not completely clear on what is making the app slow down. If by "restart" you mean back-arrow and then start from the Desktop, then in is probably because you have many downloads running at once. Note that there is no way to stop your AsyncTask once you start it: cancel doesn't actually do anything, unless you implement it.
Your AsyncTask has all the typical problems with leaking a context (Studio is probably yelling at you about this already: pay attention). There is no reason to believe that the Activity that starts the task is still there when the task completes.
My suggestion is that you separate the state of the app from the Activity that views that state. This approach has lots of names but usually something like ViewModel. The View model is some kind of singleton that only allows users to see the Splash page until its state changes (it has the files downloaded). Then it shows the MainActivity.
Good luck!
Hey Im trying to take a specific part of an website and then display it on my web view but the problem is when I do that , on smaller screens the letters got all bugged whit accents and stuff , is there any way that I can transfer just a specific div of the website to my web view that is not this bugged one ?
The part that I need in this website is called : "inside2"
This is the website: http://www.dges.gov.pt/guias/detcursopi.asp?codc=8184&code=0400
Code that I load the info :
private class MyTask extends AsyncTask<String, Integer, String> {
// Runs in UI before background thread is called
#Override
protected void onPreExecute() {
super.onPreExecute();
}
// This is run in a background thread
#Override
protected String doInBackground(String... params) {
// get the string from params, which is an array
Bundle CursoInfoData = getIntent().getExtras();
site = CursoInfoData.getString("site");
Document doc = null;
try {
doc = Jsoup.connect(site).get();
} catch (IOException e) {
e.printStackTrace();
}
ele = doc.select(".inside2");
return "start";
}
// This is called from background thread but runs in UI
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
// Do things like update the progress bar
}
// This runs in UI when background thread finishes
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
String text = "<html><head>"
+ "<style type=\"text/css\">body{color: #01A9DB; background-color: #FFFFFF;}"
+ "</style></head>"
+ "<body>"
+ ele.toString()
+ "</body></html>";
cursoInfoWeb.loadData(text, "text/html", "utf-8");
}
bugged form that I told you
You have utf-8 problem I guess. Use this:
cursoInfoWeb.loadDataWithBaseURL(null, text, "text/html", "UTF-8", null);
Reference: SO answer
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I am writing inside an activity.
I simply want to set a variable of this activity to true, wait 5 seconds and switch the variable back to false without freezing the current thread execution.
Any help is appreciated. I have googled this for hours and tried all sorts to no success.
I think what you are looking for is the AsyncTask.
http://developer.android.com/reference/android/os/AsyncTask.html
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
Once created, a task is executed very simply:
new DownloadFilesTask().execute(url1, url2, url3);
You can do that starting a Thread. Example:
boolean myvar = true;
new Thread(
new Runnable() {
public void run() {
SystemClock.sleep(5000);
myvar = false;
}
}
}).start();
you need to implement the ASyncTask interface, and sleep inside the doInBackground() method and change your variable back in the onPostExecute() method
in your class you have you boolean variable
boolean bValue = false;
Then add a private class inside your Activity
private class sleepFiveTask extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
bValue = true;
}
protected void doInBackground(Void... params) {
try {
Thread.sleep(5000); //sleep for 5 seconds
} catch (InterruptedException e) {
e.printStackTrace();
// handle the exception...
// For example consider calling Thread.currentThread().interrupt(); here.
}
}
protected void onPostExecute(Void result) {
bValue = false;
}
}
and when you want to execute it run
new sleepFiveTask ().execute();
I'm making a word game for android, and basically whenever a user enters something right I'm updating the score in the application, and I want to show the score on the screen to make it show in big then fade out slowly and get smaller, how can I do that? and is it possible to implement it in an AsyncTask class?
This is the method I'm using to check if the word entered is right.
public class checkWord extends AsyncTask<String, String, Void> {
private String c;
#Override
protected Void doInBackground(String... arg0) {
int size = correctWords.size();
String word = arg0[0];
for (int i = 0; i < size; i++) {
if (word.equalsIgnoreCase(correctWords.get(i))) {
publishProgress("bad");
}
}
try {
c = bufferedReader.readLine();
while (c != null && !c.equalsIgnoreCase(word)) {
c = bufferedReader.readLine();
}
if (c != null) {
correctWords.add(0, word);
score += word.length();
publishProgress("good");
} else {
incorrectWords.add(0, word);
publishProgress("bad");
}
} catch (IOException e) {
e.printStackTrace();
}
closeWordFile();
openWordFile();
return null;
}
So is there anyway I could pass a param to the publishProgress so that in onProgressUpdate I draw the score they got, for example +3 then make it fade out?
This is my onProgressUpdate where I add seconds to the timer and play a sound if it's a valid word or not
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
if (values[0].matches("bad"))
failureSound.start();
if (values[0].matches("good")) {
successSound.start();
if (countDownTimer != null) {
countDownTimer.cancel();
startTimer(countDownTime + c.length() / 2);
}
}
}
Because of Single threaded model in Android, only main thread can update UI, You can try the same in
runOnUiThread(new Runnable()
{
public void run()
{}
}
method.
Instead use a toast message. It will not affect your UI.
in the past few days I have been trying to figure something but had no luck, I am developing an android game, I have 3 packages for now each with its own purpose:
1 - package for GUI classes.
2 - package that has classes communicates with my wcf service (login/pass DB)
3 - package that holds my asynchronous classes/workers (like a bridge between GUI and SERVICE)
I am not sure if this is even the right approach when it comes to android/java game development, but what I want to achieve is a simple registeration/login in the GUI and when the user is done registering or logining, while the gui talks to the service through the "bridge", a message is displayed for the user like a dialog saying "registering" or "loging in".
Now I would like to hear tips/feedback from more experienced programmers, on how to acomplish this, and if this is the right aproach, and most importantly some examples for this specific case would be really helpfull, I tried to work with the asynctask but I couldn't figure out how to communicate between these 3 seperate packages and return the result from the service back to the gui through the async task.
Take a look at this
public class FindEventsActivity extends Activity {
ProgressDialog pd;
// lots of other code up here
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.clickete);
pd = new ProgressDialog(this);
pd.setMessage("loading");
findViewById(R.id.clickLayout).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
new LongOperation().execute("");
pd.show();
}
});
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
for (int i = 0; i < 15; i++) {
try {
Thread.sleep(1000); // Simulates your intensive work
// Update your progress if you want
this.publishProgress();
} catch (InterruptedException e) {
return "Failed";
}
}
return "Executed";
}
#Override
protected void onPostExecute(String result) {
// Handle fail or success accordingly
pd.dismiss();
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
// Update UI according to your progress
}
}
}
Hope this helps and enjoy your work