Making app to count time since first time used - java

How to make an app to count the time since the first time opened? I have no idea which class to use. Is it possible to achieve this with a stopwatch or something similar? Can someone pls share some code? I don't know what to search on the internet just have an idea of what I want to build. Or just tell me an idea with what I can achieve this and how?
statisticLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (plusiliminus==0){
Toast.makeText(getActivity(),R.string.toaststatistic,Toast.LENGTH_SHORT).show();
} else {
Fragment fragmentstatistic=new Statistic();
FragmentTransaction transaction=getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frameLayout,fragmentstatistic).commit();
}
}
});

As far as I could understand, you need persistent storage for the time when it was first used. I think SharedPreferences is a good way of storing this in your case.
In the onCreate function of your launcher activity, you might get the System.currentTimeInMillis() and store it in the SharedPreferences as stated here.
Then when you need to reset the time, you just have to clear the value in the SharedPreferences and can set a new value again.
I hope this gives you an idea of your implementation.

You have basically to do two things.
Get the current time when you start the app, or press a button using something like
Date currentTime = Calendar.getInstance().getTime();
This is a good beginning, you get the time, then you have to parse this time in a format you want to show to the user then you manage a stop and reset button as showed for instance in this tutorial
So you build a TextView and you show in real time the seconds, parsed in the way you need
import android.os.Handler;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView timer ;
Button start, pause, reset;
long MillisecondTime, StartTime, TimeBuff, UpdateTime = 0L ;
Handler handler;
int Seconds, Minutes, MilliSeconds ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timer = (TextView)findViewById(R.id.tvTimer);
start = (Button)findViewById(R.id.btStart);
pause = (Button)findViewById(R.id.btPause);
reset = (Button)findViewById(R.id.btReset);
handler = new Handler() ;
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
StartTime = SystemClock.uptimeMillis();
handler.postDelayed(runnable, 0);
reset.setEnabled(false);
}
});
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TimeBuff += MillisecondTime;
handler.removeCallbacks(runnable);
reset.setEnabled(true);
}
});
reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MillisecondTime = 0L ;
StartTime = 0L ;
TimeBuff = 0L ;
UpdateTime = 0L ;
Seconds = 0 ;
Minutes = 0 ;
MilliSeconds = 0 ;
timer.setText("00:00:00");
}
});
}
public Runnable runnable = new Runnable() {
public void run() {
MillisecondTime = SystemClock.uptimeMillis() - StartTime;
UpdateTime = TimeBuff + MillisecondTime;
Seconds = (int) (UpdateTime / 1000);
Minutes = Seconds / 60;
Seconds = Seconds % 60;
MilliSeconds = (int) (UpdateTime % 1000);
timer.setText("" + Minutes + ":"
+ String.format("%02d", Seconds) + ":"
+ String.format("%03d", MilliSeconds));
handler.postDelayed(this, 0);
}
};
}
and the view of activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimary"
tools:context="in.amitsin6h.stopwatch.MainActivity">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:paddingBottom="90dp">
<TextView
android:text="00:00:00"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tvTimer"
android:textSize="50dp"
android:textStyle="bold"
android:textColor="#ffffff"
android:layout_marginTop="120dp"
android:paddingBottom="50dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<Button
android:text="Start"
android:background="#ffffff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvTimer"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="41dp"
android:id="#+id/btStart" />
<Button
android:text="Pause"
android:background="#ffffff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btPause"
android:layout_alignBaseline="#+id/btStart"
android:layout_alignBottom="#+id/btStart"
android:layout_centerHorizontal="true" />
<Button
android:text="Reset"
android:background="#ffffff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/btPause"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/btReset" />
</RelativeLayout>
</android.support.constraint.ConstraintLayout>

Related

Sum timestamps from two textviews and display in new textview

