android Asynctask thread.sleep? - android

In my app when user writes wrong character,my edittext becomes red then it becomes write.Actually ı am trying to make a red blink.This is my working code
class BlinkTask extends AsyncTask<EditText, Boolean, Boolean>
{
#Override
protected Boolean doInBackground(EditText... params) {
EditText et1=params[0];
try {
et1.setBackgroundColor(Color.RED);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
et1.setBackgroundColor(Color.WHITE);
}
catch (Exception e)
{
e.printStackTrace();
}
return true;
}
}
but when I take et1.setBackgroundColor(Color.WHITE); out of try-catch block.It gives no error but unfortunately myapp has stopped.I checked loggat but saw nothing.this is false code
class BlinkTask extends AsyncTask
{
#Override
protected Boolean doInBackground(EditText... params) {
EditText et1=params[0];
try {
et1.setBackgroundColor(Color.RED);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
et1.setBackgroundColor(Color.WHITE);
return true;
}
}
I don't know why it needs try-catch although it gives no error.
also ı want to ask creating a asynctask class for this task is a good solution or nwhat else can be done.thank you

You should use animations for this purpose.

AsyncTask does not run on the UI thread so it cannot touch UI components. But there is a trick to do so.
class BlinkTask extends AsyncTask<EditText, Integer, Boolean>
{
private EditText et1;
#Override
protected Boolean doInBackground(EditText... params) {
et1 = params[0];
try {
publishProgress(Color.RED);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
publishProgress(Color.WHITE);
}
catch (Exception e)
{
e.printStackTrace();
}
return true;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
et1.setBackgroundColor(values[0]);
}
}
But to be honest, changing a background color of edittext in an asynctask is a bad idea. Use should take a look at animations.

I think because you now are in a different thread of main thread and edit text is one element of UIthread then you must use your code inside UIthread.
you can search for "how to use runonUIthread in java android".
hope this help you.

Related

Android AsyncTask change

Why, when I change
private class DownloadTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... arg0) {
try {
Downloader.DownloadFromUrl("http://www.sciencemag.org/rss/news.xml", openFileOutput("Sciencemag.xml", Context.MODE_PRIVATE));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result){
mAdapter = new SiteAdapter(MainActivity.this, -1, XmlParser.getSingleItemsFromFile(MainActivity.this));
sitesList.setAdapter(mAdapter);
}
}
to
private void downloadFile(){
try {
Downloader.DownloadFromUrl("http://www.sciencemag.org/rss/news.xml", openFileOutput("Sciencemag.xml", Context.MODE_PRIVATE));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
mAdapter = new SiteAdapter(MainActivity.this, -1, XmlParser.getSingleItemsFromFile(MainActivity.this));
sitesList.setAdapter(mAdapter);
}
i get an error? I just want to call method downloadFile() instead of creating instance of inner class DownloadTask and call execute() of this instance.
The error is telling you that you cannot make network tasks on the main thread.
Look at the Android API where NetworkOnMainThreadException is defined to know more about it.
I hope this helps!
Imagine your method downloadFile() takes too long time - this will block the UI. To prevent this you should use AsyncTask which will do the background operations (downloading your file i guess) and when it is ready will update your UI. In doInBackground() put your downloadFile() method and in onPostExecute() deal with the result. Also be careful what parameters to give to your AsyncTask class.

AsyncTask slow with OnClick

Goodmorning,
I have a button on my android app that launches a search on the web (through google endpoints) through an AsyncTask. My problem is that the button does not "unclick" until the AsyncTask is completed, which may take several seconds. When the internet connection is slow, this even makes the application crash, in any case the application is completely stuck until the AsyncTask is completed. Now the reason for using AsyncTask was exactly to eliminate this problem, so I don't really get what happens!
Here is the OnClickListener:
SearchListener = new OnClickListener() {
#Override
public void onClick(View v) {
String cname=TextCourse.getText().toString();
if (!cname.isEmpty()){
try {
CollectionResponseWine listavini= new QueryWinesTask(messageEndpoint,cname,5).execute().get();
} catch (InterruptedException e) {
showDialog("Errore ricerca");
e.printStackTrace();
} catch (ExecutionException e) {
showDialog("Errore ricerca");
e.printStackTrace();
}
} else{
showDialog("Inserisci un piatto");
}
}
};
and here is the AsyncTask that is being called:
private class QueryWinesTask
extends AsyncTask<Void, Void, CollectionResponseWine> {
Exception exceptionThrown = null;
MessageEndpoint messageEndpoint;
String cname;
Integer limit;
public QueryWinesTask(MessageEndpoint messageEndpoint, String cname, Integer limit) {
this.messageEndpoint = messageEndpoint;
this.cname=cname;
this.limit=limit;
}
#Override
protected CollectionResponseWine doInBackground(Void... params) {
try {
CollectionResponseWine wines = messageEndpoint.listwines().setCoursename(cname).setLimit(limit).execute();
return wines;
} catch (IOException e) {
exceptionThrown = e;
return null;
//Handle exception in PostExecute
}
}
protected void onPostExecute(CollectionResponseWine wines) {
// Check if exception was thrown
if (exceptionThrown != null) {
Log.e(RegisterActivity.class.getName(),
"Exception when listing Messages", exceptionThrown);
showDialog("Non ci sono vini associati al tuo piatto. Aggiungine uno!");
}
else {
messageView.setText("Vini piu' votati per " +
cname + ":\n\n");
for(Wine wine : wines.getItems()) {
messageView.append(wine.getName() + " (" + wine.getScore() + ")\n");
}
}
}
}
...execute().get() is blocking. It makes UI thread wait for Task to complete.
Don't do get(). Use onPostExecute() to get the result (wines) of task and update the UI.

How can i Handle special kind of exception in doinBackground() method

I am making an android app which requires it to fetch some information from a remote server and therefore i have to make a http request in a async task.Now the problem is that that the response sometimes take more than 2 secs and when it does it give http timeout exception but most of the time it works just fine .So i want to implement the functionality that when i recieve a http timeout exception i want to retry the request again(try the doinBackground again,because network call can only be made in thread other than the main thread) because chances are that it will be successful and all the things that need to be fetched from the remote server will occur in CallRemoteServer() method
Now in my program i have implemented something like this
new AsyncTask<Void, Void, Void>() {
private boolean httpResponseOK = true;
#Override
protected Void doInBackground(Void... params) {
try {
CallRemoteServer();
}
} catch (Exception e) {
httpResponseOK = false;
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (httpResponseOK == false) {
//Show an alert dialog stating that unable to coonect
}
else
{
//update UI with the information fetched
}
});
Can someone advice me how can i implement something which i have mentioned above ,i mean that if i get some other exception other than timeout than show an alert dialog otherwise retry atleast five time more CallRemoteServer method before showing the dialog that unable to connect.
I am not able to think of any good way to implement this logic.
Thanks in advance
You're probably getting a ConnectTimeoutException (or check in the logs what is the IOException you're getting). I would first try to extend the timeout. Some similar answers for this can be found here or here.
However, an auto-reconnect mechanism is a must to have. I would implement it using recursive code:
final int maxAttempts = 5;
protected MyServerData callRemoteServer(int attempt) throws IOException {
try {
// do the IO stuff and in case of success return some data
} catch (ConnectTimeoutException ex) {
if(attempt == maxAttempts) {
return callRemoteServer(attempt + 1);
} else {
throw ex;
}
}
}
Your doInBackground method should look like:
#Override
protected Void doInBackground(Void... params) {
try {
callRemoteServer(0);
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
In this way if the connection timeouts it will attempt to retry for 5 max times (you can set the max attempts to anything you like). Just make sure to return some data from this IO operation as that is the most valuable asset from that method anyway ...
For this reason I would change it to following:
private class MyAsynckTask extends AsyncTask<Void, Void, MyServerData> {
#Override
protected MyServerData doInBackground(Void... params) {
try {
return callRemoteServer(0);
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(MyServerData result) {
if(result != null) {
// display data on UI
}
}
}

Progress Dialog does not display due to use of thread.get() method

I want to display a Progress Dialog while I have two threads running one after the other, but my data structure that I use gets populated via the threads, becomes null. Thus I used thread.get() method to wait for the thread to be finished....not sure how I can get around this here is an example of one of my Async Threads:
private void performDetailSearch(String reference) {
String addplus = searchterm.replace(" ", "+");
RestClientDS restpSd = new RestClientDS();
String url = PLACES_DETAILS_URL +"reference="+ reference + "&sensor=false&key=" + API_KEY;
Log.d("url",url);
String[] URL = {url};
restpSd.execute(URL);
try {
restpSd.get();
}
catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
catch (ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
Use AsyncTask instead of Thread and call another task after one gets completed.
AsyncTask can be called this way new FetchData().execute();
private class FetchData extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog = new ProgressDialog(HomeActivity.this);
/** progress dialog to show user that the backup is processing. */
/** application context. */
protected void onPreExecute() {
this.dialog.setMessage(getResources().getString(
R.string.Loading_String));
this.dialog.show();
}
protected Boolean doInBackground(final String... args) {
try {
//do your background work
return true;
} catch (Exception e) {
Log.e("tag", "error", e);
return false;
}
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
if (success) {
//call the another asynctask from here.
// new FetchData2().execute();
}
}
}

Grabbing a pic from URL

I just wanted to Grab an image from a URL and to display it in an imageview
The code:
public class MainActivity extends Activity {
// declare internal using controls
private TextView txtUrl;
private ImageView imgView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgView =(ImageView)findViewById(R.id.imageView1);
Drawable drawable=null;
drawable = grabImageFromUrl("http://blog.sptechnolab.com/wp-content/uploads/2011/02/c2.jpg");
imgView.setImageDrawable(drawable);
}
private Drawable grabImageFromUrl(String url) {
try {
return Drawable.createFromStream((InputStream)new URL(url).getContent(), "src");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
I am having this error:
09-04 20:34:18.712: E/AndroidRuntime(1156): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test/com.example.test.MainActivity}: android.os.NetworkOnMainThreadException
I would appreciate your help please be specific in your answers
Is your app configured with Internet permissions? That is, do you have the following in your app's manifest?
<uses-permission android:name="android.permission.INTERNET" />
FOLLOW UP: Also, the error seems to be saying you shouldn't do network access on your app's UI thread. It's generally a bad practice to do any long blocking I\O on your app's UI thread. Try using an AnycTask, or you might even have a look at some of the code in LazyList.
EXAMPLE: add this as an inner class to your activity:
private class DownloadTask extends AsyncTask<Void, Void, Drawable>{
private final String mUrl;
public DownloadTask(String url){
mUrl = url;
}
#Override
protected Drawable doInBackground(Void... params) {
try {
return Drawable.createFromStream((InputStream)new URL(mUrl).getContent(), "src");
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(Drawable result){
((ImageView)findViewById(R.id.imageView1)).setImageDrawable(result);
}
}
Then call it like this from your onCreate:
new DownloadTask(url).execute();
Take a look at this question in stack also :
Display image from URL - sizing and screen orientation problems
It could be helpful.
The easy way is to simply use setImageURI:
imgView = (ImageView)findViewById(R.id.imageView1);
imgView.setImageURI(Uri.parse("http://blog.sptechnolab.com/wp-content/uploads/2011/02/c2.jpg"));
As noted in the docs though:
This does Bitmap reading and decoding on the UI thread, which can cause a latency hiccup.
If that's a concern, you probably want to decode in an AsyncTask as suggested by another answer.

Categories

Resources