After recieving a pictures from user, putting them in an array, animate() method is called from main, this method contains Asynktask. How can I finish this AsyncTask?
This is my code:
private void animate() {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
iv.setImageResource(pics[0]);
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
while (true) {
try {
Thread.sleep(500);
runOnUiThread(new Runnable() {
#Override
public void run() {
iv.setImageResource(pics[pos]);
pos = (pos + 1);
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}.execute();
}
From your code, I guess what you want is to change the image you show in an ImageView periodically. I'd suggest to change your code to use a Timer:
private Timer mTimer;
private void startCarousel(){
mTimer = new Timer();
TimerTask timerTask = new TimerTask() {
public void run() {
// Your periodic task...
}
};
mTimer.schedule(timerTask, 1000, 500);
}
private void stopCarousel(){
if(mTimer != null){
mTimer.cancel();
mTimer.purge();
}
}
Related
I have created code in that when I click on suppose A Image, then B Image should show for 100 Milliseconds and then goes off
I have done this by Java Code
public void changeRightDrum() {
System.out.println("RIGHT");
imageViewB.setVisibility(View.VISIBLE);
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
imageViewB.setVisibility(View.GONE);
System.out.println("RIGHT DONE");
}
But it is not working B image is not displaying
Can anybody help me how to achieve that
You're blocking the UI thread with sleep() and any UI updates cannot really be performed.
Instead of sleeping, use a Handler with postDelayed() to schedule a Runnable to run after a delay.
Use postDelayed like this.
public void changeRightDrum() {
System.out.println("RIGHT");
imageViewB.setVisibility(View.VISIBLE);
imageViewB.postDelayed(new Runnable() {
#Override
public void run() {
imageViewB.setVisibility(View.GONE);
System.out.println("RIGHT DONE");
}
}, 100);
}
Implementing what #laalto said :
public void changeRightDrum() {
System.out.println("RIGHT");
imageViewB.setVisibility(View.VISIBLE);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
imageViewB.setVisibility(View.GONE);
System.out.println("RIGHT DONE");
}
},200);
}
I have achieved by using this
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
imgPressedLeftTabla.setVisibility(View.VISIBLE);
super.onPreExecute();
}
#Override
protected void onPostExecute(Void result) {
imgPressedLeftTabla.setVisibility(View.GONE);
super.onPostExecute(result);
}
#Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(50);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}.execute();
I want run run a thread after one thread completes its execution.
Here I am using progress bar, after progress bar completes the method do1() should execute but when I am run the application the application force close.
here is my code..
public void onenc(View view) {
progressBar = new ProgressDialog(view.getContext());
progressBar.setCancelable(true);
progressBar.setMessage("Ecoding Text ...");
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setProgress(0);
progressBar.setMax(100);
progressBar.show();
//reset progress bar status
progressBarStatus = 0;
//reset filesize
fileSize = 0;
new Thread(new Runnable() {
public void run() {
while (progressBarStatus < 100) {
// process some tasks
progressBarStatus = doSomeTasks();
// your computer is too fast, sleep 1 second
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
progressBarHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressBarStatus);
}
});
}
// ok, file is downloaded,
if (progressBarStatus >= 100) {
// sleep 2 seconds, so that you can see the 100%
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
// close the progress bar dialog
progressBar.dismiss();
}
}
}).start();
Thread tt =new Thread(new Runnable() {
public void run() {
do1();
try {
Thread.sleep(1100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
tt.start();
}
I have also tried AsyncTask but both run simultaneously.
Please help me I am a newbie in android.
Thanks in advance.
Update:
After AsyncTask
class MyFirstTask extends AsyncTask<String, Boolean, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
return null;
//Do Stuff
}
public void progressUpdate(Integer progress) {
new Thread(new Runnable() {
public void run() {
while (progressBarStatus < 100) {
// process some tasks
progressBarStatus = doSomeTasks();
// your computer is too fast, sleep 1 second
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
progressBarHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressBarStatus);
}
});
}
// ok, file is downloaded,
if (progressBarStatus >= 100) {
// sleep 2 seconds, so that you can see the 100%
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
// close the progress bar dialog
progressBar.dismiss();
}
}
}).start();
}
#Override
protected void onPostExecute(Boolean result) {
//Call your next task
Thread tt =new Thread(new Runnable() {
public void run() {
do1();
try {
Thread.sleep(1100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
tt.start();
}
}
Now not even a single thread is executing the application force closes
After Another Update
class MyFirstTask extends AsyncTask<String, Boolean, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
new Thread(new Runnable() {
public void run() {
while (progressBarStatus < 100) {
// process some tasks
progressBarStatus = doSomeTasks();
// your computer is too fast, sleep 1 second
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
progressBarHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressBarStatus);
}
});
}
// ok, file is downloaded,
if (progressBarStatus >= 100) {
// sleep 2 seconds, so that you can see the 100%
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
// close the progress bar dialog
progressBar.dismiss();
}
}
}).start();
return null;
//Do Stuff
}
public void progressUpdate(Integer progress) {
}
#Override
protected void onPostExecute(Boolean result) {
do1();
//Call your next task
/* Thread tt =new Thread(new Runnable() {
public void run() {
do1();
try {
Thread.sleep(1100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
tt.start();*/
}
}
Now the function do1() executes before progress bar completes.
Finally Solved it....Here is the answer.
Hope it will help others
class MyFirstTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.show();
}
#Override
protected String doInBackground(String... params) {
int i=0;
while(fileSize<100)
{
fileSize=fileSize+1;
publishProgress(""+(int)(fileSize));
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
publishProgress(""+(int)(fileSize));
return null;
}
public void onProgressUpdate(String... progress) {
progressBar.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String result) {
progressBar.dismiss();
do1();
}
}
Don't use Thread() at all. Use AsyncTask as it makes life easier and implement the onPostExecute() method to call the next AsyncTask
class MyFirstTask extends AsyncTask<String, Boolean, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
//Do Stuff that takes ages (background thread)
for(int i=0;i<100;i++){
doStuff();
Thread.sleep(1000L); //sleep because I'm just tired
publishProgress(i);
Thread.sleep(2000L); //sleep some more
}
}
#Override
public void progressUpdate(Integer progress) {
//Update progress bar (ui thread)
progressBar.setProgress(progress);
}
#Override
protected void onPostExecute(Boolean result) {
//Call your next task (ui thread)
new MyNextTask().execute();
}
Start your first task
new MyFirstTask().execute();
You can simply use join() method.
Thread first = new Thread();
Thread secThread =new Thread();
first.start();
first.join();
secThread.start();
but do not do this on main thread.
timer.setText("setTextHere") does not work inside the thread.
Thread thread1 = new Thread(){
TextView timer;
int t;
public void run(){
timer=(TextView) findViewById(R.id.timer);
try{
timer.setText("setTextHere");
sleep(5000);
}
catch(Exception e){
e.printStackTrace();
}
finally{
Intent new1 = new Intent("com.example.app1.MENU");
startActivity(new1);
}
}
};
thread1.start();
_t = new Timer();
_t.scheduleAtFixedRate( new TimerTask() {
#Override
public void run() {
_count++;
runOnUiThread(new Runnable() //run on ui thread
{
public void run()
{
_tv.setText( "" + _count );
}
});
}
}, 1000, 1000 );
You cannot touch UI from background thread. Try to use AsyncTask http://developer.android.com/reference/android/os/AsyncTask.html
On your onCreate() add:
h = new Handler();
add this somewhere:
class SetText implements Runnable {
public void run() {
// do UI task
timer.setText("setTextHere");
}
}
on someFunction() modify like this:
...
try
{
h.post( new SetText() );
sleep(5000);
}
...
final TextView timer = (TextView) findViewById(R.id.timer);
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(2000);
timer.post(new Runnable() {
public void run() {
timer.setText("setTextHere");
}
});
} catch (Exception e) {
e.printStackTrace();
} finally {
Intent new1 = new Intent("com.example.app1.MENU");
startActivity(new1);
}
}
}).start();
you could use this and initialize the setText before initializing the Thread
Thread thread1 = new Thread(){
int t;
public void run(){
try{
sleep(5000);
}
catch(Exception e){
e.printStackTrace();
}
finally{
Intent new1 = new Intent("com.example.app1.MENU");
startActivity(new1);
}
}
};
TextView timer;
timer=(TextView) findViewById(R.id.timer);
timer.setText("setTextHere");
thread1.start();
Is it possible to do splash screen that will execute HTTP request and if this request is executing too long, i.e. 7-10 seconds, then abort the request and jump to the main activity?
The below code is what I did, but it doesn't work - the timeout isn't working, the HTTP request and jumping are working. As I understand, it's possible to use the AsyncTask's get() method or handler with delay. Get() method should be in separate thread but it doesn't work. How to do this task?
EDIT:
public class SplashActivity extends Activity {
private static final String TAG = "SplashActivity";
private Handler handler = new Handler();
private Runnable r;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_layout);
if (Helpers.isNetworkConnected(getApplicationContext())) {
Log.d(TAG, "Has Internet");
final DownloadFAQ downloadFAQ = new DownloadFAQ();
new Thread(new Runnable() {
public void run() {
try {
Log.d(TAG, "Timing...");
downloadFAQ.execute().get(1000, TimeUnit.MILLISECONDS);
SplashActivity.this.runOnUiThread(new Runnable() {
public void run() {
Log.d(TAG, "redirect");
redirect();
}
});
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
downloadFAQ.cancel(true);
Log.d(TAG, "Task has benn canceled");
if (downloadFAQ.isCancelled())
redirect();
}
}
}).start();
} else {
r = new Runnable() {
public void run() {
redirect();
}
};
handler.postDelayed(r, 2500);
}
}
private class DownloadFAQ extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
Log.d(TAG, "Execute task");
ServerAPI server = new ServerAPI(getApplicationContext());
server.serverRequest(ServerAPI.GET_FAQ, null);
return null;
}
}
private void redirect() {
Intent i = new Intent(SplashActivity.this, TabsActivity.class);
startActivity(i);
finish();
}
#Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(r);
}
}
because you are trying to start AsyncTask again inside doInBackground when it's still running . change your code as to get it work :
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_layout);
downloadFAQ = new DownloadFAQ();
new Thread(new Runnable() {
public void run() {
try {
downloadFAQ.execute().get(2000, TimeUnit.MILLISECONDS);
SplashActivity.thisrunOnUiThread(new Runnable() {
public void run() {
// start Activity here
Intent i = new Intent(SplashActivity.this,
TabsActivity.class);
SplashActivity.this.startActivity(i);
SplashActivity.this.finish();
}
});
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
and you will need to remove downloadFAQ.get(2000, TimeUnit.MILLISECONDS); from doInBackground method change your AsyncTask as
private class DownloadFAQ extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
ServerAPI server = new ServerAPI(getApplicationContext());
server.serverRequest(ServerAPI.GET_FAQ, null);
return null;
}
protected void onPostExecute(Void result) {
}
}
consider using asyncTask status:
AsyncTask.Status
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ThraedDemo objDemo = new ThraedDemo();
Thread objThread = new Thread() {
#Override
public void run() {
objDemo.firstMethod();
}
};
objThread.start();
}
class ThraedDemo {
private void firstMethod() {
Thread objThread = new Thread() {
#Override
public void run() {
try {
((ImageView)findViewById(R.id.ImageViewnumber)).setImageResource(nums[n]);
Thread.sleep(10000);
Log.v("Thread","1111111111111111sleep");
} catch (InterruptedException ex) {
System.out.println("interuped exception" + ex.getMessage());
}
secondMethod();
}
private void secondMethod() {
Thread objThread = new Thread() {
#Override
public void run() {
try {
((ImageView)findViewById(R.id.ImageViewResult)).setImageResource(nums[n+1]);
n++;
Thread.sleep(10000);
Log.v("Thread","22222222222 sleep");
} catch (InterruptedException ex) {
System.out.println("interuped exception" + ex.getMessage());
}
firstMethod();
}
};
objThread.start();
}
};
objThread.start();
}
}
I use the above code but it is not running.it got CalledFromWrongThreadException what is the problem inb the above code.Please give me some suggestions.Thanks in advance
I think you can't do view modifications from another thread than the UI thread, so either create handlers in the oncreate and post your thread to it, or use AsyncTask, or runOnUIThread method to send portions of code directly to the UI thread.
I edited your 2nd function code, I see your code is loop forever cause the firstMethod call secondMethod and the secondMethod call the new firstMethod to start and then loop forever. I removed it and moved the code update ImageView into the UI Thread, could you try this:
class ThraedDemo {
private void firstMethod() {
Thread objThread = new Thread() {
#Override
public void run() {
try {
runOnUiThread(new Runnable() {
public void run(){
((ImageView)findViewById(R.id.ImageViewnumber)).setImageResource(nums[n]);
}
});
Thread.sleep(10000);
Log.v("Thread","1111111111111111sleep");
} catch (InterruptedException ex) {
System.out.println("interuped exception" + ex.getMessage());
}
secondMethod();
}
};
objThread.start();
}
private void secondMethod() {
Thread objThread2 = new Thread() {
#Override
public void run() {
try {
runOnUiThread(new Runnable() {
public void run(){
((ImageView)findViewById(R.id.ImageViewnumber)).setImageResource(nums[n+1]);
}
});
n++;
Thread.sleep(10000);
Log.v("Thread","22222222222 sleep");
} catch (InterruptedException ex) {
System.out.println("interuped exception" + ex.getMessage());
}
}
};
objThread2.start();
}
}