Changing image in imageview using Threads - android

I'm getting error with this code. Why huhu
123123123
Thread timer = new Thread()
{
public void run()
{
try
{
sleep(1500);
splash.setImgeResource(R.drawable.dilclogo);
sleep(1500);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
finally
{
Intent intent = new Intent(MainActivity.this, MenuScreen.class);
startActivity(intent);
}
}
};
timer.start();

This is because you can NOT access your UI/Main thread directly from any other thread. You can use below methods to access your UI thread though:
Using AsyncTask
Using runOnUiThread()
You can also read this article on threading in android to help you understand this concept better.

put splash.setImgeResource(R.drawable.dilclogo); line into runOnUiThread .
Thread timer = new Thread()
{
public void run()
{
try
{
sleep(2000);
runOnUiThread(new Runnable() {
public void run() {
splash.setImageResource(R.drawable.billboard_image);
}
});
sleep(2000);
runOnUiThread(new Runnable() {
public void run() {
splash.setImageResource(R.drawable.square);
}
});
}
catch (InterruptedException e)
{
e.printStackTrace();
}
finally
{
System.out.println("finally");
}
}
};
timer.start();

You should update ui on the ui thread. Use runonUithread.
runOnUiThread(new Runnable() {
#Override
public void run() {
// set image to imageview here
// ui should be updated on the ui thread.
// you cannot update ui from a background thread
}
});
But i would suggest you to use a handler.
public class Splash extends Activity {
//stopping splash screen starting home activity.
private static final int STOPSPLASH = 0;
//time duration in millisecond for which your splash screen should visible to
//user. here i have taken half second
private static final long SPLASHTIME = 500;
//handler for splash screen
private Handler splashHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case STOPSPLASH:
//Generating and Starting new intent on splash time out
Intent intent = new Intent(Splash.this,
MainActivity.class);
startActivity(intent);
Splash.this.finish();
break;
}
super.handleMessage(msg);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
//Generating message and sending it to splash handle
Message msg = new Message();
msg.what = STOPSPLASH;
splashHandler.sendMessageDelayed(msg, SPLASHTIME);
}
}
splash.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:background="#drawable/mydrawable">
// have a imageview and set background to imageview
</RelativeLayout>
Using handlers and postdelayed
public class Splash extends Activity {
private static final int SPLASH_TIME = 2 * 1000;// 3 seconds
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
ImageView iv= (ImageView) findViewById(R.id.imageView1);
iv.setBackgroundResource(R.drawable.afor);
try {
new Handler().postDelayed(new Runnable() {
public void run() {
Intent intent = new Intent(Splash.this,
MainActivity.class);
startActivity(intent);
Splash.this.finish();
}
}, SPLASH_TIME);
} catch(Exception e)
{
e.printStacktrace();
}
}
#Override
public void onBackPressed() {
this.finish();
super.onBackPressed();
}
}
splash.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:background="#ffffaa">
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_centerInParent="true"
/>
</RelativeLayout>

You can not use normal threading on android system.
Give you some example on thread on android :D
---> Android Asynctask
Android Developer - Android Asynctask
You can use this for some loading effect on UI in android.
---> runOnUiThread
In your case, I suggest to use this.
You can have more detail here.
Click for detail
USEAGE::
runOnUiThread(new Runnable() {
#Override
public void run() {
// Do you ui update here
}
});