I have two textviews and two buttons. When you click on the first button, a window with a choice of time opens. You select the time and it is displayed in textview1. Similarly with the second button and textview2. Now the main task is to sum this time and when you click on the Sum button, display the sum of the time in TextView3 (textview1 + textview2). any ideas how to implement this? preferably with code
XML code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is First Activity"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go to Second Activity"
android:id="#+id/btnActTwo"
android:onClick="onClick">
</Button>
<TextView
android:id="#+id/viewTime1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Time1" />
<Button
android:id="#+id/time1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Choose Time 1"
android:onClick="setTime"/>
<TextView
android:id="#+id/viewTime2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Time2" />
<Button
android:id="#+id/time2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Choose Time 2"
android:onClick="setTime2"
/>
<TextView
android:id="#+id/sum"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sum" />
<Button
android:id="#+id/btnSum"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SUM"
android:onClick="onClick2"/>
</LinearLayout>
And Main.java code:
package com.example.myapplication_lab4;
import androidx.appcompat.app.AppCompatActivity;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
TextView viewTime1;
TextView viewTime2;
TextView sum;
Button time1;
Button time2;
Button btnSum;
Calendar dateAndTime=Calendar.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewTime1 = (TextView) findViewById(R.id.viewTime1);
viewTime2 = (TextView) findViewById(R.id.viewTime2);
sum = (TextView) findViewById(R.id.sum);
time1 = (Button) findViewById(R.id.time1);
time2 = (Button) findViewById(R.id.time2);
btnSum = (Button) findViewById(R.id.btnSum);
}
// display a dialog box for selecting the time for 1
public void setTime(View v) {
new TimePickerDialog(MainActivity.this, t,
dateAndTime.get(Calendar.HOUR_OF_DAY),
dateAndTime.get(Calendar.MINUTE), true)
.show();
}
// display a dialog box for selecting the time for 2
public void setTime2(View v) {
new TimePickerDialog(MainActivity.this, t2,
dateAndTime.get(Calendar.HOUR_OF_DAY),
dateAndTime.get(Calendar.MINUTE), true)
.show();
}
// setting start time for 1
private void setInitialDateTime() {
viewTime1.setText(DateUtils.formatDateTime(this,
dateAndTime.getTimeInMillis(),
DateUtils.FORMAT_SHOW_TIME));
}
// setting start time for 2
private void setInitialDateTime2() {
viewTime2.setText(DateUtils.formatDateTime(this,
dateAndTime.getTimeInMillis(),
DateUtils.FORMAT_SHOW_TIME));
}
// setting the time picker for 1
TimePickerDialog.OnTimeSetListener t = new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
dateAndTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
dateAndTime.set(Calendar.MINUTE, minute);
setInitialDateTime();
}
};
// setting the time picker for 2
TimePickerDialog.OnTimeSetListener t2 = new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
dateAndTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
dateAndTime.set(Calendar.MINUTE, minute);
setInitialDateTime2();
}
};
//irrelevant to the issue
//Click to go to Activity 2
public void onClick(View view) {
Button btnActTwo;
btnActTwo = (Button) findViewById(R.id.btnActTwo);
if (view.getId() == R.id.btnActTwo) {//call sec act
Intent intent = new Intent(this, Activity2.class);
startActivity(intent);
}
}
public void onClick2(View view) {
}
}
Here is sample code of sum two date.
String time1="0:30:32";
String time2="0:35:20";
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
timeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date1 = timeFormat.parse(time1);
Date date2 = timeFormat.parse(time2);
long sum = date1.getTime() + date2.getTime();
String date3 = timeFormat.format(new Date(sum));
Log.e("TAG", "Date sum is => " + date3);
**Output: ** Date sum is => 01:05:52

how to create on button click start repeated notifications with specific time interval and on click stop notifications in android

