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.
Related
I have a Counttimer and edittext on my app. I want write a number in edittext, and when I click button, then countdown timer will start, and the time is edittext variable. In XML, I have got an example number, because when I delete it, then it's not working. When I start countdown timer, then it works, but if I change edittext, then it uses the old edittext data. How can I solve my problem?
pomodoro.XML
<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"
tools:context=".pomodoro"
android:background="#drawable/backround_home">
<
<EditText
android:id="#+id/edittextcalisma"
android:layout_width="80dp"
android:layout_height="40dp"
android:text="20"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="25dp"
android:background="#drawable/edittext"
android:layout_marginLeft="30dp"
android:visibility="visible"
android:inputType="number"
android:maxLength="2"
android:lines="1"
/>
<EditText
android:id="#+id/edittextmola"
android:layout_width="80dp"
android:layout_height="40dp"
android:text="5"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="25dp"
android:background="#drawable/edittext"
android:visibility="visible"
android:layout_marginLeft="30dp"
android:inputType="number"
android:maxLength="2"
android:lines="1"
/>
<Button
android:id="#+id/baslatbutton"
android:layout_width="150dp"
android:layout_height="50dp"
android:text="Başla"
android:textSize="25dp"
android:layout_marginTop="400dp"
android:textColor="#ffffff"
android:fontFamily="#font/montserrat_regular"
android:background="#drawable/button"
android:layout_centerHorizontal="true"
android:visibility="visible"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="40dp"
android:layout_centerInParent="true"
android:fontFamily="#font/montserrat_regular"
android:textColor="#000000"
android:id="#+id/pomodoro"
android:visibility="invisible"
/>
</RelativeLayout>
Java.class
public class pomodoro extends AppCompatActivity {
Button baslat;
EditText edittextcalisma,edittextmola;
TextView textcalisma,textmola,pomodoro;
CountDownTimer calisma,mola;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pomodoro);
baslat = findViewById(R.id.baslatbutton);
edittextcalisma = findViewById(R.id.edittextcalisma);
edittextmola = findViewById(R.id.edittextmola);
textcalisma = findViewById(R.id.textcalisma);
textmola = findViewById(R.id.textmola);
String timercalisma = edittextcalisma.getText().toString();
String timermola = edittextmola.getText().toString();
long calismapo = Long.parseLong(timercalisma) * 60000;
long molapo = Long.parseLong(timermola) * 60000;
pomodoro = findViewById(R.id.pomodoro);
baslat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pomodoro.setVisibility(View.VISIBLE);
calisma.start();
}
});
calisma = new CountDownTimer(calismapo, 1000) {
#Override
public void onTick(long millis) {
int minuted1 = (int) (millis / 1000) / 60;
int secondd1 = (int) (millis / 1000) % 60;
pomodoro.setText(minuted1 + ":" + secondd1);
if (secondd1 < 10) {
pomodoro.setText(minuted1 + ":0" + secondd1);
}
}
#Override
public void onFinish() {
calisma.cancel();
mola.start();
}
};
mola = new CountDownTimer(molapo, 1000) {
#Override
public void onTick(long molapo) {
int minuted1 = (int) (molapo / 1000) / 60;
int secondd1 = (int) (molapo / 1000) % 60;
pomodoro.setText(minuted1 + ":" + secondd1);
if (secondd1 < 10) {
pomodoro.setText(minuted1 + ":0" + secondd1);
}
}
#Override
public void onFinish() {
mola.cancel();
pomodoro.setText("Bitti");
}
};
}
}
and the time is edittext variable. In XML, I have got an example
number, because when I delete it, then it's not working.
Because you read your EditText fields in the onCreate and your code expects a number, then that is why you need to set the "example" numbers in XML.
When you remove the number from XML, you either need to:
check for null
String timercalisma = edittextcalisma.getText().toString();
String timermola = edittextmola.getText().toString();
if(timercalisma == null || timercalisma.isEmpty()) {
timercalisma = "0";
}
if(timermola == null || timermola.isEmpty()) {
timermola = "0";
}
long calismapo = Long.parseLong(timercalisma) * 60000;
long molapo = Long.parseLong(timermola) * 60000;
or read the fields on button press
baslat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String timercalisma = edittextcalisma.getText().toString();
String timermola = edittextmola.getText().toString();
long calismapo = Long.parseLong(timercalisma) * 60000;
long molapo = Long.parseLong(timermola) * 60000;
pomodoro.setVisibility(View.VISIBLE);
calisma.start();
}
});
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>
I am trying to use splash screen for my app.
I want to display Count down timer in my splash screen.
So far I am able to achieve the splash screen working but don't know how to display count down timer. I created layout for count down timer. I want splash screen to stay for 5 Hours then take to the next activity.
Splashactivity.java
public class splash_screen extends AppCompatActivity {
private float imageAplha = 1f;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
//splashScreenUseTimer(5000);
splashScreenUseAsyncTask();
}
// Show splash screen until network load data complete.
private void splashScreenUseAsyncTask()
{
// Create a AsyncTask object.
final RetrieveDateTask retrieveDateTask = new RetrieveDateTask();
retrieveDateTask.execute("", "", "");
// Get splash image view object.
final ImageView splashImageView = (ImageView) findViewById(R.id.logo_id);
// Create a count down timer object.It will count down every 0.1 seconds and last for milliSeconds milliseconds..
CountDownTimer countDownTimer = new CountDownTimer(5000, 100) {
#Override
public void onTick(long l) {
// Reduce the splash screen background image's alpha value for each count down.
splashImageView.setAlpha(imageAplha);
imageAplha -= 0.1;
if(imageAplha <= 0)
{
imageAplha = 1;
}
}
#Override
public void onFinish() {
// When count down complete, set the image to invisible.
imageAplha = 0;
splashImageView.setAlpha(imageAplha);
// If AsyncTask is not complete, restart the counter to count again.
if(!retrieveDateTask.isAsyncTaskComplete()) {
this.start();
}
}
};
// Start the count down timer.
countDownTimer.start();
}
// This is the async task class that get data from network.
private class RetrieveDateTask extends AsyncTask<String, String, String>{
// Indicate whether AsyncTask complete or not.
private boolean asyncTaskComplete = false;
public boolean isAsyncTaskComplete() {
return asyncTaskComplete;
}
public void setAsyncTaskComplete(boolean asyncTaskComplete) {
this.asyncTaskComplete = asyncTaskComplete;
}
// This method will be called before AsyncTask run.
#Override
protected void onPreExecute() {
this.asyncTaskComplete = false;
}
// This method will be called when AsyncTask run.
#Override
protected String doInBackground(String... strings) {
try {
// Simulate a network operation which will last for 10 seconds.
Thread currTread = Thread.currentThread();
for (int i = 0; i < 10; i++) {
currTread.sleep(1000);
}
}catch(Exception ex)
{
ex.printStackTrace();
}finally {
return null;
}
}
// This method will be called after AsyncTask run.
#Override
protected void onPostExecute(String s) {
// Start SplashScreenMainActivity.
Intent mainIntent = new Intent(splash_screen.this,
MainActivity.class);
splash_screen.this.startActivity(mainIntent);
// Close SplashScreenActivity.
splash_screen.this.finish();
this.asyncTaskComplete = true;
}
}
}
Layout
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0"
android:background="#color/White"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical">
<ImageView
android:id="#+id/logo_id"
android:layout_width="350dp"
android:layout_height="match_parent"
app:srcCompat="#drawable/ts_logo"
android:layout_gravity="center"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"
android:orientation="vertical">
<LinearLayout
android:id="#+id/linear_layout_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/black"
android:visibility="visible">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="#+id/tv_hour"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="00"
android:textColor="#android:color/white"
android:textSize="20dp"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_hour_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hour"
android:textColor="#android:color/white"
android:textSize="20dp"
android:textStyle="normal" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="#+id/tv_minute"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="00"
android:textColor="#android:color/white"
android:textSize="20dp"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_minute_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Minute"
android:textColor="#android:color/white"
android:textSize="20dp"
android:textStyle="normal" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="#+id/tv_second"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="00"
android:textColor="#android:color/white"
android:textSize="20dp"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_second_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Second"
android:textColor="#android:color/white"
android:textSize="20dp"
android:textStyle="normal" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
#contact dummy I edited #Dev code with small modification.try this one. Based on your animation requirement increase and decrease imageAlpha size.
private float imageAplha = 1f;
private boolean imageStatus = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
splashScreenUseAsyncTask();
}
// Show splash screen until network load data complete.
private void splashScreenUseAsyncTask()
{
// Create a AsyncTask object.
final RetrieveDateTask retrieveDateTask = new RetrieveDateTask();
retrieveDateTask.execute("", "", "");
// Get splash image view object.
final ImageView splashImageView = (ImageView) findViewById(R.id.logo_id);
final TextView tv_hour = (TextView) findViewById(R.id.tv_hour);
final TextView tv_minute = (TextView) findViewById(R.id.tv_minute);
final TextView tv_second = (TextView) findViewById(R.id.tv_second);
// Create a count down timer object.It will count down every 0.1 seconds and last for milliSeconds milliseconds..
final int time= 3600000*5;
CountDownTimer countDownTimer = new CountDownTimer(time, 1000) {
#Override
public void onTick(long l) {
long Days = l / (24 * 60 * 60 * 1000);
long Hours = l / (60 * 60 * 1000) % 24;
long Minutes = l / (60 * 1000) % 60;
long Seconds = l / 1000 % 60;
//
// tv_days.setText(String.format("%02d", Days));
tv_hour.setText(String.format("%02d", Hours));
tv_minute.setText(String.format("%02d", Minutes));
tv_second.setText(String.format("%02d", Seconds));
splashImageView.setAlpha(imageAplha);
if(imageStatus){
imageAplha += 1;
if(imageAplha >= 1)
{
// imageAplha-= 0.5;
imageStatus = false;
}
}else{
imageAplha -= 1;
if(imageAplha <= 0)
{
imageStatus = true;
}
}
}
#Override
public void onFinish() {
// When count down complete, set the image to invisible.
imageAplha = 0;
splashImageView.setAlpha(imageAplha);
// If AsyncTask is not complete, restart the counter to count again.
if(!retrieveDateTask.isAsyncTaskComplete()) {
this.start();
}
}
};
// Start the count down timer.
countDownTimer.start();
}
// This is the async task class that get data from network.
private class RetrieveDateTask extends AsyncTask<String, String, String> {
// Indicate whether AsyncTask complete or not.
private boolean asyncTaskComplete = false;
public boolean isAsyncTaskComplete() {
return asyncTaskComplete;
}
public void setAsyncTaskComplete(boolean asyncTaskComplete) {
this.asyncTaskComplete = asyncTaskComplete;
}
// This method will be called before AsyncTask run.
#Override
protected void onPreExecute() {
this.asyncTaskComplete = false;
}
// This method will be called when AsyncTask run.
#Override
protected String doInBackground(String... strings) {
try {
// Simulate a network operation which will last for 10 seconds.
Thread currTread = Thread.currentThread();
for (int i = 0; i < 18000000; i++) {
currTread.sleep(1000);
}
}catch(Exception ex)
{
ex.printStackTrace();
}finally {
return null;
}
}
// This method will be called after AsyncTask run.
#Override
protected void onPostExecute(String s) {
// Start SplashScreenMainActivity.
Intent mainIntent = new Intent(splash_screen .this,
MainActvity.class);
splash_screen.this.startActivity(mainIntent);
// Close SplashScreenActivity.
splash_screen.this.finish();
this.asyncTaskComplete = true;
}
}
}
#contact dummy I have edited your code try using this
// Show splash screen until network load data complete.
private void splashScreenUseAsyncTask()
{
// Create a AsyncTask object.
final RetrieveDateTask retrieveDateTask = new RetrieveDateTask();
retrieveDateTask.execute("", "", "");
// Get splash image view object.
final ImageView splashImageView = (ImageView) findViewById(R.id.logo_id);
//for 5 Hours
final int time= 3600000*5;
CountDownTimer countDownTimer = new CountDownTimer(time, 1000) {
#Override
public void onTick(long l) {
long Days = l / (24 * 60 * 60 * 1000);
long Hours = l / (60 * 60 * 1000) % 24;
long Minutes = l / (60 * 1000) % 60;
long Seconds = l / 1000 % 60;
//
tv_days.setText(String.format("%02d", Days));
tv_hour.setText(String.format("%02d", Hours));
tv_minute.setText(String.format("%02d", Minutes));
tv_second.setText(String.format("%02d", Seconds));
splashImageView.setAlpha(imageAplha);
imageAplha -= 0.1;
if(imageAplha <= 0)
{
imageAplha = 1;
}
}
#Override
public void onFinish() {
// When count down complete, set the image to invisible.
imageAplha = 0;
splashImageView.setAlpha(imageAplha);
// If AsyncTask is not complete, restart the counter to count again.
if(!retrieveDateTask.isAsyncTaskComplete()) {
this.start();
}
}
};
// Start the count down timer.
countDownTimer.start();
}
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.
I've been learning some java for android by reading and trying codes, and whenever I start the application on android it crashes. In the LogCat, this shows:
08-09 16:13:24.033: E/AndroidRuntime(839): ... 11 more
Here is my activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dip">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="Brews: " />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="None"
android:gravity="end"
android:textSize="20sp"
android:id="#+id/brew_count_label" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="center"
android:padding="10dip">
<Button
android:id="#+id/brew_time_down"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="-"
android:textSize="40sp" />
<TextView
android:id="#+id/brew_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0:00"
android:textSize="40sp"
android:padding="10dip" />
<Button
android:id="#+id/brew_time_up"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+"
android:textSize="40sp" />
</LinearLayout>
<Button
android:id="#+id/brew_start"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:text="Start" />
</LinearLayout>
And here is my MainActivity.java:
package com.example.basketball;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements OnClickListener {
/** Properties **/
protected Button brewAddTime;
protected Button brewDecreaseTime;
protected Button startBrew;
protected TextView brewCountLabel;
protected TextView brewTimeLabel;
protected int brewTime = 3;
protected CountDownTimer brewCountDownTimer;
protected int brewCount = 0;
protected boolean isBrewing = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
// Connect interface elements to properties
brewAddTime = (Button) findViewById(R.id.brew_time_up);
brewDecreaseTime = (Button) findViewById(R.id.brew_time_down);
startBrew = (Button) findViewById(R.id.brew_start);
brewCountLabel = (TextView) findViewById(R.id.brew_count_label);
brewTimeLabel = (TextView) findViewById(R.id.brew_time);
// Setup ClickListeners
brewAddTime.setOnClickListener(this);
brewDecreaseTime.setOnClickListener(this);
startBrew.setOnClickListener(this);
// Set the initial brew values
setBrewCount(0);
setBrewTime(3);
}
/** Methods **/
/**
* Set an absolute value for the number of minutes to brew. Has no effect if a brew
* is currently running.
* #param minutes The number of minutes to brew.
*/
public void setBrewTime(int minutes) {
if(isBrewing)
return;
brewTime = minutes;
if(brewTime < 1)
brewTime = 1;
brewTimeLabel.setText(String.valueOf(brewTime) + "m");
}
/**
* Set the number of brews that have been made, and update the interface.
* #param count The new number of brews
*/
public void setBrewCount(int count) {
brewCount = count;
brewCountLabel.setText(String.valueOf(brewCount));
}
/**
* Start the brew timer
*/
public void startBrew() {
// Create a new CountDownTimer to track the brew time
brewCountDownTimer = new CountDownTimer(brewTime * 60 * 1000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
brewTimeLabel.setText(String.valueOf(millisUntilFinished / 1000) + "s");
}
#Override
public void onFinish() {
isBrewing = false;
setBrewCount(brewCount + 1);
brewTimeLabel.setText("Brew Up!");
startBrew.setText("Start");
}
};
brewCountDownTimer.start();
startBrew.setText("Stop");
isBrewing = true;
}
/**
* Stop the brew timer
*/
public void stopBrew() {
if(brewCountDownTimer != null)
brewCountDownTimer.cancel();
isBrewing = false;
startBrew.setText("Start");
}
/** Interface Implementations **/
/* (non-Javadoc)
* #see android.view.View.OnClickListener#onClick(android.view.View)
*/
public void onClick(View v) {
if(v == brewAddTime)
setBrewTime(brewTime + 1);
else if(v == brewDecreaseTime)
setBrewTime(brewTime -1);
else if(v == startBrew) {
if(isBrewing)
stopBrew();
else
startBrew();
}
}
}
Anyone knows how to fix this error?
Please help.
Please uncomment setContentView(R.layout.main); and change that line to setContentView(R.layout.activity_main); in
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);