Why doesn't my Intent work? - android

I have the following code:
public class P1R1 extends Activity {
int correctCounter;
private String[] answerString;
private TextView score;
private static final Random rgenerator = new Random();
protected static final String EXTRA_playerOneScore = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.level);
score = (TextView) findViewById(R.id.score);
correctCounter = 0;
loadActivity();
//start round timer
new CountDownTimer(60000, 1000) {
final TextView timer = (TextView) findViewById(R.id.timer);
public void onTick(long millisUntilFinished) {
timer.setText("Time: " + millisUntilFinished / 1000 + "s");
}
public void onFinish() {
Intent roundOneToTwo = new Intent(getActivity(), R1R2.class);
String playerOneScore = String.valueOf(correctCounter);
roundOneToTwo.putExtra(EXTRA_playerOneScore, playerOneScore);
startActivity(roundOneToTwo);
}
}.start();
I have a timer running, and when the timer is over I want the Intent to run, but I'm getting an error for my Intent saying The constructor Intent(new CountDownTimer(){}, Class<R1R2>) is undefined.
I did create an R1R2 class, but my Intent is still giving an error. I'm still new to android, so it would be great if you could help. Thanks!

In place of
Intent roundOneToTwo = new Intent(this, R1R2.class);
try
Intent roundOneToTwo = new Intent(P1R1.this, R1R2.class);
First parameter to Intent constructor should be the Context, but you're passing reference to the CountDownTimer. See http://developer.android.com/reference/android/content/Intent.html

Related

Trying to stop timer from another class

I'm using timer in my application and I'd like to stop it from another class. So I have an Activity and two classes: MainActivity,Timer,Pause.
MainActivity calls a method from Timer class to start the countdown. I have a button which calls a method from Pause class to stop the timer. It's seems like pretty easy but I always got NullPointerException error message.
MainActivity:
public TextView txt;
public TextView szamlalo;
Timer i;
Pause p;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = (TextView)findViewById(R.id.hello);
szamlalo = (TextView)findViewById(R.id.szam);
Button b = (Button)findViewById(R.id.button);
p = new Pause(szamlalo,txt,this);
i = new Timer(szamlalo,this,txt);
i.startTimerbig();
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
p.stopminden();
}
});
}
Timer class:
public Timer bigtimer;
public TimerTask bigtimerTask;
public final Handler bighandler = new Handler();
int ido = 10;
TextView szamlalo;
TextView txt;
Context context;
Over over;
public Timer(TextView szamlalo,Context context,TextView txt){
this.szamlalo = szamlalo;
this.context = context;
this.txt = txt;
}
public void startTimerbig() {
bigtimer = new Timer();
biginitializeTimerTask();
bigtimer.schedule(bigtimerTask, 3000, 1000);
}
public void bigstoptimertask(){
bigtimer.cancel();
}
public void biginitializeTimerTask() {
bigtimerTask = new TimerTask() {
#Override
public void run() {
bighandler.post(new Runnable() {
#Override
public void run() {
ido--;
szamlalo.setText("" + ido + "s");
}
});
}
};
}
Pause class:
TextView szamlalo;
TextView txt;
Context context;
Timer i;
public Pause(TextView szamlalo,TextView txt,Context context){
this.szamlalo = szamlalo;
this.txt = txt;
this.context = context;
this.i = new Timer(szamlalo,context,txt);
}
public void stopminden(){
i.bigstoptimertask();
}
The error message also says that this line is the guilty one:
bigtimer.cancel();
If anyone has an idea how to do that please response!
public Pause(TextView szamlalo,TextView txt,Context context){
this.szamlalo = szamlalo;
this.txt = txt;
this.context = context;
this.i = new Timer(szamlalo,context,txt);//HERE!!
}
You create a new object of Timer in the last line, it's not the same object with field 'i' of class 'MainActivity' and it's field 'bigtimer' not inited because it's startTimerbig() never been called;

How to pass integer variable through intent in android ?