creating a water remainder app and stuck on this for two days. there are 3 buttons to 15min, 30min, 60min user can click any one of this button then by clicking on Start Remainder button application will generate notification reminders ("Time to Drink Water") for every 15,30 or 60 min based on selected button. On click Stop Reminder button all reminders will end. am new to android trying my best and i hope stackoverflow community will help.
waterRemainder.java
public class waterRemainder extends AppCompatActivity implements View.OnClickListener {
Button min15, min30, min60, rstart, rstop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_water_remainder);
min15 = (Button) findViewById(R.id.min15);
min15.setOnClickListener(this);
min30 = (Button) findViewById(R.id.min30);
min30.setOnClickListener(this);
min60 = (Button) findViewById(R.id.min60);
min60.setOnClickListener(this);
rstart = (Button) findViewById(R.id.rstart);
rstart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StartRemainder();
}
});
rstop = (Button) findViewById(R.id.rstop);
rstart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StopRemainder();
}
});
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.min15:
SetRemainder(15);
case R.id.min30:
SetRemainder(30);
case R.id.min60:
SetRemainder(60);
}
}
public void SetRemainder(int minutes){
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE,5);
}
public void StartRemainder(){
NotificationCompat.Builder builder = new NotificationCompat.Builder(waterRemainder.this,"My Notification")
.setContentTitle("New Notification")
.setContentText("its working")
.setSmallIcon(R.drawable.ic_message)
.setAutoCancel(true);
}
public void StopRemainder(){
}
}
activity_water_remainder.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/main_header_selector"
tools:context=".waterRemainder">
<Button
android:id="#+id/min15"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="15 Min"
android:layout_above="#+id/min30"
android:layout_centerHorizontal="true"
android:layout_marginBottom="25dp"/>
<Button
android:id="#+id/min30"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="30 Min"
android:layout_above="#+id/min60"
android:layout_centerHorizontal="true"
android:layout_marginBottom="25dp"/>
<Button
android:id="#+id/min60"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="60 Min"
android:layout_centerInParent="true" />
<Button
android:id="#+id/rstart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="START
REMINDER"
android:layout_below="#+id/min60"
android:layout_toEndOf="#+id/min60"
android:layout_marginStart="20dp"
android:layout_marginTop="25dp"/>
<Button
android:id="#+id/rstop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="STOP
REMINDER"
android:layout_below="#+id/min60"
android:layout_toStartOf="#+id/min60"
android:layout_marginEnd="20dp"
android:layout_marginTop="25dp"/>
</RelativeLayout>
In SetRemainder function do the following:
Timer timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//here you can show notification method
}
}, delay, period);
}
where delay is the amount of time in milliseconds before first execution.. In your case set it to 0 and period is the amount of time in milliseconds between subsequent executions which in your case will be the 'minutes' variable.
And write timer.cancel(); in the stop method to cancel the timer.

setText function does not change the TextView