public class vv extends Activity {
int b[] = {R.drawable.a, R.drawable.m, R.drawable.b, R.drawable.j, R.drawable.er, R.drawable.chan, R.drawable.vv};
public ImageView i;
int z = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
i = (ImageView) findViewById(R.id.image);
i.setImageResource(b[0]);
Thread timer = new Thread() {
public void run() {
try {
sleep(2000);
for (z = 0; z < b.length + 2; z++) {
if (z < b.length) {
sleep(2000);
runOnUiThread(new Runnable() {
public void run() {
i.setImageResource(b[z]);
}
});
} else {
z = 0;
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("finally");
}
}
};
timer.start();
}
}

Perhaps consider using
AsyncTask.execute(new Runnable {
public void run() {
splash.setImageResource(R.drawable.square);
}
});

Related

Should I pause my thread or not Android

So I have thread where it checks every 10ms's if drag is almost outside draggingzone. Basicly my thread code is doing nothing 99% of time so should I make it to pause and resume only when needed? Or does this literally do nothing when right and left are false?
My code looks like this
timer = new Thread() { //new thread
public void run() {
b = true;
try {
do {
sleep(10);
runOnUiThread(new Runnable() {
#Override
public void run() {
if (right) {
dragzone.moveleft(-5);
} else if (left) {
dragzone.moveleft(5);
}
}
});
}
while (b);
} catch (InterruptedException e) {
}
}
;
};
timer.start();
It looks like using a Thread here is not necessary, and you should switch to using a Handler and postDelayed()
First, declare your Handler, boolean, and a Runnable as instance variables:
Handler handler;
boolean b;
Runnable checkDragZone = new Runnable(){
#Override
public void run() {
if (right) {
dragzone.moveleft(-5);
} else if (left) {
dragzone.moveleft(5);
}
if (b){
handler.postDelayed(this, 10);
}
}
};
To start monitoring, set b to true, and start the Runnable:
handler = new Handler();
b = true;
handler.postDelayed(checkDragZone, 10);
To stop it (temporarily or permanently), just set b to false:
b = false;
It's not really a good practice to keep it running. You can start it when you detect the Drag action and then release it when it's finished.
Runnable runnable;
Thread globalThread;
public void startThread() {
if (threadController) {
runnable = new Runnable() {
#Override
public void run() {
while (threadController) {
for (int i = 0; i < adapter.getCount(); i++) {
final int value = i;
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
viewPager.setCurrentItem(value, true);
}
});
}
}
}
};
globalThread = new Thread(runnable);
globalThread.start();
} else {
return;
}
}
#Override
public void onPause() {
super.onPause();
threadController = false;
handler.removeCallbacks(runnable);
runnable = null;
if (globalThread != null) {
globalThread.interrupt();
}
}
#Override
public void onDestroy() {
super.onDestroy();
threadController = false;
}
Your resolve must be like this globalThread.interrupt();

How do I set a time limit to my splash screen? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am coding in Eclipse for an Android App. I have developed a splash screen which I need to display for 5 seconds before my app starts. How to do it?
Thread timer=new Thread()
{
public void run() {
try {
sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
Intent i=new Intent(SplashScreen.this,MainActivity.class);
finish();
startActivity(i);
}
}
};
timer.start();
Use the Async Class to perform the sleep operation in the doinbackground function and in the post function do the rest of the task
public class SplashScreenActivity extends Activity {
private final int SPLASH_DISPLAY_LENGHT = 5000;
#Override
public void onCreate(Bundle icicle)
{ super.onCreate(icicle);
try{
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_splashscreen);
}catch(Exception e){
e.printStackTrace();
}
new MyAsyncTask().execute();
}
private class MyAsyncTask extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute(){
// show your progress dialog
}
#Override
protected Void doInBackground(Void... voids){
try {
Thread.sleep(SPLASH_DISPLAY_LENGHT);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void params)
{
startActivity(new Intent(SplashScreenActivity.this, HomeActivity.class));
finish();
}
}
}
use like that
public class SplaceScreenActivity extends Activity {
private static final int SPLASH_DISPLAY_TIME = 2500;
// SplashScreen Splash;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splacescreen);
new Handler().postDelayed(new Runnable() {
public void run() {
Intent intent = new Intent();
intent.setClass(SplaceScreenActivity.this,
HomeScreenActivity.class);
SplaceScreenActivity.this.startActivity(intent);
SplaceScreenActivity.this.finish();
}
}, SPLASH_DISPLAY_TIME);
}
}
Try below code:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splash);
final int welcomeScreenDisplay = 2000;
/** create a thread to show splash up to splash time */
Thread welcomeThread = new Thread() {
int wait = 0;
#Override
public void run() {
try {
super.run();
/**
* use while to get the splash time. Use sleep() to increase
* the wait variable for every 100L.
*/
while (wait < welcomeScreenDisplay) {
sleep(100);
wait += 100;
}
} catch (Exception e) {
} finally {
startActivity(new Intent(MainActivity.this,
HomeActivity.class));
finish();
}
}
};
welcomeThread.start();
}
}
Handler handler = new Handler();
Runnable run = new Runnable() {
public void run() {
// TODO Auto-generated method stub
startActivity(new Intent(SplaceActivity.this, New.class));
overridePendingTransition(0, 0);
finish();
}
};
handler.postDelayed(run, 3000);
Use AsyncTask or thread for this purpose.
http://www.androidhive.info/2013/07/how-to-implement-android-splash-screen-2/
hope it helps
I use Timer:
Timer timer = new Timer();
timer.schedule(new TimerTask(){
#Override
public void run() {
// TODO Auto-generated method stub
Intent home_page = new Intent(Splash.class,HomePage.class);
startActivity(home_page);
finish();
}}, 5000);
you can use Sleep method like this in your Splash Activity onCreate method:
Thread timer1 = new Thread(){
#Override
public void run(){
try{
sleep(4000);
}
catch (InterruptedException e){
e.printStackTrace();
}
finally{
Intent intent = new Intent(SplashActivity.this, NextActivity.class);
startActivity(intent);
}
}
};
timer1.start();
this take 4 sec to load NextActivity.
Add these few lines of code in your splashActivity and it will start your second activity after 5seconds.
new Handler().postDelayed(new Runnable(){
public void run() {
Intent mainIntent = new Intent(splashScreen.this,MainActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
splashScreen.this.startActivity(mainIntent);
splashScreen.this.finish();
}
}, 5000);
PostDelayed Causes the Runnable to be added to the message queue, to
be run after the specified amount of time elapses. The runnable will
be run on the thread to which this handler is attached.
Use handler
public class SplashActivity extends Activity {
int secondsDelayed = 5;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splash);
Message msg = new Message();
msg.what = 0;
mHandler.sendMessage(msg);
}
Handler mHandler = new Handler()
{
public void handleMessage(android.os.Message msg) {
switch(msg.what)
{
case 1:
{
startActivity(new Intent(SplashActivity.this, MainActivity.class));
finish();
}
break;
case 0:
{
Message ms = new Message();
ms.what = 1;
mHandler.sendMessageDelayed(ms, secondsDelayed * 1000);
}
break;
}
};
};
protected void onDestroy() {
super.onDestroy();
mHandler.removeMessages(1);
};
}
Note:Donot make Splash screen for 5 sec user will get irritated make it for 2sec