I have tried passing variables through Intent before. But it seems that I am missing something that I cant pass the integer variable time. The question has been asked before by others, but I cant get it to work in this situation.
I want to pass the value of the integer variable time to another class which is aftertap.class through intent.
I have this code.
public class ingame extends Activity {
private TextView textTimer;
int time = 0;
Timer t;
TimerTask task;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ingame);
Button button = (Button)findViewById(R.id.my_button);
final RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)button.getLayoutParams();
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
params.leftMargin = button.getWidth()+ new Random().nextInt(displaymetrics.widthPixels - 2*button.getWidth());
params.topMargin = button.getHeight()+ new Random().nextInt(displaymetrics.heightPixels - 3*button.getHeight());
Log.v("widthPixels", ""+ displaymetrics.widthPixels);
Log.v("heightPixels", ""+ displaymetrics.heightPixels);
button.setLayoutParams(params);
startTimer();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
t.cancel();
t.purge();
//Starting a new Intent
Intent thirdscreen = new Intent(getApplicationContext(), aftertap.class);
//Sending data to another Activity
thirdscreen.putExtra("time", time);
startActivity(thirdscreen);
}
});
}
public void startTimer(){
t = new Timer();
task = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
textTimer = (TextView) findViewById(R.id.textTimer);
textTimer.setText(time + "");
time = time + 1;
}
});
}
};
t.scheduleAtFixedRate(task, 0, 1);
}
}
Aftertap class:
public class aftertap extends Activity{
TextView score;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aftertap);
TextView gameover = (TextView)findViewById(R.id.gameover);
score = (TextView)findViewById(R.id.score);
Intent i = getIntent();
// Receiving the Data
//I do not know how to get the value of the integer variable time. I want to display the value of time in the TextView score
}
}
You should use getIntExtra() method:
int value = i.getIntExtra("time", 0);
Change the default value parameter (second parameter) to what you want it to be.
And then display the value
score.setText(String.valueOf(value));

How to display a timer in activity in Android

I want to show timer, with every second. After 20 seconds I want that activity to call itself.
But when I don't display the timer it waits for 20 seconds as I wish to do but as soon as I implement code to display timer it just starts and suddenly stops suddenly.
Here is my code. Please help me out.
public class MainActivity extends Activity {
public int time=20;
Button end;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread timerdisp = new Thread(){
TextView tv = (TextView) findViewById(R.id.timer);
public void run(){
try{
sleep(1000); // sleep for 1 seconds
tv.setText(String.valueOf(time));
time-=1;
if(time==0){
startActivity(new Intent(MainActivity.this,MainActivity.class));
}
run();
}
catch (InterruptedException e){
e.printStackTrace();
}
}
};
timerdisp.start();
);
}
Android provides a better facility of CountDownTimer, may be you should use that. As it provides many inbuilt methods and runs on background thread by default.
You can use onFinish() method to execute your call to the activity.
Here is an example of the same.
Try Below Code:
private long ms=0;
private long splashTime=2000;
private boolean splashActive = true;
private boolean paused=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Hides the titlebar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splash);
Thread mythread = new Thread() {
public void run() {
try {
while (splashActive && ms < splashTime) {
if(!paused)
ms=ms+100;
sleep(100);
}
} catch(Exception e) {}
finally {
Intent intent = new Intent(Splash.this, Home.class);
startActivity(intent);
}
}
};
mythread.start();
}
and you can try this also
public class MainActivity extends Activity {
private CountDownTimer countDownTimer;
public TextView text;
private final long startTime = 20 * 1000;
private final long interval = 1 * 1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.textView1);
countDownTimer = new MyCountDownTimer(startTime, interval);
text.setText(String.valueOf(startTime / 1000));
countDownTimer.start();
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
Intent intent = new Intent();
intent.setClass(getApplicationContext(),xxxx.class);
startActivity(intent);
}
#Override
public void onTick(long millisUntilFinished) {
text.setText("" + millisUntilFinished / 1000);
}
}
}
Use runOnUiThread
This acts as a normal Thread and will not allow your UI to sleep.
and the system will not hang.
or you can also use AsyncTask. I will prefer you using AsyncTask.
Use below code to call the function for every 20 seconds.
private Timer timer;
TimerTask refresher;
timer = new Timer();
refresher = new TimerTask() {
public void run() {
// your code to call every 20 seconds.
};
};
// first event immediately, following after 20 seconds each
timer.scheduleAtFixedRate(refresher, 0,1000*20);
Use below lines to show the time :
package com.example.test;
public class MainActivity extends Activity {
private Long startTime;
public native String getLastShotName();
public native String colorNormal();
public native String flipImage();
public native String forceInvertColor();
public native String getLastTitle();
public native String myMethod();
boolean mbFlip = false;
private Timer timer;
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TimerTask refresher;
startTime = System.currentTimeMillis();
handler.removeCallbacks(updateTimer);
handler.postDelayed(updateTimer, 1000);
}
#Override
protected void onResume() {
super.onResume();
handler.postDelayed(updateTimer, 1000);
}
private Runnable updateTimer = new Runnable() {
public void run() {
final TextView time = (TextView) findViewById(R.id.textView1);
Long spentTime = System.currentTimeMillis() - startTime;
Long minius = (spentTime/1000)/60;
Long seconds = (spentTime/1000) % 60;
time.setText(minius+":"+seconds);
handler.postDelayed(this, 1000);
}
};
}

Created clock on Android is not updating