the app runs the way I want I can see that in the Logcat
but the text view is not changing and keeps the default value
i also tried to change button enable status programmatically but stayed in the same , nothing get changed !!
I tried in the setText method both
String.valueof(int)
and
Integer.toString(int)
java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play =(Button) findViewById(R.id.button4);
Pause =(Button) findViewById(R.id.button5);
hourstext =(TextView) findViewById(R.id.textView1);
mintext =(TextView) findViewById(R.id.textView2);
sectext =(TextView) findViewById(R.id.textView3);
}
void playb(View v) {
while (!ispause) {
sec = 0 ;
while (sec < 60) {
SystemClock.sleep(1000);
sec++;
sectext.setText(Integer.toString(sec));
Log.d("this", "sec value=" + sec);
}
sec = 0;
min++;
Log.d("this","min value ="+min);
mintext.setText(String.valueOf(min));
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/textView3"
android:layout_width="114dp"
android:layout_height="94dp"
android:layout_marginTop="159dp"
android:layout_marginEnd="16dp"
android:layout_x="274dp"
android:layout_y="120dp"
android:gravity="center|center_horizontal"
android:text="00"
android:textSize="40sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/pauseButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="72dp"
android:layout_marginTop="116dp"
android:layout_marginEnd="93dp"
android:layout_x="217dp"
android:layout_y="296dp"
android:enabled="false"
android:onClick="playb"
android:text="Pause"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/playbutton"
app:layout_constraintTop_toBottomOf="#+id/textView3" />
<Button
android:id="#+id/playbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="70dp"
android:layout_marginTop="116dp"
android:layout_x="63dp"
android:layout_y="293dp"
android:onClick="playb"
android:text="playb"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView2" />
<TextView
android:id="#+id/textView2"
android:layout_width="120dp"
android:layout_height="97dp"
android:layout_marginTop="156dp"
android:layout_marginEnd="17dp"
android:layout_x="139dp"
android:layout_y="117dp"
android:gravity="center|center_horizontal"
android:text="00"
android:textSize="40sp"
app:layout_constraintEnd_toStartOf="#+id/textView3"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView1"
android:layout_width="103dp"
android:layout_height="94dp"
android:layout_marginStart="16dp"
android:layout_marginTop="159dp"
android:layout_x="11dp"
android:layout_y="117dp"
android:gravity="center_horizontal|center_vertical"
android:text="00"
android:textSize="40sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
i get no error message ! the app keeps working but no updated textView
i've included my XML Code
It's likely to do with running everything on the main thread. You should never call sleep on the main thread or you will block the UI.
When the button is clicked you should start the counter on a background thread. You will then need to update the TextView on the main thread.
It can be achieved quite easily with RxJava:
private Disposable disposable;
disposable = Observable.interval(1, 1, TimeUnit.SECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(value -> {
// Update UI
});
To stop the counter:
disposable.dispose();
If you want make counter up for 60 sec you can use this code
long time=60;
new CountDownTimer(time*1000, 1000)
{
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds : " + (time-millisUntilFinished /1000));
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
Before trying to fix this problem, let first understand why it happens
CAUSE
When you call View.setText(), Android doesn't actually set the text immediately. It pushes all of these set-text works to a queue on main thread to do LATER whenever it has free time.
Let's try to run this block, you will notice that until this while loop finish, View.setText() will not be done.
void playb(View v) {
min = 0
while (min < 1000000) {
min++
Log.d("this", "min value =$min")
mintext.setText(String.valueOf(min))
}
}
So in your situtation, actually the TextView will still be set, but you will not see the change until the while loop finishes.
SOLUTION
You should move this while loop to another thread, you can simply use an AsyncTask or a HandlerThread for that
Ex. Use a HandlerThread:
void playb() {
// Start a new background thread
HandlerThread thread = new HandlerThread("");
thread.start();
// Obtain the handler of new background thread
Handler handler = new Handler(thread.getLooper());
// Obtain the handler of main thread (UI Thread)
final Handler mainHandler = new Handler(this.getMainLooper());
// Create a runnable and send it to background thread to execute
handler.post(new Runnable() {
public final void run() {
// Do the job
int min = 0;
while(true) {
int sec = 0;
while(sec < 60) {
SystemClock.sleep(1000L);
sec ++;
final int currentSec = sec;
// Send the update-text job to main thread to execute
mainHandler.post(new Runnable() {
public final void run() {
secText.setText(currentSec);
}
});
}
sec = 0;
min++;
final int currentMin = min;
// Send the update-text job to main thread to execute
mainHandler.post(new Runnable() {
public final void run() {
minText.setText(currentMin);
}
});
}
}
});
}

How to efficiently put a multitude of stopwatches on one activity?

I made a single working stopwatch, but I can't figure out a way to add several to the same page. What would be an effective way to do this? I tried copying the code and changing all the parameters but that did not seem to work.
The code I have at the moment:
XML
<RelativeLayout
android:layout_width="368dp"
android:layout_height="495dp"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp">
<EditText
android:id="#+id/topTextInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:layout_toLeftOf="#+id/timeOne"
android:layout_toStartOf="#+id/timeOne"
android:width="300dp"
android:elevation="1dp" />
<TextView
android:id="#+id/timeOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/topTextInput"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginEnd="13dp"
android:layout_marginRight="13dp"
android:layout_marginTop="50dp"
android:clickable="false"
android:elevation="4dp"
android:text="00:00:00"
android:textSize="24sp"
android:visibility="visible" />
<Button
android:id="#+id/stopbuttonOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/topTextInput"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/topTextInput"
android:layout_toEndOf="#+id/topTextInput"
android:layout_toRightOf="#+id/topTextInput"
android:width="110dp"
android:background="#android:color/darker_gray"
android:onClick="stopClick"
android:text=""
android:visibility="invisible" />
<Button
android:id="#+id/startbuttonOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/topTextInput"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/topTextInput"
android:layout_toEndOf="#+id/topTextInput"
android:layout_toRightOf="#+id/topTextInput"
android:width="120dp"
android:onClick="startClick"
android:text=""
android:visibility="visible" />
<Button
android:id="#+id/resetButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Reset"
android:onClick="resetClick" />
<TextView
android:id="#+id/millitimeOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/timeOne"
android:visibility="visible" />
</RelativeLayout>
Java:
package com.keur.joran.time;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity
{
private TextView tempTextView; //Temporary TextView
private Button tempBtn; //Temporary Button
private Handler mHandler = new Handler();
private Handler m2Handler = new Handler();
private long startTime;
private long elapsedTime;
private long start2Time;
private long elapsed2Time;
private final int REFRESH_RATE = 100;
private String hours,minutes,seconds,milliseconds;
private long secs,mins,hrs,msecs;
private boolean stopped = false;
private Runnable startTimer = new Runnable() { public void run() { elapsedTime = System.currentTimeMillis() - startTime; updateTimer(elapsedTime); mHandler.postDelayed(this,REFRESH_RATE); } };
private Runnable start2Timer = new Runnable() { public void run() { elapsed2Time = System.currentTimeMillis() - start2Time; updateTimer(elapsed2Time); mHandler.postDelayed(this,REFRESH_RATE); } };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void stopClick (View view){ hideStopButton(); mHandler.removeCallbacks(startTimer); stopped = true; }
public void startClick (View view){ showStopButton(); if(stopped){ startTime = System.currentTimeMillis() - elapsedTime; } else{ startTime = System.currentTimeMillis(); } mHandler.removeCallbacks(startTimer); mHandler.postDelayed(startTimer, 0); }
public void resetClick (View view){ stopped = false; ((TextView)findViewById(R.id.timeOne)).setText("00:00:00"); ((TextView)findViewById(R.id.millitimeOne)).setText(".0"); }
private void showStopButton(){ ((Button)findViewById(R.id.startbuttonOne)).setVisibility(View.GONE);
((Button)findViewById(R.id.stopbuttonOne)).setVisibility(View.VISIBLE);
}
private void hideStopButton(){ ((Button)findViewById(R.id.startbuttonOne)).setVisibility(View.VISIBLE);
((Button)findViewById(R.id.stopbuttonOne)).setVisibility(View.GONE);
}
private void updateTimer (float time){ secs = (long)(time/1000);
mins = (long)((time/1000)/60); hrs = (long)(((time/1000)/60)/60);
/* Convert the seconds to String * and format to ensure it has * a leading zero when required */
secs = secs % 60;seconds=String.valueOf(secs);
if(secs == 0){ seconds = "00"; } if(secs <10 && secs > 0){ seconds = "0"+seconds;
}
/* Convert the minutes to String and format the String */ mins = mins % 60; minutes=String.valueOf(mins); if(mins == 0){ minutes = "00"; } if(mins <10 && mins > 0){ minutes = "0"+minutes; } /* Convert the hours to String and format the String */ hours=String.valueOf(hrs); if(hrs == 0){ hours = "00"; } if(hrs <10 && hrs > 0){ hours = "0"+hours; } /* Although we are not using milliseconds on the timer in this example * I included the code in the event that you wanted to include it on your own */ milliseconds = String.valueOf((long)time); if(milliseconds.length()==2){ milliseconds = "0"+milliseconds; } if(milliseconds.length()<=1){ milliseconds = "00"; } milliseconds = milliseconds.substring(milliseconds.length()-3, milliseconds.length()-2); /* Setting the timer text to the elapsed time */ ((TextView)findViewById(R.id.timeOne)).setText(hours + ":" + minutes + ":" + seconds); ((TextView)findViewById(R.id.millitimeOne)).setText("." + milliseconds); }
}
Turn the stopwatch into either a custom view or fragment. Then you should only need to include the view/fragment in the xml, and call the appropriate event handler functions you added in the java code.

R cannot resolved to a variable in eclipse android [duplicate]

This question already has answers here:
R cannot be resolved - Android error
(108 answers)
Closed 6 years ago.
This is my xml code R file is not generating please tell me where is the error and why R file is not generating
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="#333333"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin" >
<TextView
android:id="#+id/SongName"
android:layout_width="wrap_content"
android:text="#string/songName"
android:layout_height="wrap_content"/>
<ImageView
android:id="#+id/s_mp3Image"
android:layout_width="match_parent"
android:layout_height="200dp"
android:padding="30dp"
android:contentDescription="#string/music"
android:src="#drawable/music"
android:background="#ffffff"
android:layout_margin="30dp" />
<TextView
android:id="#+id/songDuration"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/songDuration"
android:layout_gravity="center"/>
<SeekBar
android:id="#+id/s_seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="30dp"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<ImageButton
android:id="#+id/s_media_rew"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="14dp"
android:onClick="rewind"
android:contentDescription="#string/ic_media_rew"
android:src="#android:drawable/ic_media_rew" />
<ImageButton
android:id="#+id/s_media_pause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="14dp"
android:onClick="pause"
android:contentDescription="#string/media_pause"
android:src="#android:drawable/ic_media_pause" />
<ImageButton
android:id="#+id/s_media_play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="14dp"
android:onClick="play"
android:contentDescription="#string/ic_media_play"
android:src="#android:drawable/ic_media_play" />
<ImageButton
android:id="#+id/s_media_ff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="14dp"
android:onClick="forward"
android:contentDescription="#string/ic_media_ff"
android:src="#android:drawable/ic_media_ff" />
</LinearLayout>
and this is my java code
package com.example.androidmediaplayer;
import java.util.concurrent.TimeUnit;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.VideoView;
public class MainActivity extends Activity {
private MediaPlayer mediaPlayer;
public TextView songName, duration;
private double timeElapsed = 0, finalTime = 0;
private int forwardTime = 2000, backwardTime = 2000;
private Handler durationHandler = new Handler();
private SeekBar seekbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set the layout of the Activity
setContentView(R.layout.activity_list_item); //here R file has problem
//initialize views
initializeViews();
}
public void initializeViews(){
songName=(TextView)findViewById(R.id.SongName); //here R file has problem
mediaPlayer = MediaPlayer.create(this, R.raw.sample); //here
finalTime = mediaPlayer.getDuration();
duration = (TextView) findViewById(R.id.songDuration); //here
seekbar = (SeekBar) findViewById(R.id.s_seekBar); //here
songName.setText("Sample_Song.mp3");
seekbar.setMax((int) finalTime);
seekbar.setClickable(false);
}
// play mp3 song
public void play(View view) {
mediaPlayer = new MediaPlayer();
mediaPlayer.start();
timeElapsed = mediaPlayer.getCurrentPosition();
seekbar.setProgress((int) timeElapsed);
durationHandler.postDelayed(updateSeekBarTime, 100);
}
//handler to change seekBarTime
#SuppressLint("NewApi")
private Runnable updateSeekBarTime = new Runnable() {
#SuppressLint("NewApi")
public void run() {
//get current position
timeElapsed = mediaPlayer.getCurrentPosition();
//set seekBar progress
seekbar.setProgress((int) timeElapsed);
//set time remaining
double timeRemaining = finalTime - timeElapsed;
duration.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining), TimeUnit.MILLISECONDS.toSeconds((long) timeRemaining) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining))));
//repeat yourself that again in 100 milliseconds
durationHandler.postDelayed(this, 100);
}
};
// pause mp3 song
public void pause(View view) {
mediaPlayer.pause();
}
// go forward at forwardTime seconds
public void forward(View view) {
//check if we can go forward at forwardTime seconds before song
if ((timeElapsed + forwardTime) <= finalTime) {
timeElapsed = timeElapsed + forwardTime;
//seek to the exact second of the track
mediaPlayer.seekTo((int) timeElapsed);
}
}
// go backwards at backwardTime seconds
public void rewind(View view) {
//check if we can go back at backwardTime seconds after song starts
if ((timeElapsed - backwardTime) > 0) {
timeElapsed = timeElapsed - backwardTime;
//seek to the exact second of the track
mediaPlayer.seekTo((int) timeElapsed);
}
}
}
This is my code R file is not generating please tell me where is the error and why R file is not generating
This is my xml code R file is not generating please tell me where is the error and why R file is not generating This is my xml code R file is not generating please tell me where is the error and why R file is not generating This is my xml code R file is not generating please tell me where is the error and why R file is not generating
You should try cleaning your project !!
Try Clean your Project.
OR
Restart Eclipse.
Or
Check with All XML Resources you have used. Is their any missing things in your XML.
This case mostly happens when you have Something wrong with your XML Resources you are using.

Categories