Show final time in Alert Dialog after 10 button clicks - android

Right now I have my app set to show an alert dialog after 10 button clicks as well as stop the timer. I cannot figure out how to display the final time the timer stops on in the alert dialog. I want to make an alert dialog that displays that the game is over and also displays the players final time. Any idea how I would do this? Please help if you can.
JAVA CODE:
package com.example.thirtytapgametest;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AnalogClock;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
public class MainActivity extends Activity {
private int mCount = 0;
private ImageButton startbutton;
private TextView timerValue;
private long startTime = 0L;
private Handler customHandler = new Handler();
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView countTextView = (TextView) findViewById(R.id.TextViewCount);
timerValue = (TextView) findViewById(R.id.timerValue);
startbutton = (ImageButton) findViewById(R.id.imageButton1);
startbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (mCount ==0) {
startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
}
mCount++;
countTextView.setText("Taps: " + mCount);
if(mCount == 10) {
view.setEnabled(false);
customHandler.removeCallbacks(updateTimerThread);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this)
.setTitle("Congratulations!")
.setMessage((R.id.timerValue))
.setIcon(R.drawable.ic_launcher)
.setCancelable(false)
.setPositiveButton(getString(R.string.play_again), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();}})
.setNegativeButton(getString(R.string.levels_menu), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();}});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
});
}
private Runnable updateTimerThread = new Runnable() {
public void run() {
updatedTime = SystemClock.uptimeMillis() - startTime;
int secs = (int) (updatedTime / 1000);
int mins = secs / 60;
secs = secs % 60;
int milliseconds = (int) (updatedTime % 1000);
timerValue.setText("Time: " + "" + mins + ":"
+String.format("%02d", secs) + ":"
+String.format("%03d", milliseconds));
customHandler.postDelayed(this, 0);
}
};
}
XML CODE:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:background="#drawable/thirty_tap_game_background">
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="200dp"
android:layout_height="100dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="138dp"
android:background="#drawable/test_play_button" />
<TextView
android:id="#+id/timerValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/imageButton1"
android:layout_centerHorizontal="true"
android:layout_marginBottom="32dp"
android:textSize="40sp"
android:textColor="#FFFFFF"
android:text="#string/timerVal" />
<TextView
android:id="#+id/TextViewCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="73dp"
android:text="#string/countVal"
android:textSize="30sp"
android:textColor="#FFFFFF"/>
</RelativeLayout>

