after fixing the null pointer exception of a previous question, (Not sure if posting a different question for the same code is okay, do let me know if it is not) I've come across a new problem. When I try passing the date variable from this first activity to another, it is always empty. I've also tried just setting a public getter or the variable and it is also empty. However, using a toast to check within the class shows that the variable does indeed contain the date. I am trying to pass the date class to be added into a database by the other classes in the application package. Any help would be much appreciated.
CalendarActivity.java
package com.example.zaphk.studenthelperapplication3.calendar;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.CalendarView;
import android.widget.Toast;
import com.example.zaphk.studenthelperapplication3.R;
public class CalendarActivity extends AppCompatActivity {
public static final String EXTRA_TEXT = "com.example.zaphk.studenthelperapplication3";
private static final String TAG = "CalendarActivity";
private CalendarView mCalendarView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calendar_layout);
mCalendarView = (CalendarView) findViewById(R.id.calendarView);
mCalendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(CalendarView CalendarView, int year, int month, int dayOfMonth) {
String date = year + "/" + month + "/"+ dayOfMonth ;
Log.d(TAG, "onSelectedDayChange: yyyy/mm/dd:" + date);
Intent intent = new Intent(CalendarActivity.this,CalendarEvent.class);
intent.putExtra(Intent.EXTRA_TEXT,date);
startActivity(intent);
Toast.makeText(CalendarActivity.this,date,Toast.LENGTH_SHORT).show();
}
});
}
}
The class I am trying to receive it from : CalendarEvent.java
package com.example.zaphk.studenthelperapplication3.calendar;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import com.example.zaphk.studenthelperapplication3.calendar.database.Calendar;
import com.example.zaphk.studenthelperapplication3.calendar.database.CalendarAdapter;
import com.example.zaphk.studenthelperapplication3.calendar.database.Calendar_DbHelper;
import com.example.zaphk.studenthelperapplication3.utils.MyDividerItemDecoration;
import com.example.zaphk.studenthelperapplication3.utils.RecyclerTouchListener;
import com.example.zaphk.studenthelperapplication3.R;
public class CalendarEvent extends AppCompatActivity {
private CalendarAdapter mAdapter;
private List<Calendar> notesList = new ArrayList<>();
private CoordinatorLayout coordinatorLayout;
private RecyclerView recyclerView;
private TextView noNotesView;
Intent intent = getIntent();
public String date;
private Calendar_DbHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
intent = getIntent();
date = intent.getStringExtra(CalendarActivity.EXTRA_TEXT);
setContentView(R.layout.activity_notes);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
coordinatorLayout = findViewById(R.id.coordinator_layout);
recyclerView = findViewById(R.id.recycler_view);
noNotesView = findViewById(R.id.empty_notes_view);
db = new Calendar_DbHelper(this);
notesList.addAll(db.getAllNotes());
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showNoteDialog(false, null, -1);
}
});
mAdapter = new CalendarAdapter(this, notesList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new MyDividerItemDecoration(this, LinearLayoutManager.VERTICAL, 16));
recyclerView.setAdapter(mAdapter);
toggleEmptyNotes();
/**
* On long press on RecyclerView item, open alert dialog
* with options to choose
* Edit and Delete
* */
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(this,
recyclerView, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, final int position) {
}
#Override
public void onLongClick(View view, int position) {
showActionsDialog(position);
}
}));
}
/**
* Inserting new note in db
* and refreshing the list
*/
private void createNote(String note) {
// inserting note in db and getting
// newly inserted note id
long id = db.insertNote(note);
// get the newly inserted note from db
Calendar n = db.getNote(id);
if (n != null) {
// adding new note to array list at 0 position
notesList.add(0, n);
// refreshing the list
mAdapter.notifyDataSetChanged();
toggleEmptyNotes();
}
}
/**
* Updating note in db and updating
* item in the list by its position
*/
private void updateNote(String note, int position) {
Calendar n = notesList.get(position);
// updating note text
n.setNote(note);
// updating note in db
db.updateNote(n);
// refreshing the list
notesList.set(position, n);
mAdapter.notifyItemChanged(position);
toggleEmptyNotes();
}
/**
* Deleting note from SQLite and removing the
* item from the list by its position
*/
private void deleteNote(int position) {
// deleting the note from db
db.deleteNote(notesList.get(position));
// removing the note from the list
notesList.remove(position);
mAdapter.notifyItemRemoved(position);
toggleEmptyNotes();
}
/**
* Opens dialog with Edit - Delete options
* Edit - 0
* Delete - 0
*/
private void showActionsDialog(final int position) {
CharSequence colors[] = new CharSequence[]{"Edit", "Delete"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose option");
builder.setItems(colors, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
showNoteDialog(true, notesList.get(position), position);
} else {
deleteNote(position);
}
}
});
builder.show();
}
/**
* Shows alert dialog with EditText options to enter / edit
* a note.
* when shouldUpdate=true, it automatically displays old note and changes the
* button text to UPDATE
*/
private void showNoteDialog(final boolean shouldUpdate, final Calendar note, final int position) {
LayoutInflater layoutInflaterAndroid = LayoutInflater.from(getApplicationContext());
View view = layoutInflaterAndroid.inflate(R.layout.note_dialog, null);
AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder(CalendarEvent.this);
alertDialogBuilderUserInput.setView(view);
final EditText inputNote = view.findViewById(R.id.note);
TextView dialogTitle = view.findViewById(R.id.dialog_title);
dialogTitle.setText(!shouldUpdate ? getString(R.string.lbl_new_note_title) : getString(R.string.lbl_edit_note_title));
if (shouldUpdate && note != null) {
inputNote.setText(note.getNote());
}
alertDialogBuilderUserInput
.setCancelable(false)
.setPositiveButton(shouldUpdate ? "update" : "save", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogBox, int id) {
}
})
.setNegativeButton("cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogBox, int id) {
dialogBox.cancel();
}
});
final AlertDialog alertDialog = alertDialogBuilderUserInput.create();
alertDialog.show();
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Show toast message when no text is entered
if (TextUtils.isEmpty(inputNote.getText().toString())) {
Toast.makeText(CalendarEvent.this, "Enter note!", Toast.LENGTH_SHORT).show();
return;
} else {
alertDialog.dismiss();
}
// check if user updating note
if (shouldUpdate && note != null) {
// update note by it's id
updateNote(inputNote.getText().toString(), position);
} else {
// create new note
createNote(inputNote.getText().toString());
}
}
});
}
/**
* Toggling list and empty notes view
*/
private void toggleEmptyNotes() {
// you can check notesList.size() > 0
if (db.getNotesCount() > 0) {
noNotesView.setVisibility(View.GONE);
} else {
noNotesView.setVisibility(View.VISIBLE);
}
}
public String getDate(){
return date;
}
}
You are using wrong key while passing data between activity.
Replace below line,
intent.putExtra(Intent.EXTRA_TEXT,date);
With this one,
intent.putExtra(CalendarActivity.EXTRA_TEXT,date);
You use the key of Intent.EXTRA_TEXT.
intent.putExtra(Intent.EXTRA_TEXT,date)
But you use the other key to receive. It's not the same key.
intent.getStringExtra(CalendarActivity.EXTRA_TEXT);
As per I know (Not pretty sure)
Intent.EXTRA_TEXT
is used for implicit intents.
For explicit (i.e.Activity to Activity)
Do as below
Intent intent = new Intent(CalendarActivity.this,CalendarEvent.class);
intent.putExtra("DATE",date);
startActivity(intent);
To receive
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_notes);
intent = getIntent();
String date = intent.getStringExtra("DATE");
}
Where "DATE" is String KEY.
I would say that CalendarActivity.EXTRA_TEXT is probably empty because you have not imported that class in to CalendarEvent.java
import com.example.zaphk.studenthelperapplication3.calendar.CalendarActivity; in CalendarEvent.java
and as other people have said the put and get on the Intent need to be the the same String value.
[Android newbie] Help required in adding 4 math operations as options to a radion button.
Also I need to perform respective options on selecting radio button option.
package com.sivaneshsg.wallet;
import android.support.annotation.IdRes;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class MainActivity extends AppCompatActivity {
int cashamount = 0;
int cardamount = 0;
int walletamount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText et = (EditText) findViewById(R.id.inputamount);
final RadioButton card1 = (RadioButton) findViewById(R.id.card1);
final RadioButton cash1 = (RadioButton) findViewById(R.id.cash1);
final RadioButton card2 = (RadioButton) findViewById(R.id.card2);
final RadioButton cash2 = (RadioButton) findViewById(R.id.cash2);
final RadioGroup rg =(RadioGroup) findViewById(R.id.rgroup);
final TextView t1 = (TextView) findViewById(R.id.amountcard);
final TextView t2 = (TextView) findViewById(R.id.amountcash);
final TextView t3 = (TextView) findViewById(R.id.amountwallet);
Button but = (Button) findViewById(R.id.button);
final int amount = Integer.parseInt(et.getText().toString());
cash1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
cash2.setChecked(false);
card1.setChecked(false);
card2.setChecked(false);
cashamount = cashamount + amount;
}
});
card1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
cash2.setChecked(false);
cash1.setChecked(false);
card2.setChecked(false);
cardamount=cardamount+amount;
}
});
cash2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
cash1.setChecked(false);
card1.setChecked(false);
card2.setChecked(false);
cashamount = cashamount - amount;
}
});
card2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
cash2.setChecked(false);
cash1.setChecked(false);
card2.setChecked(false);
cardamount=cardamount-amount;
}
});
but.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
t1.setText("Amount in Card : RS. " + cardamount);
t2.setText("Amount in Cash : Rs. " + cashamount);
walletamount = cardamount + cashamount;
t3.setText("Total Amount in Wallet : RS. " + walletamount);
}
});
}
}
your amount variable taking value at onCreate() method which is initially 0
I am trying to use btn2 to switch my page from MainActivity to CalcPage.class.
Cant seem to figure out what I am doing wrong.
I have error lines underneath btn2, OnClickListener, Override, and View v
Here is my MainActivity.java
package edu.khershockolivetcollege.ballistic_calculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.content.Intent;
import java.text.DecimalFormat;
public class MainActivity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
Button btn1 = (Button)findViewById(R.id.calculate);
Button btn2 = (Button)findViewById(R.id.calculate);
final EditText et1 = (EditText)findViewById(R.id.muzzleText);
final EditText et2 = (EditText)findViewById(R.id.rangeText);
final TextView time = (TextView)findViewById(R.id.timeAnswer);
final TextView bulletdrop = (TextView)findViewById(R.id.dropAnswer);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
DecimalFormat f = new DecimalFormat("##.00");
double x = new Integer(et1.getText().toString());
double y = new Integer(et2.getText().toString());
double timetotarget = y / x;
double grav = 9.81;
double timesquared = timetotarget * timetotarget;
double drop = grav * timesquared;
time.setText(" " + f.format(timetotarget) + " seconds");
bulletdrop.setText(" " + f.format(drop) + " meters");
}
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(context, CalcPage.class);
startActivity(i);
}
});
}
}
It seems that you are setting your btn2 OnClickListener inside your btn1 OnClickListener. If you do it outside and close all your curly brackets it should work.
Like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
Button btn1 = (Button)findViewById(R.id.calculate);
Button btn2 = (Button)findViewById(R.id.calculate);
final EditText et1 = (EditText)findViewById(R.id.muzzleText);
final EditText et2 = (EditText)findViewById(R.id.rangeText);
final TextView time = (TextView)findViewById(R.id.timeAnswer);
final TextView bulletdrop = (TextView)findViewById(R.id.dropAnswer);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
DecimalFormat f = new DecimalFormat("##.00");
double x = new Integer(et1.getText().toString());
double y = new Integer(et2.getText().toString());
double timetotarget = y / x;
double grav = 9.81;
double timesquared = timetotarget * timetotarget;
double drop = grav * timesquared;
time.setText(" " + f.format(timetotarget) + " seconds");
bulletdrop.setText(" " + f.format(drop) + " meters");
}
});
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick (View v){
Intent i = new Intent(context, CalcPage.class);
startActivity(i);
}
});
}
I'll do my best to explain my issue without a video
I have a login activity where upon successful login, the EditText and Button fields fade out and a "logging in" TextView fades in (using Facebook Shimmer). This works great!! However, upon successfully login we are greeted by a blank activity (still fine). Now, I overwrote the back button so that when the back button is pressed, the user is forced to login again. My problem arises with the user hits the login button at this time. The Edit Text and Button elements fade out nicely but the "logging in" TextView never fades in.
Below are some picture examples. I will also post the source code for LoginActivity.class and if you want to download the project it is available at: git#github.com:fbgrecojr/Android-Application-Login-Activity-Template.git
If you download the project, username: testuser and password: testpass will work.
Images:
Initial Login (working)
Login Attempt after pressing the back button and then logging in again (which I overwrote to restart the intent)
LoginActivity.class
package com.projects.fbgrecojr.logintemplate.UI;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Handler;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.facebook.shimmer.ShimmerFrameLayout;
import com.projects.fbgrecojr.logintemplate.HTTPManager.HttpManager;
import com.projects.fbgrecojr.logintemplate.HTTPManager.RequestPackage;
import com.projects.fbgrecojr.logintemplate.Parser.JSONParser;
import com.projects.fbgrecojr.logintemplate.R;
import com.projects.fbgrecojr.logintemplate.Session.Session;
import com.projects.fbgrecojr.logintemplate.Structures.User;
import com.projects.fbgrecojr.logintemplate.Utility.UTILITY;
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*/
public class LoginActivity extends AppCompatActivity implements View.OnClickListener{
private EditText userName, password;
private Button login;
private RelativeLayout image;
private LinearLayout button, belowPic;
private Animation fadeInImage, fadeInButton, bottomUp, fadeOut;
private TextInputLayout inputLayoutName,inputLayoutPassword;
private ViewGroup hiddenPanel;
private ShimmerFrameLayout container, loggingIn;
private static final int SECOND = 1000;
private static final int HALF_SECOND = 500;
private static final int QUARTER_SECOND = 250;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//INITIALIZE ANIMATION ITEMS
fadeInImage = new AlphaAnimation(0, 1);
fadeInButton = new AlphaAnimation(0, 1);
fadeOut = new AlphaAnimation(1.0f,0.0f);
bottomUp = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.bottom_up_animation);
fadeInImage.setInterpolator(new AccelerateInterpolator()); //and this
bottomUp.setInterpolator(new DecelerateInterpolator());
//GET UI ELEMENTS
userName = (EditText) findViewById(R.id.userName);
password = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.login);
image = (RelativeLayout) findViewById(R.id.image);
button = (LinearLayout) findViewById(R.id.button);
container = (ShimmerFrameLayout) findViewById(R.id.shimmer);
belowPic = (LinearLayout) findViewById(R.id.below_picture);
loggingIn = (com.facebook.shimmer.ShimmerFrameLayout) findViewById(R.id.login_shimmer);
hiddenPanel = (ViewGroup)findViewById(R.id.input);
inputLayoutName = (TextInputLayout) findViewById(R.id.text_input_username);
inputLayoutPassword = (TextInputLayout) findViewById(R.id.text_input_password);
//SET UI PROPERTIES
loggingIn.setVisibility(View.INVISIBLE);
userName.setCursorVisible(false);
password.setCursorVisible(false);
password.setHint("Password");
userName.setHint("Username");
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
userName.setCursorVisible(true);
password.setCursorVisible(true);
userName.requestFocus();
}
}, LoginActivity.SECOND * 3);
//ANIMATIONS
fadeInImage.setDuration(SECOND * 3);
fadeOut.setStartOffset(SECOND);
fadeOut.setDuration(SECOND);
image.setAnimation(fadeInImage);
fadeInButton.setStartOffset(SECOND + HALF_SECOND + QUARTER_SECOND);
fadeInButton.setDuration(SECOND * 2);
button.setAnimation(fadeInButton);
hiddenPanel.startAnimation(bottomUp);
hiddenPanel.setVisibility(View.VISIBLE);
container.setDuration(SECOND * 2 + QUARTER_SECOND);
container.setRepeatDelay(QUARTER_SECOND);
container.setIntensity((float) 0.15);
container.setBaseAlpha((float) 0.75);
container.setFadingEdgeLength(3);
container.setDropoff((float) 0.40);
container.startShimmerAnimation();
//ON CLICK LISTENERS
login.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.login:
if(getUserName().getText().toString().equals("") || getUserName().getText().toString().equals(" ")) {
inputLayoutName.setError("enter username");
}else if(getPassword().getText().toString().equals("") || getPassword().getText().toString().equals(" ")){
inputLayoutPassword.setError("enter password");
}else{
//webservice
if (UTILITY.isOnline(getApplicationContext())) {
RequestPackage p = new RequestPackage();
p.setMethod("GET");
p.setUri(UTILITY.UBUNTU_SERVER_URL);
p.setParam("query", "user");
p.setParam("username", getUserName().getText().toString());
new WebserviceCallOne().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, p);
} else {
Toast.makeText(getApplicationContext(), "you are not connected to the internet", Toast.LENGTH_LONG).show();
}
}
break;
}
}
private void animateExit() {
//fade out annimation
belowPic.startAnimation(fadeOut);
belowPic.setVisibility(View.INVISIBLE);
fadeInImage.setStartOffset(SECOND * 2);
fadeInImage.setDuration(HALF_SECOND);
loggingIn.startAnimation(fadeInImage);
loggingIn.setVisibility(View.VISIBLE);
loggingIn.setDuration(SECOND);
loggingIn.startShimmerAnimation();
}
public EditText getPassword() {
return password;
}
public EditText getUserName() {
return userName;
}
private class WebserviceCallOne extends AsyncTask<RequestPackage, String, User> {
#Override
protected User doInBackground(RequestPackage... params) {
String content = HttpManager.getData(params[0]);
return JSONParser.parseUserFeed(content);
}
#Override
protected void onPostExecute(User s) {
Session.setCurrentUser(s);
//if null, error stacktrace will print to the log. This is expected!!
if(Session.getCurrentUser() == null){ //username was incorrect
inputLayoutName.setError("username does not exist");
}else{ //check password
if(getPassword().getText().toString().equals(s.getPassword())){ //passwords match
animateExit();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
},LoginActivity.SECOND * 4);
}else{
inputLayoutPassword.setError("password incorrect");
}
}
}
}
}
MainActivity.class
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* Take care of popping the fragment back stack or finishing the activity
* as appropriate.
*/
#Override
public void onBackPressed() {
startActivity(new Intent(this, LoginActivity.class));
}
}
You have to call animateExit(); code in onResume methord
#Override
public void onResume() {
super.onResume();
animateExit();
}
override onResume() in your Activity.
try starting your animation in onresume.
override onPause() in your Activity
try stopping your animation in onPause.
Hope this Helps :)
I got this code from a website for chronometer i want to run the chronometer when my activity starts and i want to recive the time running in seconds in a integer value like
myclock = mChronometer.get vaule (example idea);
or anyother methods that can get value from chronometer directly
import android.app.Activity;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Chronometer;
public class StopWatch extends Activity {
Chronometer mChronometer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button;
mChronometer = (Chronometer) findViewById(R.id.chronometer);
// Watch for button clicks.
button = (Button) findViewById(R.id.start);
button.setOnClickListener(mStartListener);
button = (Button) findViewById(R.id.stop);
button.setOnClickListener(mStopListener);
button = (Button) findViewById(R.id.reset);
button.setOnClickListener(mResetListener);
}
View.OnClickListener mStartListener = new OnClickListener() {
public void onClick(View v) {
mChronometer.start();
}
};
View.OnClickListener mStopListener = new OnClickListener() {
public void onClick(View v) {
mChronometer.stop();
}
};
View.OnClickListener mResetListener = new OnClickListener() {
public void onClick(View v) {
mChronometer.setBase(SystemClock.elapsedRealtime());
}
};
}
Thank u all in advance for helping me
here is the link to the orginal site http://www.edumobile.org/android/android-development/stop-watch-example/