using or excecution of sleep in setOnclicklistner function - java

I code a program which I expected to perform follwing action sequentially onclick the button:
1.Display the text(eg: "abc") in textview.
2.sleep for sometime(eg:2000).
3.finally it has to change the text(eg: "xyz") in textview.
for that i try the below code. when I run this, first it sleep for 2000 millisecond and display "xyz", It doesnot displaying "abc"...
(* I noticed that sleep will excecuting first inside the setOnclickListner()function then only rest of the code are excecuting *)
please help me to perform the action in sequence...
If my question is silly please excuse as I was new to this....
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
Button b1;
TextView tv;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv =(TextView)findViewById(R.id.textView1);
b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
tv.setText("abc");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
tv.setText("xyz");
}
});
}}}

Use Handler.postDelayed instead of Thread.sleep which freeze main UI Thread for 2000. Do same using Handler as:
Create Runnable :
private Runnable runnable = new Runnable() {
public void run() {
tv.setText("xyz");
mHandler.removeCallbacks(runnable);
}
};
call Handler.postDelayed on Button click :
mHandler = new Handler();
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
tv.setText("abc");
mHandler.postDelayed(runnable, 2000);
}
});

Related

I need to cancel the Timer started in a service class from MainActivity, but get null reference exception

I have a service type class which starts a timertask in onCreate method and I need to stop the timer from MainActivity when user press the button. I know I have to keep the reference to the timer in my service, but I cannot figure out how to do that and need some help, please!
please take a look at my code
package com.example.timertest;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
button.setOnClickListener(this);
startService(new Intent(this, TimeService.class));
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.button){
// i need here to call mTimer.cancel() in TimeService.class
//
}
}
}
// and here is the TimeService.java
package com.example.timertest;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TimeService extends Service {
public Timer mTimer;
private Handler mHandler = new Handler();
long NOTIFY_INTERVAL = 60 * 1000 * 1; // 1 min
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
if (mTimer != null) {
mTimer.cancel();
} else {
mTimer = new Timer();
}
mTimer.scheduleAtFixedRate(new RefreshDataTimerTask(), 0, NOTIFY_INTERVAL);
}
class RefreshDataTimerTask extends TimerTask {
#Override
public void run() {
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), getDateTime(), Toast.LENGTH_LONG).show();
}
});
}
private String getDateTime() {
SimpleDateFormat sdf = new SimpleDateFormat("[yyyy/MM/dd - HH:mm:ss]");
return sdf.format(new Date());
}
}
}
//and service registered in manifest
<service android:name=".TimeService"/>
I have tried to call the mTimer.cancel(), but got a null reference, because seems I have created a new instance of the service class.
This example shows a Toast with date and time each minute, i want when for example 15 seconds have past and i press the button, the timer to be canceled and to start counting 60 seconds again from the beginning. Inside this service i have many other things like notifications,channels, shared preferences and so on, so it will be good if i can operate only with the timer object.
Take a look on this API documentaion and this. There is example of how to bind service to activity after what you can get direct access to service methods.
After successful binding you can add method inside your service to stop the timer:
public void stopMyTimer() {
mTimer.cancel();
}
And call this method from Activity
This might not be best practice, but you can access public values by directly referring to the class:
TimeService.mTimer.cancel()
Which should work because Services function similarly to Singletons, in that each call of startService should be calling the same instance.

event can't run in android ( get errors)

I recently use android studio instead of eclipse.
but somthing is wrong!
these are main java code that run currectly in eclipse but now get errors!
package com.example.amir.myapplicationeeee;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
Button button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
startActivity(new Intent(getApplicationContext(),Main2Activity.class));
finish();
}
});
setOnClickListener is hilighed red and error ";" excepted showed when want to runnin app in virtual device
If the code you provide here is exactly the same as you have in your project, then you should just add '}' on the end of your code - it closes the MainActivity class.
You should also have evertyhing implemented inside onCreate() method.
So it should look like:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
startActivity(new
Intent(this,Main2Activity.class));
finish();
}
});
}
}

Thread in Android