You can do this
int i =0; // declare this globally.
btn.setonclicklistener(new onClicklistener
onclick(View v){
i++;
if(i==10){
// show alert dialog
}
else{
// to do your stub here
}
}

You'll want to use the set message method in your AlertDialog builder.
.setTitle("Congratulations!")
.setMessage("Your time was: " + updatedTime)
.setIcon(R.drawable.ic_launcher)

why dont you use this?
http://developer.android.com/reference/android/widget/TextClock.html
and your code shows you using :
.setMessage((R.id.timerValue))
R.id.viewName refers to the hex id of the resource .Using this will not set the value that is contained in the textView.
you could try:
.setMessage(((TextView)R.id.timerValue).getText().toString())
or you could declare the text view earlier and call TextView.getText().toString() while creating the dialog.

Related

Android timer,Broadcast Receiver,

Developing a timer application,
Have 4 buttons
start--Will start the timer
stop-- will stop timer
pause--will pause timer
lap time--will calculate lap time.
when button click it s working Good.
Now i am Modify the application like timer should start when phone is connected to charger and pause when phone is disconnected from charger.
The timer is starting fine when connected to the charger,
but during discharging the stop timer is not stopping at the accurate time it will be misplaced with some other time.i.e delay in minutes and seconds.
How to make the timer pause and show correct timer when disconnected from the charger...?
MainActivity.java
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends Activity {
private static final String TAG ="Main Activity";
TextView textView;
Button start, pause, reset, lap;
long MillisecondTime, StartTime, TimeBuff, UpdateTime = 0L;
Handler handlerr;
int Seconds, Minutes, MilliSeconds;
ListView listView;
String[] ListElements = new String[]{};
List<String> ListElementsArrayList;
ArrayAdapter<String> adapter;
TextView textview;
Button button;
IntentFilter intentfilter;
int deviceStatus;
String currentBatteryStatus = "Battery Info";
int batteryLevel;
Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview = (TextView) findViewById(R.id.textViewBatteryStatus);
intentfilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
MainActivity.this.registerReceiver(broadcastreceiver, intentfilter);
textView = (TextView)findViewById(R.id.textView);
start = (Button)findViewById(R.id.button);
pause = (Button)findViewById(R.id.button2);
reset = (Button)findViewById(R.id.button3);
lap = (Button)findViewById(R.id.button4) ;
listView = (ListView)findViewById(R.id.listview1);
handler = new Handler() ;
ListElementsArrayList = new ArrayList<String>(Arrays.asList(ListElements));
adapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1,
ListElementsArrayList
);
listView.setAdapter(adapter);
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 ;
textView.setText("00:00:00");
ListElementsArrayList.clear();
adapter.notifyDataSetChanged();
}
});
lap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ListElementsArrayList.add(textView.getText().toString());
adapter.notifyDataSetChanged();
}
});
}
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);
textView.setText("" + Minutes + ":"
+ String.format("%02d", Seconds) + ":"
+ String.format("%03d", MilliSeconds));
handler.postDelayed(this, 0);
}
};
// Broadcasts receiver//
private BroadcastReceiver broadcastreceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
deviceStatus = intent.getIntExtra(BatteryManager.EXTRA_STATUS,-1);
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int batteryLevel=(int)(((float)level / (float)scale) * 100.0f);
if(deviceStatus == BatteryManager.BATTERY_STATUS_CHARGING){
StartTime = SystemClock.uptimeMillis();
handler.postDelayed(runnable, 0);
reset.setEnabled(false);
textview.setText(currentBatteryStatus+" = Charging at "+batteryLevel+" %");
}
if(deviceStatus == BatteryManager.BATTERY_STATUS_DISCHARGING){
textview.setText(currentBatteryStatus+" = Discharging at "+batteryLevel+" %");
}
if (deviceStatus == BatteryManager.BATTERY_STATUS_FULL){
textview.setText(currentBatteryStatus+"= Battery Full at "+batteryLevel+" %");
}
if(deviceStatus == BatteryManager.BATTERY_STATUS_UNKNOWN){
textview.setText(currentBatteryStatus+" = Unknown at "+batteryLevel+" %");
}
if (deviceStatus == BatteryManager.BATTERY_STATUS_NOT_CHARGING){
TimeBuff += MillisecondTime;
handler.removeCallbacks(runnable);
reset.setEnabled(true);
textview.setText(currentBatteryStatus+" = Not Charging at "+batteryLevel+" %");
}
}
};
}
activity_main.xml
<TextView
android:text="00:00:00"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:textSize="50dp"
android:textStyle="bold"
android:textColor="#009688"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<Button
android:text="Start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="41dp"
android:id="#+id/button" />
<Button
android:text="Pause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button2"
android:layout_alignBaseline="#+id/button"
android:layout_alignBottom="#+id/button"
android:layout_centerHorizontal="true" />
<Button
android:text="Reset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/button2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/button3" />
<Button
android:text="Save Lap"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:id="#+id/button4"
android:layout_below="#+id/button"
android:layout_centerHorizontal="true" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/button4"
android:layout_centerHorizontal="true"
android:layout_marginTop="12dp"
android:id="#+id/listview1"/>
<TextView
android:id="#+id/textViewBatteryStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/button2"
android:layout_below="#+id/textView"
android:text="Current Battery Status"
android:textAppearance="?android:attr/textAppearanceLarge" />
Guidance in editing code will be helpful.
If you want to catch the Charger Connected and Disconnected events, then you should not use the BATTERY_STATUS_CHARGING and BATTERY_STATUS_DISCHARGING at the first place.You should listen for -
<receiver android:name=".YourPowerConnectionReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
</intent-filter>
</receiver>
Thus you will get the broadcast only during charger connected and disconnected state.
Look here : https://developer.android.com/reference/android/content/Intent.html#ACTION_BATTERY_CHANGED

