I have a DialogFragment which has a listView as container. I've set up OnItemClickListener on the listView.
How can I get the value when the user touchs an item and pass it to another activity then store that value into a variable? I need to set a count down timer depending on which item will be selected. Actually can only display simple toast message with the item position.
As a note, the activity to which the value will be passed is not the fragment activity.
I was thinking about Bundle but have not having much knowledge on programming is a pain even after reading documentation on Google site.
on the MainActivy, here is how I set the timer:
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
String elapsedTime = String.valueOf(millisUntilFinished / 1000);
timer.setText(elapsedTime);
}
public void onFinish() {
timer.setText(R.string.text);
}
}.start();
}
Exemple:
If user touches item 1 then the timer gets value 15 minutes and so on...
Please guide me, thank you.
So, you want to pass data from Fragment to Activity. Here is how you do it.
Passing the data from Fragment to Activity:
final Intent intent = new Intent(getActivity(), ActivityName.class);
intent.putExtra("counter-value", counterValue);
getActivity().startActivity(intent);
Reading the value in the Activity:
final Bundle extras = getIntent().getExtras();
if(extras != null) {
final int counterValue = extras.getInt("counter-value", -1);
showCountDown(counterValue);
}
Now, Pass the value to the countdowntimer.
private void showCountDown(final int counterValue) {
new CountDownTimer(counterValue, 1000) {
public void onTick(long millisUntilFinished) {
String elapsedTime = String.valueOf(millisUntilFinished / 1000);
timer.setText(elapsedTime);
}
public void onFinish() {
timer.setText(R.string.text);
}
}.start();
}
Related
I am making a game.
Lets say that it has 2 levels.
I have a TIMER in both which works properly. The code for timer:
public Timer t;
public int TimeCounter = 0;
t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
runOnUiThread(new Runnable() {
public void run() {
TextView t = (TextView)findViewById(R.id.txtcount);
t.setText(String.valueOf(TimeCounter));
TimeCounter++;
}
});
}
}, 1000, 1000);
Now in my 3rd activity i want the total time (Adding the first activity's and second activity's time taken) to be shown.
Also, I want to save the time the user took as the high score. And then when the user takes less time than the highest score, the previous will get deleted and the new will be saved
I would appreciate your help.Thanks
Make TimeCounter static
public static int TimeCounter = 0;
Now you can increment it in both of your activities like (in second activity it will retain values from first activity)
ActivityOne.TimeCounter++;
Wherever you want to get its value you can get it easily.
I have run into a problem. I have an animation that is going in my first activity, and a countdown timer in my second activity. When I set the countdown timer the value is passed back into my first activity which begins a new countdown activity, but the animation stops. How can I pass the value of the countdown timer to my MainActivity while still Maintaining the animation in my main activity.
Here is my code for the intent in my SecondActivity that is being passed to my MainActivity. Im not sure what code to show because I am not sure what the cause of the problem is.
buttonStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//put your logic here to set the time with hourPicked and minPicked variables
timer = new CounterClass((hours * 60 * 1000) + (minutes * 1000), 1000);
String hms = String.format(("%02d:%02d"), hours, minutes);
textViewTime.setText(hms);
Intent intent = new Intent(SleepTimer.this, MainActivity.class);
String TimeValue = (hms);
intent.putExtra("TimeValue", TimeValue);
startActivity(intent);
timer.start();
}
});
You have to declare String hms globally and onclick of button finish the SleeoTimer activity.and access global variable hms at MainActivity in SleepTimer Activity create field as public static String hms;
and in MainActivity use it as SleepTimer.hms
buttonStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//put your logic here to set the time with hourPicked and minPicked variables
timer = new CounterClass((hours * 60 * 1000) + (minutes * 1000), 1000);
hms = String.format(("%02d:%02d"), hours, minutes);
textViewTime.setText(hms);
SleepTimer.this.finish();
}
});
You have to add your animation code on Activity Oncreate,OnPause and also in OnResume as per your requirement.
Im working on a Quiz App. in which I have a different types of quizzes. Quiz with Time and Quiz without Time. Quiz without time is simple and there is no certain or specific time given to attempt the quiz. But the Quiz with Time is time restricted Quiz.
What I Want:
When an individual try to attempt a time restricted quiz. The certain amount of time will be show on an activity for instance remaining time (30 min left). and after the 30th min the activity automatically stop. I have tried timer class but that is used for delay.
how can I stop a activity after a certain time?
Thanks in Advance
public void countDown() {
new CountDownTimer(60000*30, 1000) {
public void onTick(long millisUntilFinished) {
int seconds = (int) (millisUntilFinished / 1000) % 60 ;
int minutes = (int) ((millisUntilFinished / (1000*60)) % 60);
int hours = (int) ((millisUntilFinished / (1000*60*60)) % 24);
String my_new_str =((((((((( (pad(hours)+":"+pad(minutes)+":"+pad(seconds)));
timer.setText( my_new_str);
float pvalue = ( float)(millisUntilFinished*100)/(60000*30);
myprogressbar.setProgress((int)(Math.round(pvalue)));
}
public void onFinish() {
timer.setText("Completed");
goToResult();
this,finish();
}
}.start();
}
you can do this using Handlers
try some thing like this...
Handler handler = new Handler();
Runnable x=new Runnable() {
#Override
public void run() {
finish();
}
};
handler.postDelayed(x, 6000);
Put your question in Thread...
Thread t=new Thread()
{
public void run()
{
try{
sleep(30000);
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
Intent intent = new Intent(Splash.this, Login.class);
startActivity(intent);
finish();
}
}
};
t.start();
Try to use AsyncTask or Handler in your Activity. i think you set some certain time limits for the
Quiz Question so please make sure to use any one of this above i mentioned.
Handler handler = new Handler();
Runnable x=new Runnable() {
#Override
public void run() {
Intent intent = new Intent(CurrentActivity.this, TargetActivity.class);
startActivity(intent);
finish();// activity will kill. or use
System.Exit();
}
};
handler.postDelayed(x, yourtimelimit(in timemills or millisecond));
Even you doesn't work yet means try to use onComplete listener and the put it finish in that method or
use onDestroy method inside to finish().
thank you
I have an activity in which i need to implement a basic mm::ss timer . Below is the code i have written for it. However the problem is that when i press the back button in the emulator and click on the app again, the values change much faster. It looks like the onCreate is being called again. How do i rectify this?
I have tried creating a boolean variable and setting it to true the first time the task is invoked . I call the startPeriodidUpdates() only when the value is false.But the onCreate creates the variable again with the value of false.
public class GraphicsActivity extends Activity {
static int seconds = 0;
static int minutes = 0;
public static String time_elapsed;
public static boolean clearView = true;
Handler myhandler = new Handler();
public static String min,sec;
public static boolean running = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startPeriodicUpdates();
}
public void onResume(){
super.onResume();
}
public void onPause() {
super.onPause();
}
public void onStop(){
super.onStop();
}
public void startPeriodicUpdates()
{
periodicCall();
}
public void stopPeriodicUpdates(){
myhandler.removeCallbacksAndMessages(myhandler);
}
public void periodicCall()
{
seconds++;
if(seconds ==60)
{
seconds=0;
minutes++;
if(minutes==60)
{
seconds=0;
minutes=0;
}
}
// left-padding zeros to the minutes and seconds values
min = String.format("%02d",minutes);
sec = String.format("%02d",seconds);
time_elapsed = min + ":" + sec;
time_elapsed = min + ":" + sec + "";
myhandler.postDelayed(new Runnable(){
public void run(){
periodicCall();
}
},1000);
}
Perhaps this will help: The right way to do a peridic task is registering the handler in the OnResume and unregister in in OnPause. (You can unregister it other places, but OnPause is important)
I think its better if you use a Service for implementing your timer. Even if you push back button, the Service will continue running.
Here you can see a question I asked a bit time ago. You can see the implementation of a Custom Chronometer using a Service.
The activity where you want to receive the value of the Chronometer just need to have a BroadcastReceiver like:
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
mMilis = intent.getLongExtra("milis",0);
String time = intent.getStringExtra("tiempo");
// Do Something with the time
}
};
This may not be a solution to the problem above, but if you just want to update a view and count up form a given time, maybe have a look at Chronometer. If you want to count down and update views, you can do that with CountDownTimer
You can use shared preference to use this method only once .
//pass true first time
protected void storeSharedPrefs(Boolean value) {
/*
* Storing in Shared Preferences
*/
editor.putString("first", value);
editor.commit(); //Commiting changes
}
Check each on time application is loaded, whether its the first time and configuration details has been entered correctly by checking SharedPreferences
private boolean first_time_check() {
/*
* Checking Shared Preferences if the user had pressed
* */
Boolean first = uPreferences.getString("first", false);
return first;
}
I have the service working now. I'm just having trouble getting information back from the service to the main activity.
I have added a function to try and retrieve the data from the service which is launched after the button click in the main activity launches the service:
startService(passvars);
//Init. variable for getDisplayInf() function to update the display with counter strings
Running = 1;
getDisplayInf();
And the getDisplayInf() ex:
public void getDisplayInf() {
//Intent stIntent = new Intent(MainActivity.this,MainActivity.class);
//Intent passvars = new Intent(MainActivity.this,Service.class);
Bundle getvars = getIntent().getExtras();
String Remaining;
String CountDown;
do {
Remaining = getvars.getString("Remaining");
CountDown = getvars.getString("CountDown");
mRemaining.setText(Remaining);
mCountDown.setText(CountDown);
Running = getvars.getInt("Running");
}
while (Running == 1);
};
The timer will set the Running variable to 0 on finish inside of the service.
As soon as I click the button with this new function in place it crashes the app, so I'm assuming it has to do with the Bundle/intent I'm using in the getDisplayInf() code.
In the service I'm doing this on the counter's onTick:
#Override
public void onTick(long millisUntilFinished) {
Running = 1;
Remaining = "Time Remaining: ";
CountDown = formatTime(millisUntilFinished);
ticker();
}
ticker's code:
public void ticker () {
Intent passvars = new Intent(Service.this,MainActivity.class);
//this is for the activity to keep looping to grab the countdown values while running this timer
//now send it to the activity
passvars.putExtra("Running", Running);
//String Values to be passed to the activity
//now send it to the activity
passvars.putExtra("mRemaining", Remaining);
//now send it to the activity
passvars.putExtra("mCountDown", CountDown);
};
Am I going about this in the right way? Is there an easier way? Some help would be greatly appreciated!!!