I get this error. not on any device, just on some.
This is all the report:
java.lang.NullPointerException
at eu.innovaapps.tpark.ro.MainSms$4$1$1.run(MainSms.java:444)
at java.util.Timer$TimerImpl.run(Timer.java:284)
and it comes from:
buton.setEnabled(false);
Timer buttonTimer = new Timer();
buttonTimer.schedule(new TimerTask() {
#Override
public void run() {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
buton.setEnabled(true);
}
});
}
}, 5000);
When i press the button it gets disabled and after 5 seconds it gets enabled again.
Line 444 is getActivity().runOnUiThread(new Runnable() {.
I'd appreciate alot if you could help me solve this error.
EDIT:
I got the same problem as here:
Scheduled Task in Fragment returns getActivity as null
If the button in disabled, and i press the back button of the phone, i get this error which sends me at this part of the code.
Is there a way i could stop the timer if the back button is pressed?
Can you please tell what is the line number 444 in your code ?
If line 444 is buton.setEnabled(true); then can you modify the code to add Button buton = (Button) findViewById(R.id. just before buton.setEnabled(true); and then try out the same code.
EDIT
Dear Victor,
I have read your EDIT... I used to get such exception... To go around this, what I have done is that I declared and static variable in my Activity class...
public static sActivity = null;
and then in onCreate method of Activity I assigned the current activity to it...
sActivity = this;
and then used it in the code instead of getActivity()...
So for e.g. my Activity name is myActivity then your code in that case could changed to...
#Override
public void run() {
getActivity().runOnUiThread(new Runnable()
#Override
public void run() {
if (myActivity.sActivity != null) {
myActivity.sActivity.runOnUiThread(new Runnable()
.
.
.
}
Let me know if you find any other better solution...
Timer notificationtask = new Timer();
notificationtask.schedule(new TimerTask()
{
#Override
public void run() {
// TODO Auto-generated method stub
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
buton.setEnabled(true);
} catch (Exception e) {
}
}
});
}
}, 1000, 1000);
Related
cancelBtn = (Button) findViewById(R.id.btnCncl);
cancelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
countDownTimer.cancel();
//txtViewOff.setText("");
txtViewOn.setText("Countdown Timer Canceled");
//Timer to set visible text view
Timer t = new Timer(false);
t.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
txtViewOn.setText("");
}
});
}
}, 3000);
}
});
when i click on the button related to this code the app get crashes..i made this to cancel the timer
I have no clear idea about this without a crash log. But according to this code most probably it may be a null pointer exception. try below thing by adding a null check before call countdowntimer
if(countDownTimer != null){
countDownTimer.cancel();
}
I am using the following code to execute a method after a specific time period say 9seconds.The code works fine only after the first execution.However i want that when the activity is launched the method must be called after 9 secs.Now what happens is the method is called the moment the activity is launched followed by after 9 seconds again it is called.
Following is my code:
private Timer myTimer;
myTimer = new Timer();
myTimer.schedule(new TimerTask()
{
#Override
public void run()
{
TimerMethod();
}
}, 0, 9000);
private void TimerMethod()
{
this.runOnUiThread(Timer_Tick);
}
private Runnable Timer_Tick = new Runnable()
{
public void run()
{
//Did some UI Operation
Toast.makeText(context, msg, 1000).show();
}
};
You can use this:
private void TimeMethod() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//TODO after 9 sec
}
}, 9000);
}
Hope this will be usefull,
Cheers
So I have an activity which runs a simple snakes and ladders game, and I want to allow the player to click a button and move, which would subsequently be followed by the computer moving. My problem is, that once the player moves, the computer immediately makes its move.
Instead I want the activity to wait before the computer makes its move. I've looked around a lot and found that waiting involves using a thread, but I have failed to implement it without my app crashing
My attempt at declaring a thread:
final Runnable runnable = new Runnable() {
#Override
public void run()
{
while (true)
{
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
};
Thread thread= new Thread(runnable);
My onClick() method for the button:
Button rollButton = (Button) (findViewById(R.id.rollButton));
rollButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//executes only if current player is a human
if(GAME_BOARD.getCurrentPlayer().isHuman()) {
GAME_BOARD.rollDie(); // rolls the die
showDie(GAME_BOARD); // displays die on screen
GAME_BOARD.move(); // moves the player and sets next player as current player
playerTurn.setText(GAME_BOARD.getCurrentPlayer().getName() +"'s turn");// sets TextView to display who's player's turn it is
thread.start();
if(!GAME_BOARD.getCurrentPlayer().isHuman()) {
GAME_BOARD.rollDie();
showDie(GAME_BOARD);
GAME_BOARD.move();
playerTurn.setText(GAME_BOARD.getCurrentPlayer().getName() +"'s turn");
}
}
}
});
So again, my question is, how do I make it so that before the second if statement executes, the activity waits, say 4 seconds?
you can use an Handler.postDeleayed. You have to provide a Runnable to execut and the delay period in milliseconds. The Runnable will be executed on the UI Thread
You can use Handle to post your task defined in runnable after some delay
use this
Inside Activity define
Handler hand = new Handler();
and define your task in runnable like this
Runnable run = new Runnable() {
#Override
public void run() {
**your Task here.......**
}
};
In on click event
btnStartShow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
hand.postDelayed(run,3000); // For delay three seconds
}
});
also remove all pending messages by calling following sentence at appropriate place
hand.removeCallbacksAndMessages(null);
Use a CountDownTimer:
CountDownTimer timer = new CountDownTimer(4000, 1000) {
#Override
public void onFinish() {
*function containing the second statement*
}
#Override
public void onTick(long millisLeft) {
// not ticking
}
};
and in the onClick method in the click listener use:
timer.start();
Try the following,
rollButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Runnable runnable = new Runnable() {
#Override
public void run() {
// whatever you would like to implement when or after clicking rollButton
}
};
rollButton.postDelayed(runnable, 5000); //Delay for 5 seconds to show the result
}
My problem is...
I have 2 events.. onCreate and Onclick. I have a thread running inside onCreate and i have to stop it inside onClick. Is this possible?
If yes, please provide me with some hints/ code snippets how to implement this.
My code inside onCreate event is this:-
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen);
button = (Button) findViewById(R.id.btn);
button.setOnClickListener(this);
try{
bright = Settings.System.getInt(getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS);
}catch(Exception ex){
ex.printStackTrace();
bright = 1.0f;
}
lp = getWindow().getAttributes();
new Thread(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(10000);
mHandler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
lp.screenBrightness= dim;
getWindow().setAttributes(lp);
// SLEEP 2 SECONDS HERE ...
final Handler handler = new Handler();
Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
lp.screenBrightness=bright;
getWindow().setAttributes(lp);
}
});
}
}, 2000);
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
}
this activity is running inside a loop. And i want to stop this wen i click on the button. It seems that i cannot call the Thread.interrupt() method inside the button onclick event. How do i proceed with this?
Declare an boolean mRunnning in your class, this is like a flag, and custom running thread will depend on this to know if it has been cancelled.
As usual, you have a loop in your thread, instead of while(true) do while(mRunning).
Also, you are making your thread sleep, during sleep, thread won't be able to check on mRunning variable, you will have to call interrupt() on thread object to make it stop.
It will be better to use a variable to hold thread reference Thread t = new Thread(....
So, now to stop your thread you have to call mRunning = false and then t.interrupt().
according to your current situation based on previous answer comment . you r trying like:
myThread = new Thread(new Runnable
right?
then u should also delete .start(); part of your previous coding. then write:
myThread.start();
u should declare myThread as global in your class, so that u can access this thread from anywhere in your class. now u can stop thread in onClick
u should combine this answer and User117 s answer together .
If you create a reference you can access it from everywhere in you class. So, in the class body ad something like
Thread thrd
Just like you would do so with a Button, TextView, or whatever. Then in the onCreate method add the reference like
thrd = new Thread(new Runnable(){
Now you have a reference to your thread you can use everywhere in your class.
instead of
while(true)
inside the run() Method, declare a boolean variable to true and change it after onClick. For example:
private boolean shouldRun = true;
then in the run() method:
#Override
public void run() {
// TODO Auto-generated method stub
while (shouldRun==true) {
.
.
.
and in your onClick:
#override
public void OnClick(View v){
shouldRun=false;
.
.
.
I am working on a Testing Project for me , just so I could learn more , so now I need to update the text of a TextView constantly every 250 milliseconds through a for(;;) loop , it happens after a Button click ... My problem is that whenever I press that button my app freezes (Yes my button is totally working , verified through previous testings) , I am using a handler to the Main thread doesn't get affected while the Runnable is up ... Here is my code of the Button and Handler ...
final Handler handler = new Handler();
B3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
for(;;){
String a = Shells.sendSingleCommand("free");//Here I send a command "free" and it returns its output
text.setText(a);//text is my TextView which is used through my experimentations ...
synchronized(this){
try{
wait(250);
}catch(Exception e){
}
}
}
}
});
}
});
If you need anymore info ask please :)
use handler.postDelayed for updating textview constantly every 250 milliseconds instead of using for loop to avoid freeze current Activity as :
Handler handler=new Handler();
B3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handler.post(runnable);
}
});
Runnable runnable=new Runnable(){
#Override
public void run() {
String a = Shells.sendSingleCommand("free");
text.setText(a);
handler.postDelayed(runnable, 250);
}
};
Android doesnt allow you to do long tasks in the main thread. If you need to do something like this I recommend moving the for loop and depdendent code into a separate thread..