stopwatch - how to?

I have been trying to build a stopwatch in my app which starts counting on a start button click.I want it to count from seconds then minutes, then Hour but the problem is I can't count Hour but I can count milliseconds which I do not want. is that possible on start button click the app takes the current system time and on stop click just calculate and print the interval between starts and stop clicks?
Here is my activity class
package com.example.rimapps.stopwatch;
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;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
TextView textView;
Button but1,but2;
long MillisecondTIme,StarTime,TimeBuff,UpdateTime=0L;
Handler handler;
int MilliSeconds,Seconds,Minutes,Hour;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=(TextView)findViewById(R.id.textView);
but1=(Button)findViewById(R.id.buttonstart);
but2=(Button)findViewById(R.id.buttonstop);
handler = new Handler();
but1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Date d=new Date();
//SimpleDateFormat sdf=new SimpleDateFormat("hh:mm a");
//String currentDateTimeString=sdf.format(d);
//textView.setText(currentDateTimeString);
StarTime=SystemClock.uptimeMillis();
handler.postDelayed(runnable,0);
//reset.setEnabled(false);
}
});
but2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MillisecondTIme=0L;
TimeBuff = 0L ;
UpdateTime = 0L ;
Seconds = 0 ;
Minutes = 0 ;
MilliSeconds = 0 ;
textView.setText("00:00:00");
}
});
}
public Runnable runnable=new Runnable() {
#Override
public void run() {
MillisecondTIme=SystemClock.uptimeMillis()-StarTime;
UpdateTime=TimeBuff+MillisecondTIme;
Seconds=(int)(UpdateTime/1000);
Minutes=Seconds/60;
Seconds=Seconds%60;
MilliSeconds=(int)(UpdateTime%1000);
textView.setText("" + Minutes + ":"
+ String.format("%02d", Seconds) + ":"
+ String.format("%03d", MilliSeconds));
handler.postDelayed(this,0);
}
};
}
here is my xml layout
<?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"
tools:context="com.example.rimapps.stopwatch.MainActivity">
<TextView
android:text="00:00:00"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:textSize="50dp"
android:textStyle="bold"
android:textColor="#009688"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="33dp" />
<Button
android:text="Start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="47dp"
android:id="#+id/buttonstart"
android:layout_below="#+id/textView"
android:layout_alignLeft="#+id/textView"
android:layout_alignStart="#+id/textView" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<Button
android:text="Stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/buttonstop"
android:layout_marginRight="89dp"
android:layout_marginEnd="89dp"
android:layout_marginTop="140dp"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
</RelativeLayout>
While I was learning a book I also had a stopwatch coding problem this is a sample of the code I use.
final Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
int hours=seconds/3600;
int minutes=(seconds%3600)/60;
int secs=seconds%60;
String time = String.format("%d:%02d:%02d",hours,minutes,secs);
timeView.setText(time);
if(running)
{
seconds++;
}
handler.postDelayed(this,1000);
}
});
also understand Handler class, handler will always run the code immediately(like every second forever) so you gotta add a boolean value that know if it is running then set it to your button like if start button is click you got to set the running to true. Handler will always run forever like the famous loop() method of arduino(it is running forever).
Use sendMessage that does have a clearMessage instead of postRunnable
This time I'll write for you (most for fix convention with camel case):
The stop function is at the second button action listener
package com.example.rimapps.stopwatch;
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;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
TextView textView;
Button but1,but2;
long millisecondTIme,starTime,timeBuff,updateTime=0L;
Handler handler;
int milliSeconds,seconds,minutes,hour;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=(TextView)findViewById(R.id.textView);
but1=(Button)findViewById(R.id.buttonstart);
but2=(Button)findViewById(R.id.buttonstop);
handler = new Handler() {
public void handleMessage(Message what) {
millisecondTIme=SystemClock.uptimeMillis()-starTime;
updateTime=timeBuff+millisecondTIme;
seconds=(int)(UpdateTime/1000);
minutes=Seconds/60;
seconds=Seconds%60;
milliSeconds=(int)(updateTime%1000);
textView.setText("" + minutes + ":"
+ String.format("%02d", seconds) + ":"
+ String.format("%03d", milliSeconds));
handler.sendEmptyMessageDelayed(0, 1000); //repost in a loop
}
}
but1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
starTime=SystemClock.uptimeMillis();
handler.sendEmptyMessage(0); //Here send message with id 0
}
});
but2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
millisecondTIme=0L;
timeBuff = 0L ;
updateTime = 0L ;
seconds = 0 ;
minutes = 0 ;
milliSeconds = 0 ;
textView.setText("00:00:00");
handler.removeMessages(0); //Here clear all messages with same id
}
});
}
}

