Run thread from another thread - java

I test the following code and the Toast message did not appear and the "TestMethod" did not call "Catch" method , please help me ?
public void TestMethod()
{
Test= new Thread(new Runnable() {
public void run() {
try{
Catch();
}
catch (Exception ioe)
{
}
}
});
Test.start();
}
public void Catch()
{
Test2= new Thread(new Runnable() {
public void run() {
try{
Toast.makeText(getApplicationContext(), "Yes", Toast.LENGTH_SHORT).show();
}
catch (Exception ioe)
{
}
}
});
Test2.start();
}

May be runOnUiThread helpful to you.
runOnUiThread lets you ride on the UI thread and let s you to perform action on UI thread.
Try this:
runOnUiThread(new Runnable()
{
public void run()
{
Toast.makeText(getApplicationContext(), "Yes", Toast.LENGTH_SHORT).show();
}
});

You should call Toast.makeText on UI thread. Read this for more details.

You can make a toast only from the UI Thread. If you have access to the activity, you can change your code like thi
public void TestMethod()
{
Test= new Thread(new Runnable() {
public void run() {
try{
Catch();
}
catch (Exception ioe)
{
}
}
});
Test.start();
}
public void Catch()
{
activity.runOnUiThread(new Runnable() {
public void run() {
try{
Toast.makeText(getApplicationContext(), "Yes", Toast.LENGTH_SHORT).show();
}
catch (Exception ioe)
{
}
}
});
}

This is the complete solution and it should work perfectly
Some methods will only run on the uithread, (runOnUiThread is a method on the activity, so if you can't reach it, than just put a variable
private final Activity activity = this;
and call the runOnUiThread from there
public void TestMethod() {
Test= new Thread(new Runnable() {
public void run() {
try{
Catch();
}
catch (Exception ioe) {
//always log your exceptions
Log.e("simpleclassname", ioe.getMessage(), ioe);
}
}
});
Test.start();
}
public void Catch() {
Test2= new Thread(new Runnable() {
public void run() {
try{
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Yes", Toast.LENGTH_SHORT).show();
});
catch (Exception ioe) {
//always log your exceptions
Log.e("simpleclassname", ioe.getMessage(), ioe);
}
}
});
Test2.start();
}

The thread you are using does not allows toast to show. You must do UI related stuff on a UI thread. If you are not on Main Thread, then you need to use runOnUiThread.

Related

ProgressDialog keeps on showing despite being cancelled and hidden

