Calling from wrong thread exception - java

I am trying to develop an application, that uses threads to implement slideshow. I am retrieving the image path from SQLite and displaying them on the ImageView. The problem, where I got struck is, I got confused and so I am unable to understand, from which thread I am calling images() method, where I am actually implementing the slideshow.
I got the Logcat as follows -
09-03 13:47:00.248: E/AndroidRuntime(10642): FATAL EXCEPTION: Thread-151
09-03 13:47:00.248: E/AndroidRuntime(10642): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
09-03 13:47:00.248: E/AndroidRuntime(10642): at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:5908)
09-03 13:47:00.248: E/AndroidRuntime(10642): at com.example.fromstart.MainActivity.images(MainActivity.java:90)
09-03 13:47:00.248: E/AndroidRuntime(10642): at com.example.fromstart.MainActivity$2.run(MainActivity.java:59)
09-03 13:47:00.248: E/AndroidRuntime(10642): at java.lang.Thread.run(Thread.java:841)
MainActivity.java:
public class MainActivity extends Activity
{
ImageView jpgView;
TextView tv;
//adapter mDbAdapter;
adapter info = new adapter(this);
String path;
Handler smHandler = new Handler()
{
public void handleMessage(Message msg)
{
TextView myTextView =
(TextView)findViewById(R.id.textView1);
myTextView.setText("Button Pressed");
}
};
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
jpgView = (ImageView)findViewById(R.id.imageView1);
tv = (TextView) findViewById(R.id.textView1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
final Runnable runnable = new Runnable()
{
public void run()
{
images();
}
};
int delay = 1000; // delay for 1 sec.
int period = 15000; // repeat every 4 sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
smHandler.post(runnable);
}
}, delay, period);
Thread mythread = new Thread(runnable);
mythread.start();
return true;
}
public void handleMessage(Message msg)
{
String string = "sample";
TextView myTextView = (TextView)findViewById(R.id.textView1);
myTextView.setText(string);
}
public void images()
{
try
{
for(int i=0;i<=20;i++)
{
path = info.getpath();
Bitmap bitmap = BitmapFactory.decodeFile(path);
jpgView.setImageBitmap(bitmap);
}
}
catch(NullPointerException er)
{
String ht=er.toString();
Toast.makeText(getApplicationContext(), ht, Toast.LENGTH_LONG).show();
}
}
}
I am a newbie to android, just now started working on Threads. If you find any mistakes in my code, please point out those and please suggest me, the right way to deal with this problem.
Thanks in advance.
UPDATE:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Handler mHandler = new Handler();
// Create runnable for posting
runOnUiThread(new Runnable()
{
public void run()
{
images();
}
});
int delay = 1000; // delay for 1 sec.
int period = 15000; // repeat every 4 sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
images();
}
}, delay, period);
}
public void images()
{
try
{
Toast.makeText(getApplicationContext(), "1", Toast.LENGTH_LONG).show();
path = info.getpath();
Toast.makeText(getApplicationContext(), "2", Toast.LENGTH_LONG).show();
Bitmap bitmap = BitmapFactory.decodeFile(path);
Toast.makeText(getApplicationContext(), "3", Toast.LENGTH_LONG).show();
jpgView.setImageBitmap(bitmap);
Toast.makeText(getApplicationContext(), "4", Toast.LENGTH_LONG).show();
}
catch(NullPointerException er)
{
String ht=er.toString();
Toast.makeText(getApplicationContext(), ht, Toast.LENGTH_LONG).show();
}
}
}

You cannot update/access ui from from a thread.
You have this
public void run()
{
images();
}
And in images you have
jpgView.setImageBitmap(bitmap);
You need to use runOnUiThread for updating ui.
runOnUiThread(new Runnable() {
#Override
public void run() {
// do something
}
});
TimerTask also runs on a different thread. So you have use a Handler for updati ui.
You can use a handler.
Edit:
Handler m_handler;
Runnable m_handlerTask ;
m_handler = new Handler();
m_handlerTask = new Runnable()
{
#Override
public void run() {
// do something. call images()
m_handler.postDelayed(m_handlerTask, 1000);
}
};
m_handlerTask.run();
If you still wish to use a timer task use runOnUiThread
timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
runOnUiThread(new Runnable() {
#Override
public void run() {
images();
}
});
}
}, delay, period);

