How to pass integer variable through intent in android ? - 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));

Related

How to start a countdown with a textview from another class?

I am making a countdown timer in android eclipse and I want to use a Textview from another class.
This is my first class
public class Main extends Activity {
Spinner timerValueSpinner;
Button startButton;
TextView statusTextView;
Countdown timer;
String[] timeValues;
Resources resourcePointer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timerValueSpinner = (Spinner)this.findViewById(R.id.secondsSpinner);
statusTextView = (TextView)this.findViewById(R.id.timerView);
resourcePointer = getResources();
timeValues = resourcePointer.getStringArray(R.array.seconds_list);
startButton = (Button)this.findViewById(R.id.startButton);
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Main.this,Timer.class);
startActivity(intent);
if(timerValueSpinner.getSelectedItemPosition() > -1){
int parsedSpinnerValue = 0;
parsedSpinnerValue = Integer.parseInt(timeValues[timerValueSpinner.getSelectedItemPosition()]);
if(parsedSpinnerValue > 0){
if(timer != null){
timer.cancel();
}
timer = new Countdown(parsedSpinnerValue
* Countdown.oneSecond, Countdown.oneSecond,statusTextView);
timer.start();
}
}
}
});
}
This is my Second class and I want to get its statusTextVie and use it in the First(Main) class instead of its own textview so when I click the button the second class will show and the countdown will start from its textview.
public class Timer extends Activity {
TextView statusTextVie;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer);
statusTextVie = (TextView)this.findViewById(R.id.timerVie);
}
This is my first time asking a question here, so I am sorry if i made some mistakes.
Why not pass the time value from the first activity to second activity via intent and start the thread in second activity ?
First Activity:
public class Main extends Activity {
Spinner timerValueSpinner;
Button startButton;
String[] timeValues;
Resources resourcePointer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timerValueSpinner = (Spinner)this.findViewById(R.id.secondsSpinner);
resourcePointer = getResources();
timeValues = resourcePointer.getStringArray(R.array.seconds_list);
startButton = (Button)this.findViewById(R.id.startButton);
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Main.this,Timer.class);
if(timerValueSpinner.getSelectedItemPosition() > -1){
int parsedSpinnerValue = 0;
parsedSpinnerValue = Integer.parseInt(timeValues[timerValueSpinner.getSelectedItemPosition()]);
if(parsedSpinnerValue > 0){
intent.putExtra("TimeValue", parsedSpinnerValue);
startActivity(intent);
}
}
}
});
}
Second Activity:
public class Timer extends Activity {
Countdown timer;
TextView statusTextVie;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer);
Bundle extras = getIntent().getExtras();
int timeVal = extras.getInt("TimeValue", 0);
statusTextVie = (TextView)this.findViewById(R.id.timerVie);
if (timeVal > 0){
if(timer != null){
timer.cancel();
}
timer = new Countdown(timeVal * Countdown.oneSecond, Countdown.oneSecond,statusTextVie);
timer.start();
}
}
}

How to update TextView dynamically (periodically)?

I am developing a simple android activity with a scrollable TextView. I am displaying numbers from 1-100 in my TextView with a time delay. However my desired output is not what I'm getting.
Current Output: 1 replaced by 2 replaced by 3....till 100.
Desired Output:
1
2
3
4
.
.
100
Here is my Activity code:
public class MainActivity extends ActionBarActivity {
private static int i = 0;
TextView textView;
Handler handler;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
textView = (TextView) findViewById(R.id.text_area);
new PrimeCalculation().execute();
handler = new Handler();
handler.post(updateView);
}
private Runnable updateView = new Runnable() {
#Override
public void run() {
if(i <= 100) {
textView.setText(Integer.toString(i));
i++;
handler.postDelayed(this, 1000);
}
}
};
}
How about this:
textView.setText(textView.getText() + "\n" + i);
Create a new String Array. Set the text view to the array.toString(); Every time that your timer runs out insert the most recent number into the array and repeat. The most recent number should be an int that increases when the timer runs out. Hope this helps!
Try this
private Handler mHandler = new Handler();
private int nCounter = 0;
View.OnClickListener mButtonStartListener = new OnClickListener() {
public void onClick(View v) {
try {
mHandler.removeCallbacks(hMyTimeTask);
// Parameters
// r The Runnable that will be executed.
// delayMillis The delay (in milliseconds) until the Runnable will be executed.
mHandler.postDelayed(hMyTimeTask, 1000); // delay 1 second
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
private Runnable hMyTimeTask = new Runnable() {
nCounter++;
hTextView.append("\n"+nCounter);
}
public void run() {
};
Hope this will help you
You can use following code......
public class MainActivity extends ActionBarActivity {
private static int i = 0;
TextView textView;
Handler handler;
String textViewText="";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.text_area);
handler = new Handler();
handler.post(updateView);
}
private Runnable updateView = new Runnable() {
#Override
public void run() {
if(i <= 100) {
//
textViewText=textViewText+Integer.toString(i)+" ";
textView.setText(textViewText);
// textViewText=textViewText+textView.getText().toString();
i++;
handler.postDelayed(this, 1000);
}
}
};}
I hope it will help you....

Why doesn't my Intent work?

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

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