Right now I'm simulating the showing of a ProgressDialog for an event that is expected to take several seconds.
I'm doing it this way:
progressDialog = new ProgressDialog(getContext());
progressDialog.setMessage(getString(R.string.calendar_load));
progressDialog.setCancelable(false);
progressDialog.show();
Thread t=new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
getActivity().runOnUiThread(new Runnable()
{
#Override
public void run() {
progressDialog.cancel();
progressDialog.hide();
But even though I've checked in debug that the progressDialog.cancel() and progressDialog.hide() execute the dialog just keeps on showing apparently in an indefinite way.
What could be causing such behavior?
PROBLEM SOLVED: Thanks to everyone who has answered/commented, it looks like an emulator bug (indeed it has also worked some times on emulator).
Call progressDialog.dismiss();
Could you try this snippet?
progressDialog.show();
new Thread(new Runnable() {
#Override
public void run() {
try {
while (progressDialog.getProgress() <= progressDialog.getMax()) {
Thread.sleep(100);
handle.sendMessage(handle.obtainMessage());
if (progressDialog.getProgress() == progressDialog.getMax()) {
progressDialog.dismiss();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
Handler handle = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
progressDialog.incrementProgressBy(1);
}
};

How can I stop thread and properly display text by Toast in thread?

I need solution to stop my thread and display Toast.
Why doesn't stop my thread?
Why doesn't my solution display "success" by Toast?
This is my class StopperThread where I try stop by blinker my thread.
public class StopperThread implements Runnable{
private Context context;
private volatile boolean blinker;
public StopperThread(Context context){
this.context = context;
this.blinker = true;
}
#Override
public void run ()
{
Looper.prepare();
try {
while(blinker) {
Log.e("LOG","ACTIVE");
Thread.sleep(1000);
Toast.makeText(context, "success", Toast.LENGTH_SHORT).show();
}
} catch (InterruptedException e) {
e.printStackTrace();
blinker = false;
}
Looper.loop();
}
public void mystop() {
blinker = false;
}
}
This is my method clickedButton inside the Activity where I created thread.
private void clickedButton() {
final StopperThread stopperThread = new StopperThread(this);
Thread t1 = new Thread(stopperThread);
if(click)
{
t1.start();
click = false;
}
else
{
try {
stopperThread.mystop();
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
click = true;
}
}
I tried to change
/*First Try*/
final StopperThread stopperThread = new StopperThread(getApplicationContext());
/*Second Try*/
runOnUiThread(new Runnable() {
#Override
public void run() {
t1 = new Thread(stopperThread);
}
});

ProgressDialog - why runnable doesn't make appear ProgressDialog?

When I try to update text in my progressDialog like someone suggests here or here.
In my case, I'm trying to update the text in a loop while the progressDialog is not dismissed (?) elsewhere...
But my loop inside the runnable doesn't seems work, or better, the runnable doesn't make show the progressDialog.
So, in this way the code shows the progressDialog:
#Override
public void onDirectionFinderStart() {
String title = "PriscaLobby";
String msg = "Loading...";
progressDialog = ProgressDialog.show (MapsActivity.this,title,msg,true,false);
//--> runOnUiThread(changeMessage);
}
private Runnable changeMessage = new Runnable() {
#Override
public void run() {
progressDialog.setMessage("bruka");
while (progressDialog.isShowing()) {
try {
Thread.sleep(1500);
if (progressDialog.isShowing())
progressDialog.setMessage("Can you wait, please?");
Thread.sleep(1500);
if (progressDialog.isShowing())
progressDialog.setMessage("Here we are..");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
In this way NO:
#Override
public void onDirectionFinderStart() {
String title = "PriscaLobby";
String msg = getString(R.string.calculate_directions);
progressDialog = ProgressDialog.show (MapsActivity.this,title,msg,true,false);
runOnUiThread(changeMessage);
}
private Runnable changeMessage = new Runnable() {
#Override
public void run() {
progressDialog.setMessage("bruka");
while (progressDialog.isShowing()) {
try {
Thread.sleep(1500);
if (progressDialog.isShowing())
progressDialog.setMessage("Can you wait, please?");
Thread.sleep(1500);
if (progressDialog.isShowing())
progressDialog.setMessage("Here we are..");
} catch (InterruptedException e) {
e.printStackTrace();
}
} //Log.v(TAG, strCharacters);
}
};
Why?

Creating an android app using twitter api, the control is not going in thread

Here is the code:
public void onClick(View v) {
Log.d(TAG, "hay i am working till here");
new Thread() {
public void run() {
try {
Log.d(TAG, "hay i reached till here");
twitter = new Twitter("student", "password");
twitter.setAPIRootUrl("http://yamba.marakana.com/api");
twitter.setStatus(editText.getText().toString());
Log.d(TAG,"Successfully Posted");
} catch (TwitterException e) {
Log.e(TAG, "Died", e);
}
}
}.start();
Log.d(TAG, "onClicked");
}
When I run it, it reaches just the first Log i.e Log.d(TAG, "hay i am working till here"); I can't find out what the problem is.
public void onClick(View v) {
Log.d(TAG, "hay i am not working");
Handler.post(new Runnable() {
public void run() {
try {
Log.d(TAG, "hay i reached till here");
twitter = new Twitter("student", "password");
twitter.setAPIRootUrl("http://yamba.marakana.com/api");
twitter.setStatus(editText.getText().toString());
Log.d(TAG, "Successfully Posted");
} catch (TwitterException e) {
Log.e(TAG, "Died", e);
}
}
});
Log.d(TAG, "onClicked");
}
The problem lies in the fact that you are trying to access the ui thread via a non ui thread with this line in your code
twitter.setStatus(editText.getText().toString());
As edittext.getText() should be accessed/called on ui thread.
Instead use an handler on ui thread to accomplish your needs.
Handler tweethandler=new Handler(getMainLooper());
tweethandler .post(new Runnable(){
public void run(){
try {
Log.d(TAG, "hay i reached till here");
twitter = new Twitter("student", "password");
twitter.setAPIRootUrl("http://yamba.marakana.com/api");
twitter.setStatus(editText.getText().toString());
Log.d(TAG,"Successfully Posted");
} catch (TwitterException e) {
Log.e(TAG, "Died", e);
}
}
});

Creating a slidshow in android

I am creating an application in which user can start slideshow (auto-play) of images by clicking a specific button. I have started a thread in which a new image is set to my imageView after a 1 sec. Problem is that my app stop responding and crashes after few seconds.
Please check my code and help me to resolve this issue. (variables are correctly initialized)
playThread = new Runnable() {
#Override
public void run() {
synchronized (this) {
for (int i=pos;i<mImageIds.length;i++){
//pos++;
selectedImage.setImageResource(mImageIds[i]);
try {
wait(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
}};
play.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
runOnUiThread(playThread);
}
});
}
my logcat while app freezes!
The runOnUiThread() method is meant to update the user interface. Any other logic shouldn't happen there. So I would suggest something like this:
Thread t = new Thread() {
for (int i=pos;i<mImageIds.length;i++){
runOnUiThread(new Runnable() {
#Override
public void run() {
selectedImage.setImageResource(mImageIds[i]);
}};);
try {
wait(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}};
play.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
t.start();
}
});
Please note, I didn't test this code.

Categories