To update UI from any other Thread you must use
runOnUiThread(<Runnable>);
which will update your UI.
Example:
runOnUiThread(
new Runnable()
{
// do something on UI thread Update UI
});

Related

I am using handler for delay in android but it's not working

I want a delay for two seconds. and every 2 seconds I want to change the text, and for that, I am using handler like this, but it's not working it's only showing hello. it's not changing at all it only shows what I write second. The code is like this,
private Handler handler = new Handler();
int i=5;
private TextView textView ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.hello);
textView.setText("Android Things !!");
hello_first.run();
}
private Runnable hello_first = new Runnable() {
#Override
public void run() {
textView.setText("Nice Work");
handler.postDelayed(this,5000);
textView.setText("Hello");
handler.postDelayed(this,2000);
i = i+1;
if(i==5)
handler.removeCallbacks(this);
}
};
You are using postDelayed incorrectly. It looks like you expect it to work the same way Thread.sleep would work. However that is not the case.
Here is a correct implementation of what you are trying to achieve:
private Handler handler = new Handler();
private TextView textView;
private int i = 0;
private boolean flip;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.hello);
handler.post(hello_first);
}
private Runnable hello_first = new Runnable() {
#Override
public void run() {
if(++i == 5) {
handler.removeCallbacks(this);
return;
}
if(flip) {
textView.setText("Nice Work");
} else {
textView.setText("Hello");
}
flip = !flip;
handler.postDelayed(this, TimeUnit.SECONDS.toMillis(2));
}
};
I Hope this will work for you.
Handler handler = new Handler();
Runnable task = new Runnable() {
#Override
public void run() {
textView.setText("Nice Work");
handler.postDelayed(this,2000);
textView.setText("Hello");
handler.postDelayed(this,2000);
}
};
task.run();
For Stopping task
handler.removeCallbacks(task);
Its easy to use like
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
textView.setText("Hello");
},2000);
handler.postDelayed(new Runnable() {
#Override
public void run() {
textView.setText("Nice Work");},5000);
A Handler allows you to send and process Message and Runnable objects
associated with a thread's MessageQueue.
Rectify your postDelayed method.
Causes the Runnable r to be added to the message queue, to be run
after the specified amount of time elapses.
DEMO STRUCTURE
textView.setText("Nice Work");
final Handler handlerOBJ = new Handler();
handlerOBJ.postDelayed(new Runnable() {
#Override
public void run() {
// YOUR WORK
textView.setText("Hello");
}
}, 5000); // 5S delay
You can Log and see what happened actually...
Every time you call handler.postDelayed(this, 5000);
it will create two Runnable instance and send them to the handler. So the number of runnable in the queue increase very quickly.
You can set a text list and index, and then throw the runnable to the handler and postDealyed as 2000 milliseconds. Use the text list and index to see what text should be set to the textview.
try this code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.hello);
textView.setText("Android Things !!");
handler.postDelayed(hello_first,5000);
handler.postDelayed(hello_second,2000);
}
private Runnable hello_first = new Runnable() {
#Override
public void run() {
textView.setText("Nice Work");
}
};
private Runnable hello_second = new Runnable() {
#Override
public void run() {
textView.setText("Hello");
}
};

Pause the changing Images when Audio paused