Why do I need a Handler object in this example?

public class ProgressBarTest extends Activity {
private int progress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.progress_bar);
final Handler handler = new Handler();
progress = 0;
final ProgressBar pb = (ProgressBar) findViewById(R.id.progressbar);
new Thread(new Runnable() {
public void run() {
while (progress < 10) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
progress++;
}
handler.post(new Runnable() {
#Override
public void run() {
pb.setVisibility(View.GONE);
}
});
}
}).start();
}
}
Why can't I just put the pb.setVisibility(View.GONE) in the first Runnable inner class? Like this: The program crashes if I write it this way.
new Thread(new Runnable() {
public void run() {
while (progress < 10) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
progress++;
pb.setVisibility(View.GONE);
}
}
}
The program crashes when the setVisibility statement is executed.
You cannot update ui from a thread. Ui should be updated on the ui thread.
In the second one you are setting the visibility of progressbar inside the threads runs method. Hence it crashes. So you use handler to set the visibility of progress bar in the the first
To know more about handlers.
http://developer.android.com/reference/android/os/Handler.html

Splash Screen not working with Thread

I write a Splash Screeen to run at the boot time of application
public class SplashScreen extends Activity {
ImageView imgView;
int[] imgID = new int[]{R.drawable.frame0, R.drawable.frame1, R.drawable.frame2, R.drawable.frame3,
R.drawable.frame4, R.drawable.frame5, R.drawable.frame6};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
imgView = (ImageView) findViewById(R.id.imgSplash);
new Thread(new WelcomeScreen()).start();
}
private class WelcomeScreen implements Runnable {
#Override
public void run() {
try {
for (int i = 0; i < imgID.length; i++)
{
imgView.setImageResource(imgID[i]);
sleep(500);
}
} catch (InterruptedException e) {
}finally {
Intent intent = new Intent(SplashScreen.this,LoginActivity.class);
startActivity(intent);
finish();
}
}
}
}
It getting error "Sorry the application has stopped unexpectedly" . I don't know why . Somebody can help me ????
you can not set the resource for yuor ImageView inside a thread different from the UI Thread.
you can use runOnUiThread. It takes as paramter a runnable, and post it in the UI Thread queue. There, the UI thead takes it and update your ImageView. All in all your runnable will become:
private class WelcomeScreen implements Runnable {
#Override
public void run() {
try {
for (int i = 0; i < imgID.length; i++)
{
final int resuorceId = imgID[i];
runOnUiThread(new Runnable() {
#Override
public void run() {
imgView.setImageResource(resuorceId);
}
});
sleep(500);
}
} catch (InterruptedException e) {
}finally {
Intent intent = new Intent(SplashScreen.this,LoginActivity.class);
startActivity(intent);
finish();
}
}
You can not access your views from Thread.
You will need to put your code imgView.setImageResource(imgID[i]); in runOnUiThread
use like:
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
imgView.setImageResource(imgID[i]);
}
});
Thanks
You can not change something in UI from non-UI thread so replace this you code:
imgView.setImageResource(imgID[i]);
to:
runOnUiThread(new Runnable() {
#Override
public void run() {
imgView.setImageResource(imgID[i]);
}
});
//try code this way...
public class SplashScreen extends Activity {
private Intent launchIntent;
private Thread splashThread; //used for perform splash screen operation
private int splashTime = 10000, sleepTime = 50; //used for threading operation
private boolean active = true; //used for touch event
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splashscreen); //Set splashscreen.xml here
try {
splashThread = new Thread() { // Creating Thread for splash the screen
#Override
public void run() { // run method implemented to perform threading operation
try {
int waitTime = 0; //counter for threading
do {
sleep(sleepTime); //delay for specific time
if (active)
waitTime += 100;
//write your image code here that display your no. of images
} while (active && (waitTime < splashTime)); //Check touch condition and counter
} catch (Exception e) {
// to handle runtime error of run method
Validation.displayToastMessage(SplashScreen.this, e.toString()); //Call static method of class ToastMessage
}
finish(); //finish current activity
startJustCoupleActivityScreen(); //Call below defined function
}
};
splashThread.start(); //start thread here
} catch (Exception e) {
message("SplashScreen : "+ e.toString()); //Call static method of class ToastMessage
}
}
public void startJustCoupleActivityScreen() {
launchIntent=new Intent(SplashScreen.this,JustCoupleActivity.class); //call Next Screen
startActivity(launchIntent); //start new activity
}
#Override
public boolean onTouchEvent(MotionEvent event) { //onTouch Event
//on touch it immediate skip splash screen
if(event.getAction()==MotionEvent.ACTION_DOWN) active=false; //Check Touch happened or not
return true;
}
public void message(String msg)
{
Validation.displayToastMessage(SplashScreen.this, msg); //display Error Message
}
}