How to display number pickers in pop up window

how to display the number pickers in the pop up window...
I tried making the number pickers in different activity..but i want it to be displayed in a pop up window on a button click.
package com.example.uc232142.picker;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.NumberPicker;
import android.widget.PopupWindow;
import static android.app.PendingIntent.getActivity;
public class MainActivity extends AppCompatActivity {
NumberPicker numberpicker,numberPicker1,numberPicker2;
final String month[] = {"jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"};
final String sub[] ={"Airlaw","criminal","Income tax","Direct tax","Customs", "Defence & Security Forces" , "Disinvestment" , "Education" , "Election" ,
"Electricity & Energy" , "Environment, Wildlife & Animal", "Exchange Control & FDI " , "Excise"};
// TextView textview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.picker);
// final int popup=0x7f04002b;
numberpicker = (NumberPicker) findViewById(R.id.numberPicker1);
numberPicker1 = (NumberPicker) findViewById(R.id.numberPicker2);
numberPicker2 = (NumberPicker) findViewById(R.id.numberPicker3);
final ImageButton button = (ImageButton) findViewById(R.id.imageButton);
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
final View popupView = layoutInflater.inflate(R.layout.picker, null);
final PopupWindow popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
button.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
popupWindow.showAsDropDown(button, 10, -10);
show();
}
});
}
public void show(){
numberpicker = (NumberPicker) findViewById(R.id.numberPicker1);
numberPicker1 = (NumberPicker) findViewById(R.id.numberPicker2);
numberPicker2 = (NumberPicker) findViewById(R.id.numberPicker3);
numberpicker.setMinValue(1950);
numberpicker.setMaxValue(2018);
numberpicker.setValue(2017);
numberPicker1.setMinValue(0);
numberPicker1.setMaxValue(month.length - 1);
numberPicker1.setDisplayedValues(month);
numberPicker1.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
numberPicker2.setMinValue(0);
numberPicker2.setMaxValue(sub.length - 1);
numberPicker2.setDisplayedValues(sub);
numberPicker2.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
}
}
I've tried using AlertDialog instead of PopupWindow. It's working fine on my side, give it a try if it's what you are looking for.
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
public class MainActivity extends AppCompatActivity {
final String month[] = {"jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"};
final String sub[] ={"Airlaw","criminal","Income tax","Direct tax","Customs", "Defence & Security Forces" , "Disinvestment" , "Education" , "Election" ,
"Electricity & Energy" , "Environment, Wildlife & Animal", "Exchange Control & FDI " , "Excise"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageButton button = (ImageButton) findViewById(R.id.imageButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openDialog();
}
});
}
/**
* This will construct An {#link AlertDialog} with some custom views.
*/
private void openDialog() {
//Inflating a LinearLayout dynamically to add TextInputLayout
//This will be added in AlertDialog
final LinearLayout linearLayout = (LinearLayout) getLayoutInflater().inflate(R.layout.view_number_dialog, null);
NumberPicker numberpicker = (NumberPicker) linearLayout.findViewById(R.id.numberPicker1);
NumberPicker numberPicker1 = (NumberPicker) linearLayout.findViewById(R.id.numberPicker2);
NumberPicker numberPicker2 = (NumberPicker) linearLayout.findViewById(R.id.numberPicker3);
numberpicker.setMinValue(1950);
numberpicker.setMaxValue(2018);
numberpicker.setValue(2017);
numberPicker1.setMinValue(0);
numberPicker1.setMaxValue(month.length - 1);
numberPicker1.setDisplayedValues(month);
numberPicker1.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
numberPicker2.setMinValue(0);
numberPicker2.setMaxValue(sub.length - 1);
numberPicker2.setDisplayedValues(sub);
numberPicker2.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
//Finally building an AlertDialog
final AlertDialog builder = new AlertDialog.Builder(this)
.setPositiveButton("Submit", null)
.setNegativeButton("Cancel", null)
.setView(linearLayout)
.setCancelable(false)
.create();
builder.show();
//Setting up OnClickListener on positive button of AlertDialog
builder.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Code on submit
}
});
}
}
view_number_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="260dp"
android:orientation="horizontal"
android:padding="14dp">
<NumberPicker
android:id="#+id/numberPicker1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<NumberPicker
android:id="#+id/numberPicker2"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginLeft="14dp"
android:layout_marginRight="14dp"
android:layout_weight="1" />
<NumberPicker
android:id="#+id/numberPicker3"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>
It'll output as following...

