I am trying to show error messages and hide them after 3 seconds. That's what I have written but it seems that it doesn't work that way.
yazi.setVisibility(View.VISIBLE);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
yazi.setVisibility(View.GONE);
You can use a Handler with its postDelayed method for your purpose:
//Show your view
yazi.setVisibility(View.VISIBLE);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Hide your View after 3 seconds
yazi.setVisibility(View.GONE);
}
}, 3000);
Update your code like this
Inside your onCreate() method
yazi.setVisibility(View.VISIBLE);
Thread thread=new Thread(runnable);
thread.start();
and outside your onCreate() method , do like this
Runnable runnable=new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
yazi.setVisibility(View.GONE);
}
});
}
};
};
Always use runOnUiThread for making UI operations.
Related
I am working on an android app development and I am stuck in an issue. I have used ANSYNC TASK method but now it has stopped working.
It was working fine from last many years but now it is creating problem.
Also, doinbackground() and postExecute() methods are not working (they are not called) only preExecute() method is working for me.
I am attaching code here for the reference:
class MyAsyncTask extends AsyncTask<Void, ConversationModel, Void> {
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
heading.setText("myheading");
}
});
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (ConversationModel model : dataList) {
if (flagStop)
break;
publishProgress(model);
long_time = Long.parseLong(model.sound_time) * 1000 + 500;
try {
Thread.sleep(long_time);
Thread.sleep(long_extraTime);
long_extraTime = 0;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
i++;
Log.d("i", i + " -----------------");
}
return null;
}
protected void onProgressUpdate(ConversationModel... model) {
if (i % 2 == 0) {
View v = View.inflate(Conversation1.this, arrInt_resource[0], null);
v.setAnimation(null);
TextView txtV_spn = (TextView) v.findViewById(R.id.textView_spn);
TextView txtV_eng = (TextView) v.findViewById(R.id.textView_eng);
ImageView img_sound = (ImageView) v.findViewById(R.id.imgsound_conv_spn2eng);
RelativeLayout speak_layout = (RelativeLayout) v.findViewById(R.id.speaking_layout);
heading.setText(dataList.get(0).heading);
if (flag != 1) {
txtV_spn.setText(model[0].eng_txt);
txtV_eng.setText(model[0].spn_txt);
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (i >= dataList.size()) {
Log.d("i", i + " ------------------");
makingcontinueImageView();
}
}
}
i think you are using .execute() method of asynctask to start execute of asynctask, change that line of code with this one
asynctask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
I have a problem, I have a for loop and a ProgressDialog and would like to see something like (10/5) where 10 is the total items to be processed by and for the 5 elements are currently being developed. I have this code.
new Thread(new Runnable() {
public void run() {
for(int i=0; i<adapter.getTotalItems().size(); i++) {
try {
index = i;
progressDialog = ProgressDialog.show(MyClass.this,adapter.getTotalItems().size()+"/"+index, );
MyClass.this.runOnUiThread(new Runnable() {
public void run() {
progressDialog.cancel();
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Thread.sleep(1*2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
MyClass.this.runOnUiThread(new Runnable() {
public void run() {
progressDialog.dismiss();
}
});
}
}).start();
Don´t cancle the ProgressDialog every Time, just Change the Title like:
mProgressDialog.setTile(adapter.getTotalItems().size()+"/"+index);
That´s it.
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.
I've been trying to get this to work for a while. I'm trying to send a message from my phone to a simple server on my laptop. I keep getting the NetworkOnMainThreadException, I've tried making a new Thread(new Runnable() etc. and an ASynchTask but I am still getting the error and the app is force closing. I have read through 3 or 4 of the questions similar to this but none have worked for me. Here is my code:
final Button post2 = (Button) findViewById(R.id.postbutton2);
post2.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new Thread(new Runnable() {
// TODO Auto-generated method stub
#Override
public void run() {
// TODO Auto-generated method stub
message = text.getText().toString(); //Message is a string, text is an EditText.
text.setText("");
try {
clientSocket = new Socket("10.0.0.2", 4445);
printWriter = new PrintWriter(clientSocket
.getOutputStream(), true);
printWriter.write(message);
printWriter.flush();
printWriter.close();
clientSocket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
Toast.makeText(context, e.toString(),
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(context, e.toString(),
Toast.LENGTH_SHORT).show();
}
}
}).start();
}
});
try removing the following part from your code.
message = text.getText().toString(); //Message is a string, text is an EditText.
text.setText("");
It does not look right to do this in this thread.
You must do YourActivity.this.runOnUiThread(new Runnable() { public void run() { /* show your toast here */ });
I'm trying to develop an app which gets some data from an HTML webpage and displays it every second.
For that i'm using a runnable in this way:
In the OnCreate() method:
mHandler.removeCallbacks(mMuestraMensaje);
mHandler.postDelayed(mMuestraMensaje, 5000);
And then this other method:
private Runnable mMuestraMensaje = new Runnable() {
public void run() {
try {
returned = test.GetSensorData(newString);
rowTextView.setText(returned);
} catch (Exception e) {
e.printStackTrace();
}
mHandler.removeCallbacks(mMuestraMensaje);
mHandler.postDelayed(this, 500);
}
};
The problem is that if i press the back button, for example, the app starts to behave slowly and until i don't force close the whole app the device runs too slow!
Thank you!
EDIT
This is the whole class:
public class HttpExample extends Title {
GetMethodEx test, moredata ;
String returned;
TextView rowTextView, rowTextView2;
LinearLayout ll;
private Handler mHandler = new Handler();
String newString;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.httpexample);
rowTextView = (TextView)findViewById(R.id.textView2);
rowTextView2 = (TextView)findViewById(R.id.textView1);
mHandler.removeCallbacks(mMuestraMensaje);
mHandler.postDelayed(mMuestraMensaje, 5000);
Bundle extras = getIntent().getExtras();
newString = extras.getString("STRING_I_NEED");
test = new GetMethodEx();
moredata = new GetMethodEx();
try {
String name = moredata.GetName(newString);
rowTextView2.setText(name);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ScheduledExecutorService executor =
Executors.newSingleThreadScheduledExecutor();
executor.scheduleAtFixedRate(mMuestraMensaje , 0, 500, TimeUnit.MILLISECONDS );
}
private Runnable mMuestraMensaje = new Runnable() {
public void run() {
try {
returned = test.GetSensorData(newString);
} catch (Exception e) {
e.printStackTrace();
}
MainActivity.this.runOnUiThread(new Runnable(){
rowTextView.setText(returned);
});
}
};
}
Your program slows down because you are running the thread on the GUI thread. That isn't recommended. However, I notice you are setting text after you are done. Here's a few things you could do.
Run the sensor data gathering in a different thread. Update the text by the runOnUiThread command.
Use an AsyncTask, this seems to be an ideal situation for one.
For such a regular occurrence, that doesn't require a UI thread, I would suggest using a ScheduledExecutorService.
The simplest to start with would be the first, but I would look carefully at the second option. The first option would be something like this: (Note, you will need to replace MainActivity with the name of your activity)
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(mMuestraMensaje , 0, 500, TimeUnit.MILLISECONDS );
private Runnable mMuestraMensaje = new Runnable() {
public void run() {
try {
returned = test.GetSensorData(newString);
} catch (Exception e) {
e.printStackTrace();
}
MainActivity.this.runOnUiThread(new Runnable(){
rowTextView.setText(returned);
});
}
};
You can attach you Handler to work on a different thread by using HandlerThread. For example:
HandlerThread ht = new HandlerThread("nonUiThread");
ht.start();
Handler mHandler = new Handler(ht.getLooper());
but more preferably, I would suggest you to use AsyncTask in your case.
Got it to work with this:
private Runnable mMuestraMensaje = new Runnable() {
public void run() {
try {
returned = test.GetSensorData(newString);
} catch (Exception e) {
e.printStackTrace();
}
HttpExample.this.runOnUiThread(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
rowTextView.setText(returned.get(0)+returned.get(1));
rowTextView2.setText(returned.get(2));
}
});
}
};