Activity will run, but not show up (Android)?

I'm just trying to test some stuff with a splash screen. The strangest thing happens when I run the app though. I can see my Log messages in the LogCat, but the activity itself won't show up. Once the loop finishes, it starts the next activity, which does in fact show up. If I comment out the UIThread, it will show up though. I know I'm doing something simple wrong, but I'm not sure what it is. Ideas?
XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="#000000">
<ImageView
android:id="#+id/logoIV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="50dp"
android:paddingTop="50dp"
android:src="#drawable/logoa"
/>
Java:
public class Splash extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.splash);
final ImageView logo = (ImageView) findViewById(R.id.logoIV);
final int[] anim = new int[6];
anim[0]=R.drawable.logoa;
anim[1]=R.drawable.logob;
anim[2]=R.drawable.logoc;
anim[3]=R.drawable.logod;
anim[4]=R.drawable.logoe;
anim[5]=R.drawable.logof;
runOnUiThread(new Runnable() {
int img = 0, counter=0;
boolean up = true;
public void run() {
while(counter<21){
logo.setImageResource(anim[img]);
if(up){
img++;
if(img>=5)
up=false;
}else{
img--;
if(img<=0)
up=true;
}
try{
Thread.sleep(150);
}catch (InterruptedException e){
e.printStackTrace();
}
counter++;
Log.e("Tag",Integer.toString(counter));
}
if(counter>=21){
Intent creditsIntent = new Intent(Splash.this, TitlePage.class);
creditsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Splash.this.startActivity(creditsIntent);
}
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
change your oncreate method like this
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.splash);
final ImageView logo = (ImageView) findViewById(R.id.logoIV);
final int[] anim = new int[6];
anim[0] = R.drawable.logoa;
anim[1] = R.drawable.logob;
anim[2] = R.drawable.logoc;
anim[3] = R.drawable.logod;
anim[4] = R.drawable.logoe;
anim[5] = R.drawable.logof;
Thread t = new Thread(new Runnable()
{
int img = 0, counter = 0;
boolean up = true;
#Override
public void run()
{
while (counter < 21)
{
runOnUiThread(new Runnable()
{
public void run()
{
logo.setImageResource(anim[img]);
}
});
if (up)
{
img++;
if (img >= 5)
up = false;
}
else
{
img--;
if (img <= 0)
up = true;
}
try
{
Thread.sleep(150);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
counter++;
Log.e("Tag", Integer.toString(counter));
}
if (counter >= 21)
{
runOnUiThread(new Runnable()
{
public void run()
{
Intent creditsIntent = new Intent(Splash.this, TitlePage.class);
creditsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Splash.this.startActivity(creditsIntent);
}
});
}
}
});
t.start();
}
instead of calling runOnUiThread directly do the following:
new Timer().schedule(new TimerTask()
{
#Override
public void run()
{
runOnUiThread(new Runnable()
{
int img = 0, counter=0;
.....
}
}
}, 1000);
I'm not sure if your animation will work, but surely your activity will show up.

Categories

Resources