I have an example like this:
package android.uiexample;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.RadioGroup.OnCheckedChangeListener;
public class BasicViewsExampleActivity extends Activity
{
private static int progress = 0;
private ProgressBar progressBar;
private int progressStatus = 0;
private Handler handler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_views);
progressBar = (ProgressBar) findViewById(R.id.progressbar);
//---do some work in background thread---
new Thread(new Runnable()
{
public void run()
{
//---do some work here---
while (progressStatus < 10)
{
progressStatus = doSomeWork();
}
//---hides the progress bar---
handler.post(new Runnable()
{
public void run()
{
progressBar.setVisibility(View.GONE);
}
});
}
//---do some long lasting work here---
private int doSomeWork()
{
try {
//---simulate doing some work---
Thread.sleep(500);
} catch (InterruptedException e)
{
e.printStackTrace();
}
return ++progress;
}
}).start();
}
}
In this example, it use Handler to post a Runable to exc progressBar.setVisibility(View.GONE);. I don't know why i can't call progressBar.setVisibility(View.GONE); directly:
//---do some work here---
while (progressStatus < 10)
{
progressStatus = doSomeWork();
}
//---hides the progress bar---
progressBar.setVisibility(View.GONE);
Anybody can tell me why i can't?
The android UI framework (like pretty much every UI framework before it) only allows you to update the UI state from the main thread. You may want to look at AsyncTask which include the plumbing needed to route progress updates onto the main thread.
Take a look at the Handler class. It provides a simple way to enqueue Runnable callbacks to run on the UI event thread.
changing the progressBar visibility is a UI operation. All UI operations must be done on the UI thread.

Change between activities does not work

I'm trying to change between activities in my Android app (2.1-update1), but it doesn't work.
Any suggestions?
The only thing that happens when I debug the app is that it stops on this part of the code in Instrumentation.java:
public void waitForIdle() {
synchronized (this) {
while (!mIdle) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
}
Eclipse says that it is in Thread 1 on
Instrumentation.checkStartActivityResult(int, Object) line: 1537. If I
resume the app, the next stop is in ZygoteInit.java trying to run
Throwable cause = ex.getCause(); ... Eclipse says
ZygoteInit$MethodAndArgsCaller.run() line: 864.
Here is the source code:
HappyHomes.java
package com.example.app;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class HappyHomes extends Activity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button login = (Button) findViewById(R.id.btnLogin);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ProgressDialog laddRuta = ProgressDialog.show(HappyHomes.this, "",
"Loggar in, vänligen vänta...", true);
Intent myIntent = new Intent(view.getContext(), Kategorier.class);
myIntent.
startActivity(myIntent);
}
});
}
}
Kategorier.java
package com.example.app;
import android.app.Activity;
import android.os.Bundle;
public class Kategorier extends Activity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.kategorier);
}
}
Thanks for helping!
Make sure that Kategorier is registered in your AndroidManifest.xml file.
Change myIntent.startActivity(myIntent); to HappyHomes.this.startActivity(myIntent);
There is no any startActivity() method in Intent class . you must be doing wrong.
just write startActivity(myIntent)
All the Services, Broadcast Receivers and Activites must be declared in manifest file.

setOnClickListener in simple Android does not work

I try to learn JAVA and I try to write an app for Android. My Code is simple and often I've seen code like this. But when I push the second time a button, the message does not return. The first time it works. What is my error?
package com.test.helloworld;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class HelloWorldApp extends Activity {
private Button closeButton;
private Button buttonAnswer1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonAnswer1 = (Button)findViewById(R.id.button1);
closeButton = (Button)findViewById(R.id.buttonEnde);
buttonAnswer1.setFocusable(false);
closeButton.setFocusable(false);
buttonAnswer1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.main);
showToastMessage("1");
}
});
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.main);
showToastMessage("2");
}
});
}
private void showToastMessage(String msg){
Toast toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
toast.show();
}
}
Don't call the setContentView method inside the click listener:
buttonAnswer1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showToastMessage("1");
}
});
In your onClick functions, you are replacing the entire content view, which will replace the existing button objects with new instances. These new instances no longer have any OnClickListeners.
There is no reason to replace the content view in this case, so the solution is to eliminate those calls from the onClick functions. But if for some reason you needed to replace the content view, then you would need to go through the entire process of finding the new buttons and calling setOnClickListener for each.

Categories