I am building an application in which images starts changing when audio is played.
When audio is play (starts) onclick button, the images also start changing with different delays and i can pause my audio as well. The problem which i am facing and getting confuse is that, when i paused my audio,
How can i pause my images as well ,so that when i click the button again,my audio resumes and images starts changing next from where they were paused.
private Button btn_play;
MediaPlayer mp;
int duration;
private ImageView imageView;
Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_names);
int resID = getResources().getIdentifier("audio", "raw", getPackageName());
mp = MediaPlayer.create(NamesOfALLAH.this, resID);
duration = mp.getDuration();
btn_play = (Button) findViewById(R.id.btn_play);
imageView = (ImageView) findViewById(R.id.imageView_Names);
btn_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mp.isPlaying()) {
mp.pause();
btn_play.setText("Play");
} else {
mp.start();
btn_play.setText("Pause");
changeImage1();
changeImage2();
changeImage3();
changeImage4();
changeImage5();
}
}
});
}
public void changeImage1() {
handler.postDelayed(new Runnable() {
#Override
public void run() {
imageView.setImageResource(R.drawable.a1);
}
}, 6000);
}
public void changeImage2() {
handler.postDelayed(new Runnable() {
#Override
public void run() {
imageView.setImageResource(R.drawable.a2);
}
}, 8000);
}
public void changeImage3() {
handler.postDelayed(new Runnable() {
#Override
public void run() {
imageView.setImageResource(R.drawable.a3);
}
}, 10000);
}
public void changeImage4() {
handler.postDelayed(new Runnable() {
#Override
public void run() {
imageView.setImageResource(R.drawable.a4);
}
}, 11000);
}
public void changeImage5() {
handler.postDelayed(new Runnable() {
#Override
public void run() {
imageView.setImageResource(R.drawable.a5);
}
}, 12000);
}
`
Use an ImageSwitcher, it does some of the work for you. In any case, if you want to create the animation yourself, you must consider all the changes as a whole. For example, you can repost the runnable to the handler. Pseudo-code:
handler.postDelayed(new Runnable() {
#Override
public void run() {
// set the image you want
if (mustContinue)
handler.postDelayed(this, time);
}
}, 10000);
Toggle the boolean mustContinue every time you press the play/pause button.
EDIT:
Check this as an example.

Android Thread for a timer

public class MainActivity extends Activity
{
int min, sec;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
min = 5;
sec = 0;
final TextView timer1 = (TextView) findViewById(R.id.timer1);
timer1.setText(min + ":" + sec);
Thread t = new Thread() {
public void run() {
sec-=1;
if (sec<0) {
min-=1;
sec=59;
}
timer1.setText(min + ":" + sec);
try
{
sleep(1000);
}
catch (InterruptedException e)
{}
}
};
t.start();
}
}
This is a code for a Thread in Java but it doesn't work. Can you help me?
Its a Timer that counts down from 5 Minutes to 0:00.
In your case you are using threads. So you cannot update ui from the thread other than the ui thread. SO you use runOnUithread. I would suggest you to use a countdown timer or a Handler.
1.CountDownTimer
http://developer.android.com/reference/android/os/CountDownTimer.html
Here's a link to another example. Suggest you to check the link for the count down timer.
Countdowntimer in minutes and seconds
Example:
public class MainActivity extends Activity {
Button b;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView1);
b= (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startTimer(200000);
}
});
}
private void startTimer(long time){
CountDownTimer counter = new CountDownTimer(30000, 1000){
public void onTick(long millisUntilDone){
Log.d("counter_label", "Counter text should be changed");
tv.setText("You have " + millisUntilDone + "ms");
}
public void onFinish() {
tv.setText("DONE!");
}
}.start();
}
}
2.You can use a Handler
Example :
Handler m_handler;
Runnable m_handlerTask ;
int timeleft=100;
m_handler = new Handler();
m_handlerTask = new Runnable()
{
#Override
public void run() {
if(timeleft>=0)
{
// do stuff
Log.i("timeleft",""+timeleft);
timeleft--;
}
else
{
m_handler.removeCallbacks(m_handlerTask); // cancel run
}
m_handler.postDelayed(m_handlerTask, 1000);
}
};
m_handlerTask.run();
3.Timer
Timer runs on a different thread. You should update ui on the ui thread. use runOnUiThread
Example :
int timeleft=100;
Timer _t = new Timer();
_t.scheduleAtFixedRate( new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() //run on ui thread
{
public void run()
{
Log.i("timeleft",""+timeleft);
//update ui
}
});
if(timeleft>==0)
{
timeleft--;
}
else
{
_t.cancel();
}
}
}, 1000, 1000 );
You are trying to update the UI Thread from a background Thread with
timer1.setText(
which you can't do. You need to use runOnUiThread(), AsyncTask, CountDownTimer, or something similar.
See this answer for an example of runOnUiThread()
But CountDownTimer is nice for things like this.
Also, when posting a question on SO, statements like "it doesn't work." are very vague and often unhelpful. Please indicate the expected results compared to actual results of your code and logcat if the app is crashing.

Android Handler and Thread at start time not running?

I'm trying to create a handler at the start of my application so I can have two threads working 1 the UI and 2 my server, I'm doing this so the server will not stop the UI from lagging, and usefully sort out my lag issues, but anyways, I'm looking at this website http://crodrigues.com/updating-the-ui-from-a-background-thread-on-android/ , the guy creates a runnable method, with a run method, there is also a method called updateGame which is always called when that method is ran, now I have tried out his code like so
public class MainActivity extends Activity {
private static final String TAG = gameObject.class.getSimpleName();
//Create a handler to deal with the server
private Handler serverHandler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Turn off title
requestWindowFeature(Window.FEATURE_NO_TITLE);
//Make the application full screen
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView( new gamePanel( this ) );
Log.d( TAG, "View added" );
//Server method
new Thread(new Runnable() { onServer( ); } ).start( );
}
final Runnable updateRunnable = new Runnable() {
public void run() {
//call the activity method that updates the UI
updateGame();
}
};
//Give the positions to the game
public void updateGame()
{
Log.d(TAG, "Update that game");
}
//Update/run the server
private void onServer()
{
if( gamePanel.rtnServerState() == true )
{
Log.d(TAG, "Start the server");
}
serverHandler.post( updateRunnable );
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void onDestroy()
{
Log.d( TAG, "Destroying... " );
super.onDestroy();
}
public void onStop()
{
Log.d( TAG, "Stopping... " );
super.onStop();
}
}
and my updateGame is only ran once. Can anyone see the issue in why it doesn't keep running in the background?
Canvas
Updated post
public class MainActivity extends Activity {
private static final String TAG = gameObject.class.getSimpleName();
private final Handler serverHandler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Turn off title
requestWindowFeature(Window.FEATURE_NO_TITLE);
//Make the application full screen
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView( new gamePanel( this ) );
TextView textView = new TextView(this);
textView.setTextSize(40);
String message = "hello";
textView.setText(message);
Log.d( TAG, "View added" );
//Server method
new Thread(new Runnable() {
#Override
public void run() { onServer( ); } } ).start( );
}
private void updateServer()
{
Log.d(TAG, "testing");
}
//Update/run the server
private void onServer()
{
if( gamePanel.rtnServerState() == true )
{
Log.d(TAG, "Start the server");
}
serverHandler.post( updateRunnable );
}
//Update/server
final Runnable updateRunnable = new Runnable() {
public boolean running = true;
public void run() {
while(running){
//call the activity method that updates the UI
updateServer();
}
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void onDestroy()
{
Log.d( TAG, "Destroying... " );
super.onDestroy();
}
public void onStop()
{
Log.d( TAG, "Stopping... " );
super.onStop();
}
}
Update number 2
public class MainActivity extends Activity {
private static final String TAG = gameObject.class.getSimpleName();
private final Handler serverHandler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Turn off title
requestWindowFeature(Window.FEATURE_NO_TITLE);
//Make the application full screen
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView( new gamePanel( this ) );
TextView textView = new TextView(this);
textView.setTextSize(40);
String message = "hello";
textView.setText(message);
Log.d( TAG, "View added" );
//Server method
Runnable server = new Runnable() {
public boolean running = true;
public void run() {
while(running){
onServer(); // Make sure this blocks in some way
}
}
};
}
private void updateServer()
{
Log.d(TAG, "testing");
}
//Update/run the server
private void onServer()
{
if( gamePanel.rtnServerState() == true )
{
Log.d(TAG, "Start the server");
}
serverHandler.post( updateRunnable );
}
//Update/server
final Runnable updateRunnable = new Runnable() {
public void run() {
//call the activity method that updates the UI
updateServer();
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void onDestroy()
{
Log.d( TAG, "Destroying... " );
super.onDestroy();
}
public void onStop()
{
Log.d( TAG, "Stopping... " );
super.onStop();
}
}
The Runnable object's run method is only called once, after a new Thread is created in response to your .start() call.
Usually you do something like:
final Runnable myRunnable = new Runnable() {
public boolean running = true;
public void run() {
while(running){
doSomething();
}
}
};
But I'm not sure this is the best way to do this. The updateGame() method will be constantly called unnecessarily.
Instead, put your server logic inside the runnable's run() method. In there use the while(running){...} construct I listed above but make sure there is some blocking call in there. Whether it be from a network socket, a BlockingQueue, etc. That way it won't needlessly loop.
EDIT
From discussion in comments. Leave
final Runnable updateRunnable = new Runnable() {
public void run() {
//call the activity method that updates the UI
updateGame();
}
};
as it is and change
new Thread(new Runnable() { onServer( ); } ).start( );
to
Runnable server = new Runnable() {
public boolean running = true;
public void run() {
while(running){
onServer(); // Make sure this blocks in some way
}
}
}
new Thread(server).start();
In the tutorial UI is updated only on button click but you do it only once in onCreate method. If you will do it in #jedwards way your UI will froze as you wrote. Don't update UI all the time. Try to update it using timer or using sockets. It will be more effective and your UI will not froze.
Timer example
import java.util.Timer;
import java.util.TimerTask;
...
TimerTask task = new TimerTask() {
#Override
public void run() {
// update UI
}
};
Timer timer = new Timer();
// 1000 - after 1 second run this timer
// 3000 - and do it every 3 second
timer.schedule(task, 1000, 3000);
I wont write socket example because there is to much to write. I've found this tutorial where you can read about android socket programming.
BTW Of course you should update only your entity data using socket or timer, not the whole UI.

Use timertask to update clock each X seconds?

I'm trying to update my digital clock using timertask. I have created a function called updateClock() which sets the hours and minutes to the current time but I haven't been able to get it to run periodically. From what I've read in other answers one of the best options is to use timertask however I haven't been able to make any example I found online work inside an Android activity.
This is what I've written so far:
public class MainActivity extends Activity {
TextView hours;
TextView minutes;
Calendar c;
int cur_hours;
int cur_minutes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.clock_home);
hours = (TextView) findViewById(R.id.hours);
minutes = (TextView) findViewById(R.id.minutes);
updateClock();
}
public void updateClock() {
c = Calendar.getInstance();
hours.setText("" + c.get(Calendar.HOUR));
minutes.setText("" + c.get(Calendar.MINUTE));
}
public static void init() throws Exception {
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
updateClock(); // ERROR
}
}, 0, 1 * 5000);
}
}
How can I make it work?
Use runOnUiThread for updating Ui from Timer Thread
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
MainActivity.this.runOnUiThread (new Runnable() {
public void run() {
updateClock(); // call UI update method here
}
}));
}
}, 0, 1 * 5000);
}
if you just need updates every minute, you can also listen to the ACTION_TIME_TICK broadcast event.
private boolean timeReceiverAttached;
private final BroadcastReceiver timeReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateClock();
}
};
private Handler handler = new Handler();
#Override
protected void onResume() {
super.onResume();
updateClock();
if (!timeReceiverAttached) {
timeReceiverAttached = true;
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_TIME_TICK);
filter.addAction(Intent.ACTION_TIME_CHANGED);
filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
registerReceiver(timeReceiver, filter, null, handler);
}
}
#Override
protected void onPause() {
super.onPause();
if (timeReceiverAttached) {
unregisterReceiver(timeReceiver);
timeReceiverAttached = false;
}
}
OR, periodically post the Runnable to the Handler of UI thread. Also, pause and resume tasks to save battery.
public class MyActivity extends Activity {
private final Handler mHandler = new Handler();
private final Timer mTimer = new Timer();
#Override
protected void onResume() {
super.onResume();
mTimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
mHandler.post(new Runnable() {
#Override
public void run() {
//---update UI---
}
});
}
},0,5000);
}
#Override
protected void onPause() {
super.onPause();
mTimer.cancel();
}
}

Categories

Resources