I´m trying to create a fullscreen clock. I managed to set text for hours, minutes and seconds. Well, but when I start the app, it shows the time but the UI is not updating... I dont know how to do it, I read this tutorial but i dont understand it... any one can explain me how to consantly update the UI?
public class Clock1Activity extends Activity {
/** Called when the activity is first created. */
private Timer timer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView txtHour = (TextView)findViewById(R.id.TxtHour);
final TextView txtMinutes = (TextView)findViewById(R.id.TxtMinute);
final TextView txtSeconds = (TextView)findViewById(R.id.TxtSeconds);
final TextView txtMilliseconds = (TextView)findViewById(R.id.TxtMilliseconds);
final Integer hora = new Integer(Calendar.HOUR_OF_DAY);
final Integer minutos = new Integer(Calendar.MINUTE);
final Integer segundos = new Integer(Calendar.SECOND);
final Long milisegundos = new Long (System.currentTimeMillis());
timer = new Timer("DigitalClock");
Calendar calendar = Calendar.getInstance();
// Get the Current Time
final Runnable updateTask = new Runnable() {
public void run() {
/** txtHour.setText(hora.toString());
txtMinutes.setText(minutos.toString());
txtSeconds.setText(segundos.toString()); */
txtMilliseconds.setText(milisegundos.toString());
Toast toast1 = Toast.makeText(getApplicationContext(), milisegundos.toString(), Toast.LENGTH_SHORT);
toast1.show();
}
};
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(updateTask);
}
}, 1, 1000);
}
}
Just tell me how to complete it to update UI,please...
You didn't mention which tutorial you're working on, so just in case, you'll probably want to use AsyncTask.
see this example for Create a Apps to Show Digital Time in Android .And in your case use
runOnUiThread for Upadting time on UI.as
CurrentActivity.this.runOnUiThread(new Runnable() {
public void run() {
//UPDATE TIME HERE
}
});
and your code look like:
public class Clock1Activity extends Activity {
/** Called when the activity is first created. */
private Timer timer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView txtHour = (TextView)findViewById(R.id.TxtHour);
final TextView txtMinutes = (TextView)findViewById(R.id.TxtMinute);
final TextView txtSeconds = (TextView)findViewById(R.id.TxtSeconds);
final TextView txtMilliseconds = (TextView)findViewById(R.id.TxtMilliseconds);
timer = new Timer("DigitalClock");
Calendar calendar = Calendar.getInstance();
// Get the Current Time
final Runnable updateTask = new Runnable() {
public void run() {
final Integer hora = new Integer(Calendar.HOUR_OF_DAY);
final Integer minutos = new Integer(Calendar.MINUTE);
final Integer segundos = new Integer(Calendar.SECOND);
final Integer milisegundos = new Integer(Calendar.MILLISECOND);
txtHour.setText(hora.toString());
txtMinutes.setText(minutos.toString());
txtSeconds.setText(segundos.toString());
txtMilliseconds.setText(milisegundos.toString());
}
};
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(updateTask);
}
}, 1, 1000);
}
}

Passing data through Intent in Android, just want the number of clicks

I have a program that starts on one activity goes to the next and their is button to click, after a certain amount of time it goes back to the starting page and reports the number of clicks.
Here's my code: clickcount is the first activity
public class ClickCountActivity extends Activity {
/** Called when the activity is first created. */
Button next;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
next=(Button) findViewById(R.id.NextButton);
//---------------------------------------------------------------
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(ClickCountActivity.this, startClickActivity.class);
i.putExtra("comingFrom", "come");
final int result=1;
startActivityForResult(i,result);
}
});
//---------------------------------------------------------------------------
}
}
public class startClickActivity extends Activity {
/** Called when the activity is first created. */
Button clicker;
int counter ;
Timer timer = new Timer(); // use timer to start a new task
MyTimerTask task = new MyTimerTask();
final long seconds = 3;
Intent p = getIntent();
String answer = p.getStringExtra("comingFrom");
class MyTimerTask extends TimerTask {
public void run()
//override run method
{
Intent x = new Intent(startClickActivity.this, ClickCountActivity.class);
x.putExtra("returnStr", answer);
setResult(RESULT_OK,x);
startActivity(x);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.action);
clicker=(Button) findViewById(R.id.Clicker);
//---------------------------------------------------------------
clicker.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
counter++; // counts number of clicks
task.cancel(); // cancels current task
task = new MyTimerTask(); //create new task
timer.schedule(task,seconds*1000L); // start a new timer task in 5seconds (timertask, seconds(long))
// System.out.println(counter);
}
});
}
}
Your code in run method should be this:
Intent x = new Intent(startClickActivity.this, ClickCountActivity.class);
x.putExtra("returnStr", counter);
setResult(RESULT_OK,x);
finish();
You need to pass the no. of counts i.e. counter in intent and collect it from onActivityResult(int requestCode, int resultCode, Intent data) method of ClickCountActivity class. The value is passed in the data intent and can be queried using int counterValue = data.getIntegerExtra("returnStr", 0);

Categories

Resources