Android TImer: Add a timer

I've been experimenting with Eclipse a bit...
and I almost finished a timer :)
Although, I can't get the Reset button working...
Res/Layout/main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:background="#000000"
android:layout_height="match_parent" >
<TextView
android:id="#+id/timerValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/pauseButton"
android:layout_centerHorizontal="true"
android:layout_marginBottom="37dp"
android:textSize="40sp"
android:textColor="#ffffff"
android:text="#string/timerVal" />
<Button
android:id="#+id/startButton"
android:layout_width="90dp"
android:layout_height="45dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="38dp"
android:text="#string/startButtonLabel" />
<Button
android:id="#+id/pauseButton"
android:layout_width="90dp"
android:layout_height="45dp"
android:layout_alignBaseline="#+id/startButton"
android:layout_alignBottom="#+id/startButton"
android:layout_alignParentRight="true"
android:layout_marginRight="38dp"
android:text="#string/pauseButtonLabel" />
<Button
android:id="#+id/resetButton"
android:layout_width="90dp"
android:layout_height="45dp"
android:layout_above="#+id/timerValue"
android:layout_centerHorizontal="true"
android:layout_marginBottom="31dp"
android:text="#string/resetButtonLabel" />
</RelativeLayout>
[/code]
[B]res/values/strings.xml[/B]
[code]<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Timer</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="timerVal">00:00:00</string>
<string name="pauseButtonLabel">Pause</string>
<string name="startButtonLabel">Start</string>
<string name="resetButtonLabel">Reset</string>
</resources>
MainActivity.java
package com.MertensMobile.Timer;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private Button startButton;
private Button pauseButton;
private TextView timerValue;
private long startTime = 0L;
private Handler customHandler = new Handler();
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
timerValue = (TextView) findViewById(R.id.timerValue);
startButton = (Button) findViewById(R.id.startButton);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
}
});
pauseButton = (Button) findViewById(R.id.pauseButton);
pauseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
timeSwapBuff += timeInMilliseconds;
customHandler.removeCallbacks(updateTimerThread);
}
});
resetButton = (Button) findViewById(R.id.resetButton);
resetButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
timeSwapBuff += timeInMilliseconds;
customHandler.removeCallbacks(updateTimerThread);
}
});
}
private Runnable updateTimerThread = new Runnable() {
public void run() {
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
int secs = (int) (updatedTime / 1000);
int mins = secs / 60;
secs = secs % 60;
int milliseconds = (int) (updatedTime % 1000);
timerValue.setText("" + mins + ":"
+ String.format("%02d", secs) + ":"
+ String.format("%03d", milliseconds));
customHandler.postDelayed(this, 0);
}
public void Reset() {
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
};
}
I'm very close, (at least I think I am) :P
I got it working on my cellphone, just the reset isn't working yet :o
I think you can use this to reset the timer.
TimerValue.cancel();
TextView digital_display = (TextView) findViewById(R.id.digital_display);
digital_display.setText("00:00.0");

Timer in three EditTexts not working properly

I have made a Timer Application in android.In application there are three (uneditable)EditText and a Button.When i press Button first time the timer in 1st EditText will start ,when i press it 2nd time the timer in 1st EditText will stop and at the same time the timer in 2nd EditText will be start,when i again press button same thing will be happened with 3rd EdtiText.NOw this code is working properly but when i press back button and again start it,its stopped working in 3rd EditText.The problem is sometimes the timer in 3rd EditText is not working(not displayed)..my code is as below:
mainActivity.java
package com.example.timerdemo2;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;
import org.w3c.dom.Text;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
EditText et1,et2,et3;
TextView tv;
public int i=0;
long starttime = 0;
long lasttime,lasttime1;
final Handler handler = new Handler();
Handler h2 = new Handler();
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
Runnable run = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
long millis = System.currentTimeMillis() - starttime;
int seconds = (int) (millis / 1000);
int minutes = (seconds%3600)/60;
int hours = seconds / 3600;
seconds = seconds % 60;
et1.setText(String.format("%02d:%02d:%02d",hours, minutes, seconds));
// et2.setText(String.format("%02d:%02d:%02d",hours, minutes, seconds));
// et3.setText(String.format("%02d:%02d:%02d",hours, minutes, seconds));
h2.postDelayed(this, 500);
}
};
class firstTask extends TimerTask {
public void run() {
handler.sendEmptyMessage(0);
}
};
class secondTask extends TimerTask{
#Override
public void run() {
// TODO Auto-generated method stub
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
long millis = System.currentTimeMillis() - starttime;
int seconds = (int)(millis/1000);
int hours =seconds/3600;
int minutes = (seconds % 3600)/60;
seconds = seconds % 60;
et2.setText(String.format("%02d:%02d:%02d", hours,minutes,seconds));
}
});
}
}
class thirdTask extends TimerTask{
#Override
public void run() {
// TODO Auto-generated method stub
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
long millis = System.currentTimeMillis() - starttime;
int seconds = (int)(millis/1000);
int hours =seconds/3600;
int minutes = (seconds % 3600)/60;
seconds = seconds % 60;
et3.setText(String.format("%02d:%02d:%02d", hours,minutes,seconds));
h2.postDelayed(this, 500);
}
});
}
}
Timer timer = new Timer();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle bundle = this.getIntent().getExtras();
String title = bundle.getString("title");
tv = (TextView)findViewById(R.id.projectTitle);
tv.setText(title);
et1= (EditText)findViewById(R.id.timeEdit1);
et2= (EditText)findViewById(R.id.timeEdit2);
et3= (EditText)findViewById(R.id.timeEdit3);
Button b = (Button)findViewById(R.id.btn);
b.setText("Start");
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Button b =(Button)v;
if(b.getText().equals("Stop")){
timer.cancel();
timer.purge();
h2.removeCallbacks(run);
Intent intent =new Intent(MainActivity.this,Timedetails.class);
Bundle bundle =new Bundle();
//Procedure for Showing time stamps on another page
String a = et1.getText().toString();
String b1 = et2.getText().toString();
String c = et3.getText().toString();
String t = tv.getText().toString();
intent.putExtra("titl1",t);
startActivity(intent);
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
try{
bundle.putString("t1", a);
bundle.putString("t2", b1);
bundle.putString("t3", c);
Date date1 = (Date) format.parse(a);
Date date2 = (Date) format.parse(b1);
Date date3 = (Date) format.parse(c);
//time difference in milliseconds
long timeDiff = date2.getTime() - date1.getTime();
long timeDiff2 = date3.getTime() - date2.getTime();
//new date object with time difference
Date diffDate = new Date(timeDiff);
Date diffDate2 = new Date(timeDiff2);
long timeDiffSecs = timeDiff/1000;
String timeDiffString = timeDiffSecs/3600+":"+
(timeDiffSecs%3600)/60+":"+
(timeDiffSecs%3600)%60;
long timeDiffSecs1 = timeDiff2/1000;
String timeDiffString1 = timeDiffSecs1/3600+":"+
(timeDiffSecs1%3600)/60+":"+
(timeDiffSecs1%3600)%60;
//formatted date string
// String timeDiffString = format.format(diffDate);
//System.out.println("Time Diff = "+ timeDiffString );
bundle.putString("t1", a);
bundle.putString("t2", b1);
bundle.putString("t3", c);
bundle.putString("dif1", timeDiffString);
bundle.putString("dif2", timeDiffString1);
}
catch(Exception e){
e.printStackTrace();
}
intent.putExtras(bundle);
startActivity(intent);
b.setText("Next");
}
else if(b.getText().equals("Lap1"))
{
timer.schedule(new secondTask(),0, 500);
h2.removeCallbacks(run);
b.setText("lap2");
}
else if(b.getText().equals("lap2")){
timer.schedule(new thirdTask(), 0,500);
h2.removeCallbacks(run);
timer.cancel();
timer.purge();
b.setText("Stop");
}
else {
starttime = System.currentTimeMillis();
timer = new Timer();
timer.schedule(new firstTask(), 0,500);
// timer.schedule(new secondTask(), 0,500);
//timer.schedule(new thirdTask(), 0,500);
h2.postDelayed(run, 0);
b.setText("Lap1");
//long lastdown = System.currentTimeMillis();
}
}
});
}
}
MainActivity.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/abs5"
android:orientation="vertical" >
<TextView
android:id="#+id/projectTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|center"
android:layout_marginTop="5dp"
android:text="Project Title"
android:textColor="#CCCCCC"
android:textSize= "40dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:text="Timing Point1"
android:textSize="20dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#CCCCCC" />
<EditText
android:id="#+id/timeEdit1"
android:layout_width="172dp"
android:layout_height="30dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:background="#FFFFFF"
android:editable="false"
android:filterTouchesWhenObscured="false"
android:focusable="false" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Timing Point2"
android:textColor="#CCCCCC"
android:textSize="20dp"
android:layout_marginTop="10dp"
android:layout_marginLeft="5dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/timeEdit2"
android:layout_width="172dp"
android:layout_height="30dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:focusable="false"
android:filterTouchesWhenObscured="false"
android:background="#FFFFFF"
android:editable="false" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:text="Timing Point3"
android:textColor="#CCCCCC"
android:textSize="20dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/timeEdit3"
android:layout_width="172dp"
android:layout_height="30dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:background="#FFFFFF"
android:editable="false" >
<requestFocus />
</EditText>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginBottom="20dp"
android:orientation="horizontal" >
<Button
android:id="#+id/btn"
android:layout_width="129dp"
android:layout_height="64dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="110dp"
android:layout_marginTop="10dp"
android:background="#drawable/aqa"
android:textColor="#FFFFFF"
android:textSize="30dp" />
</LinearLayout>
</LinearLayout>
Please help me for this as fast ...really thanking you.....hav a gud tym
Look at this code in your lap2 handler:
timer.schedule(new thirdTask(), 0,500);
h2.removeCallbacks(run);
timer.cancel();
timer.purge();
b.setText("Stop");
You schedule a task and cancel the timer immediately afterwards.
I would suggest that you get rid of the Timer and just use the Handler.postDelayed() method, as you have done already for the time updates and to start the update of the first field:
h2.postDelayed(run, 0);
Use the same method to start the updates for second and third fields. You don't need the Timer and TimerTask instances at all.
Also, why do you need two handlers (handler, and h2)?

Categories

Resources