I want to have one date and two time pickers in one dialog and I have done it, but the second time (Time to) is getting the same values as (time from). I have put some 'if cases' to try to fix it but didn't help. I get ("2016/10/27 5:41 0:00) even if I pick the time for the two "timepickers" I don't get the value for the second one or it duplicates the first one.
here is my code:
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.Calendar;
public class AdminActivity extends AppCompatActivity implements View.OnClickListener, TimePickerDialog.OnTimeSetListener, DatePickerDialog.OnDateSetListener {
//firebase auth object
private FirebaseAuth firebaseAuth;
//view objects
private TextView textViewUserEmailadmin;
private Button buttonLogout;
private DatabaseReference databaseReference;
private EditText editTextinfo;
private TextView Textpass;
private Button buttonSave;
int day, month, year, hour, minute,hour1,minute1;
int dayFinal, monthFinal, yearFinal, hourFinal, minuteFinal,hourFinal1,minuteFinal1;
int i = 0;
Button btnDatePicker;
String a="";
String b="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin);
//initializing firebase authentication object
firebaseAuth = FirebaseAuth.getInstance();
//if the user is not logged in
//that means current user will return null
if (firebaseAuth.getCurrentUser() == null) {
//closing this activity
finish();
//starting login activity
startActivity(new Intent(this, LoginActivity.class));
}
databaseReference = FirebaseDatabase.getInstance().getReference();
editTextinfo = (EditText) findViewById(R.id.editText3);
buttonSave = (Button) findViewById(R.id.buttonSave);
//getting current user
FirebaseUser user = firebaseAuth.getCurrentUser();
//initializing views
textViewUserEmailadmin = (TextView) findViewById(R.id.textViewUserEmailAdmin);
buttonLogout = (Button) findViewById(R.id.buttonLogout);
//displaying logged in user name
textViewUserEmailadmin.setText("Welcome admin " + user.getEmail());
//adding listener to button
buttonLogout.setOnClickListener(this);
buttonSave.setOnClickListener(this);
btnDatePicker = (Button) findViewById(R.id.btn_date);
// btnTimeFrom = (Button) findViewById(R.id.btn_time_from);
// btnTimeTo = (Button) findViewById(R.id.btn_time_to);
Textpass = (TextView) findViewById(R.id.Textviewpass);
btnDatePicker.setOnClickListener(this);
}
private void saveUserInformation() {
String info = editTextinfo.getText().toString().trim();
String pass = Textpass.getText().toString().trim();
i++;
UserInformation UserInformation = new UserInformation(info, pass);
// FirebaseUser user = firebaseAuth.getCurrentUser();
//databaseReference.child(user.getUid()+i++).setValue(UserInformation);
databaseReference.child("tidnr" + i).setValue(UserInformation);
Toast.makeText(this, "Information saved...", Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View view) {
//if logout is pressed
if (view == buttonLogout) {
//logging out the user
firebaseAuth.signOut();
//closing activity
finish();
//starting login activity
startActivity(new Intent(this, LoginActivity.class));
}
if (view == buttonSave) {
saveUserInformation();
}
if (view == btnDatePicker) {
if(a == "" && b == "") {
Calendar c = Calendar.getInstance();
day = c.get(Calendar.DAY_OF_MONTH);
month = c.get(Calendar.MONTH);
year = c.get(Calendar.YEAR);
DatePickerDialog datePickerDialog = new DatePickerDialog(AdminActivity.this, AdminActivity.this, year, month, day);
datePickerDialog.show();
}
}
}
#Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
yearFinal=i;
monthFinal=i1 +1;
dayFinal= i2;
Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
if(a == "" && b == "") {
android.text.format.DateFormat dateFormat = new android.text.format.DateFormat();
//is24HourFormat = dateFormat.is24HourFormat(this);
TimePickerDialog timePickerDialog = new TimePickerDialog(AdminActivity.this, AdminActivity.this,
hour, minute, dateFormat.is24HourFormat(this));
timePickerDialog.show();
}
}
#Override
public void onTimeSet(TimePicker view, int i, int i1) {
hourFinal = i;
minuteFinal = i1;
String curTime = String.format("%02d",minuteFinal);
if(a == "" && b == ""){
a = yearFinal+"/"+monthFinal+"/"+dayFinal+" "+hourFinal+":"+curTime;
}
if(a != "" && b == "" ) {
Calendar c1 = Calendar.getInstance();
hour1 = c1.get(Calendar.HOUR_OF_DAY);
minute1 = c1.get(Calendar.MINUTE);
android.text.format.DateFormat dateFormat1 = new android.text.format.DateFormat();
//is24HourFormat = dateFormat.is24HourFormat(this);
TimePickerDialog timePickerDialog1 = new TimePickerDialog(AdminActivity.this, AdminActivity.this,
hour1, minute1, dateFormat1.is24HourFormat(this));
timePickerDialog1.show();
String curTime1 = String.format("%02d",minuteFinal1);
b = a+" "+hourFinal1+":"+curTime1;
a="";
Textpass.setText(b);
Toast.makeText(this, "test.", Toast.LENGTH_SHORT).show();
}
}
}
Replace this line
String curTime1 = String.format("%02d",minuteFinal1);
b = a+" "+hourFinal1+":"+curTime1;
with:
String curTime1 = String.format("%02d",minute1);
b = a+" "+hour1+":"+curTime1;
Related
Hi i am currently working on application of reminder in android and using Firebase as database. My reminder is getting set properly without any issue but when i retrieve data from Firebase, i'am getting data of particular date but don't know how to ring it on time that user had entered.
This is my code :
Miscelleneous.java
package com.example.dell.reminder;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.sql.Time;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
public class Miscelleneous extends Activity {
private static Button setting,resetting;
private EditText text;
private TextView rem1,date1,time1;
private FirebaseDatabase fdb;
private DatabaseReference db5;
private Button btn1,btn2;
private DatePickerDialog.OnDateSetListener dateSetListener;
private TimePickerDialog.OnTimeSetListener timeSetListener;
String strDate;
String timeString = "";
public static final String REM_KEY = "com.example.dell.reminder.REM_KEY";
public static final String DATE_KEY = "com.example.dell.reminder.DATE_KEY";
public static final String TIME_KEY = "com.example.dell.reminder.TIME_KEY";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.miscelleneous);
setting = (Button)findViewById(R.id.remset);
Toolbar tool = (Toolbar)findViewById(R.id.setreminder);
text = (EditText)findViewById(R.id.editText);
btn1 = (Button)findViewById(R.id.selectdate);
btn2 = (Button)findViewById(R.id.selecttime);
rem1 = (TextView)findViewById(R.id.rem1);
date1 = (TextView)findViewById(R.id.date1);
time1 = (TextView)findViewById(R.id.time11);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(Miscelleneous.this,
android.R.style.Theme_DeviceDefault_Dialog_MinWidth,dateSetListener,year,month,day);
//dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.getDatePicker().setMinDate(System.currentTimeMillis()-1000);
dialog.show();
}
});
dateSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
// Log.d("Miscelleneous","OnDateSet: mm/dd/yyyy" +month + "/" + day + "/" + year);
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, day);
month = month - 1;
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
strDate = format.format(calendar.getTime());
// date = day + "/" + month + "/" + year;
btn1.setText(strDate);
}
};
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Calendar cal = Calendar.getInstance();
int hours = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
//int second = cal.get(Calendar.SECOND);
TimePickerDialog tdialog = new TimePickerDialog(Miscelleneous.this,
android.R.style.Theme_Holo_Light_Dialog,timeSetListener,hours,minute,false);
tdialog.show();
}
});
timeSetListener = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int hours_x, int minute_x) {
//String timeString = "";
if (hours_x == 0) {
timeString = "12:"+minute_x+" "+"a.m.";
btn2.setText(timeString);
} else if (hours_x < 12) {
timeString = hours_x + ":" + minute_x +" "+ "a.m.";
btn2.setText(timeString);
} else if (hours_x == 12) {
timeString = hours_x+":"+minute_x+" "+"p.m.";
btn2.setText(timeString);
} else {
timeString = hours_x-12+ ":" + minute_x +" "+"p.m.";
btn2.setText(timeString);
}
}
};
db5 = FirebaseDatabase.getInstance().getReference().child("user1");
setting.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(text.getText().toString().isEmpty())
Toast.makeText(getApplicationContext(),"Please write something",Toast.LENGTH_LONG).show();
else if(btn1.getText().toString().isEmpty() && btn2.getText().toString().isEmpty()) {
Toast.makeText(getApplicationContext(),"Please select date and time",Toast.LENGTH_LONG).show();
}
else if(btn1.getText().toString().isEmpty()){
Toast.makeText(getApplicationContext(),"Please select date",Toast.LENGTH_LONG).show();
}
else if(btn2.getText().toString().isEmpty()){
Toast.makeText(getApplicationContext(),"Please select time",Toast.LENGTH_LONG).show();
}
else{
final HashMap<String,String> adddata = new HashMap<String, String>();
adddata.put("Reminder",text.getText().toString());
adddata.put("Date",btn1.getText().toString());
adddata.put("Time",btn2.getText().toString());
db5.child("Users Own").setValue(adddata).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(getApplicationContext(),
"Reminder has been set successfully!!!",Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(getApplicationContext(),
"Problem in reminder setting !!",Toast.LENGTH_LONG).show();
}
}
});
retrive();
/*Intent intent = new Intent(Miscelleneous.this,History.class);
intent.putExtra(REM_KEY,validate1);
intent.putExtra(DATE_KEY,validate2);
intent.putExtra(TIME_KEY,validate3);
startActivity(intent);*/
//send();
}
}
});
}
/*private void send(){
final ArrayList<String> arrayList = new ArrayList<>();
arrayList.add(validate1);
arrayList.add(validate2);
arrayList.add(validate3);
Intent i = new Intent(Miscelleneous.this,History.class);
i.putExtra(REM_KEY,arrayList);
startActivity(i);
}*/
private void retrive(){
long current_date = System.currentTimeMillis();
long current_time = System.currentTimeMillis();
// String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat sdf1 = new SimpleDateFormat("hh:mm a");
String System_Date = sdf.format(current_date);
final String System_Time = sdf1.format(current_time);
String usrdate = btn1.getText().toString().trim();
final String usrtime = btn2.getText().toString().toLowerCase().trim();
// Log.d("Miscelleneous",usrtime);
// Log.d("Miscelleneous",usrdate);
if( System_Date.equals(usrdate)){
db5.child("Users Own").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String tim="",date="",remind="";
for (DataSnapshot cdata:dataSnapshot.getChildren()) {
remind = cdata.getValue(String.class).toString();
date = cdata.getValue(String.class).toString();
tim = cdata.getValue(String.class).toString();
}
if(usrtime.equals(System_Time)){
Log.d("Miscelleneous","actual reminder");
Log.d("Miscelleneous","Date:"+remind);
Log.d("Miscelleneous","Reminder:"+date);
Log.d("Miscelleneous","Time:"+tim);
rem1.setText("Reminder : "+remind);
date1.setText("Date : "+date);
time1.setText("Time : "+tim);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//Toast.makeText(this,"User date matches with System date",Toast.LENGTH_SHORT).show();
}
else {
//Toast.makeText(this,"User date doesn't matches with System date",Toast.LENGTH_SHORT).show();
}
}
}
Can anyone give me a solution please,
Thanks
you can use AlarmManager to ringing or notify user at particular time.
private AlarmManager alarmManager;
private static Intent alarmIntent;
private static PendingIntent pendingAlarmIntent;
public void setTimings(){
private Calender alarmCalender = Calendar.getInstance();
alarmCalender.setTimeInMillis(System.currentTimeMillis());
alarmCalender.set(Calendar.HOUR_OF_DAY, "hour"); // hour=07
alarmCalender.set(Calendar.MINUTE, "minute"); // minute=01
alarmCalender.set(Calendar.SECOND, "second"); // second=0
alarmCalender.set(Calendar.MILLISECOND, "millisecond");//millisecond=0
setAlarm(AlarmManager.RTC_WAKEUP, alarmCalender, AlarmManager.INTERVAL_DAY);
}
public void setAlarm(int type, Calendar calendar, long timeInMillis){
alarmIntent = new Intent(context, yourBroadcastReciever.class);
pendingAlarmIntent = PendingIntent.getBroadcast(context, Constant.ALARM_REQUEST_CODE, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(type, calendar.getTimeInMillis(), timeInMillis, pendingAlarmIntent);
}
To handle the alarm at particular time you create the Reciever
yourBroadcastReciever.class
#Override
public void onReceive(Context context, Intent intent) {
// here you handle the task when alarm ringing
}
[Note: Intent and Pending Intent is compulsory for create an Alarm]
use a broadcast receiver and set the time which you are getting.
I am new to android development and I hope you can help me solve my problem. Any help will be appreciated. I created a dialogfragment for picking dates. I am able to select the desired dates but I am having trouble in displaying the selected dates.
Here is my DialogFragment
public class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
private Calendar mCalendar;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
mCalendar = Calendar.getInstance();
int year = mCalendar.get(Calendar.YEAR);
int monthOfYear = mCalendar.get(Calendar.MONTH);
int dayOfMonth = mCalendar.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, monthOfYear, dayOfMonth);
}
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mCalendar.set(Calendar.YEAR, year);
mCalendar.set(Calendar.MONTH, monthOfYear);
mCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
}
and I call it from my remindersFragment which extends fragment
private void registerButtonListenersAndSetDefaultText() {
mDateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//getActivity().showDialog(DATE_PICKER_DIALOG);
android.support.v4.app.DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
updateDateButtonText();
}
});
updateDateButtonText();
}
and my updateButton :
private void updateDateButtonText() {
// Set the date button text based upon the value from the database
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
String dateForButton = dateFormat.format(mCalendar.getTime());
mDateButton.setText(dateForButton);
}
I hope you can help me. I've been trying to figure this out for days but I had no luck. Thanks in advance.
Here is the full code on my DialogFragment. I hope this will help:
package com.csu.eclassrecord;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
public class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener{
//
// Date Format
//
private static final String DATE_FORMAT = "yyyy-MM-dd";
private static final String TIME_FORMAT = "kk:mm";
public static final String DATE_TIME_FORMAT = "yyyy-MM-dd kk:mm:ss";
private EditText mTitleText;
private EditText mBodyText;
private Button mDateButton;
private Button mTimeButton;
private Button mConfirmButton;
private Long mRowId;
private RemindersDbAdapter mDbHelper;
private Calendar mCalendar;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
mCalendar = Calendar.getInstance();
int year = mCalendar.get(Calendar.YEAR);
int monthOfYear = mCalendar.get(Calendar.MONTH);
int dayOfMonth = mCalendar.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, monthOfYear, dayOfMonth);
}
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mCalendar.set(Calendar.YEAR, year);
mCalendar.set(Calendar.MONTH, monthOfYear);
mCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateDateButtonText();
}
private void updateDateButtonText() {
// Set the date button text based upon the value from the database
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
String dateForButton = dateFormat.format(mCalendar.getTime());
mDateButton.setText(dateForButton);
}
}
and on my remindersFragment:
package com.csu.eclassrecord;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import com.csu.eclassrecord.R;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;
public class RemindersFragment extends Fragment {
//
// Dialog Constants
//
private static final int DATE_PICKER_DIALOG = 0;
private static final int TIME_PICKER_DIALOG = 1;
//
// Date Format
//
private static final String DATE_FORMAT = "yyyy-MM-dd";
private static final String TIME_FORMAT = "kk:mm";
public static final String DATE_TIME_FORMAT = "yyyy-MM-dd kk:mm:ss";
private EditText mTitleText;
private EditText mBodyText;
private Button mDateButton;
private Button mTimeButton;
private Button mConfirmButton;
private Long mRowId;
private RemindersDbAdapter mDbHelper;
private Calendar mCalendar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDbHelper = new RemindersDbAdapter(getActivity());
View rootView = inflater.inflate(R.layout.fragment_reminders, container, false);
mCalendar = Calendar.getInstance();
mTitleText = (EditText) rootView.findViewById(R.id.title);
mBodyText = (EditText) rootView.findViewById(R.id.body);
mDateButton = (Button) rootView.findViewById(R.id.reminder_date);
mTimeButton = (Button) rootView.findViewById(R.id.reminder_time);
mConfirmButton = (Button) rootView.findViewById(R.id.confirm);
mRowId = savedInstanceState != null ? savedInstanceState.getLong(RemindersDbAdapter.KEY_ROWID)
: null;
registerButtonListenersAndSetDefaultText();
return rootView;
}
private void setRowIdFromIntent() {
if (mRowId == null) {
Bundle extras = getActivity().getIntent().getExtras();
mRowId = extras != null ? extras.getLong(RemindersDbAdapter.KEY_ROWID)
: null;
}
}
#Override
public void onPause() {
super.onPause();
mDbHelper.close();
}
#Override
public void onResume() {
super.onResume();
mDbHelper.open();
setRowIdFromIntent();
populateFields();
}
/**
protected Dialog onCreateDialog(int id) {
switch(id) {
case DATE_PICKER_DIALOG:
return showDatePicker();
case TIME_PICKER_DIALOG:
return showTimePicker();
}
return super.onCreate(id);
private DatePickerDialog showDatePicker() {
DatePickerDialog datePicker = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mCalendar.set(Calendar.YEAR, year);
mCalendar.set(Calendar.MONTH, monthOfYear);
mCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateDateButtonText();
}
}, mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH));
return datePicker;
}
**/
private TimePickerDialog showTimePicker() {
TimePickerDialog timePicker = new TimePickerDialog(getActivity(), new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
mCalendar.set(Calendar.MINUTE, minute);
updateTimeButtonText();
}
}, mCalendar.get(Calendar.HOUR_OF_DAY), mCalendar.get(Calendar.MINUTE), true);
return timePicker;
}
private void registerButtonListenersAndSetDefaultText() {
mDateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//getActivity().showDialog(DATE_PICKER_DIALOG);
android.support.v4.app.DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
}
});
mTimeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().showDialog(TIME_PICKER_DIALOG);
}
});
mConfirmButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent;
saveState();
getActivity().setResult(Activity.RESULT_OK);
Toast.makeText(getActivity(), getString(R.string.task_saved_message), Toast.LENGTH_SHORT).show();
intent = new Intent(getActivity().getApplication(), Manage_Settings.class);
startActivity(intent);
}
});
updateDateButtonText();
updateTimeButtonText();
}
private void populateFields() {
// Only populate the text boxes and change the calendar date
// if the row is not null from the database.
if (mRowId != null) {
Cursor reminder = mDbHelper.fetchReminder(mRowId);
getActivity().startManagingCursor(reminder);
mTitleText.setText(reminder.getString(
reminder.getColumnIndexOrThrow(RemindersDbAdapter.KEY_TITLE)));
mBodyText.setText(reminder.getString(
reminder.getColumnIndexOrThrow(RemindersDbAdapter.KEY_BODY)));
// Get the date from the database and format it for our use.
SimpleDateFormat dateTimeFormat = new SimpleDateFormat(DATE_TIME_FORMAT);
Date date = null;
try {
String dateString = reminder.getString(reminder.getColumnIndexOrThrow(RemindersDbAdapter.KEY_DATE_TIME));
date = dateTimeFormat.parse(dateString);
mCalendar.setTime(date);
} catch (ParseException e) {
Log.e("ReminderEditActivity", e.getMessage(), e);
}
} else {
// This is a new task - add defaults from preferences if set.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String defaultTitleKey = getString(R.string.pref_task_title_key);
String defaultTimeKey = getString(R.string.pref_default_time_from_now_key);
String defaultTitle = prefs.getString(defaultTitleKey, null);
String defaultTime = prefs.getString(defaultTimeKey, null);
if(defaultTitle != null)
mTitleText.setText(defaultTitle);
if(defaultTime != null)
mCalendar.add(Calendar.MINUTE, Integer.parseInt(defaultTime));
}
updateDateButtonText();
updateTimeButtonText();
}
private void updateTimeButtonText() {
// Set the time button text based upon the value from the database
SimpleDateFormat timeFormat = new SimpleDateFormat(TIME_FORMAT);
String timeForButton = timeFormat.format(mCalendar.getTime());
mTimeButton.setText(timeForButton);
}
private void updateDateButtonText() {
// Set the date button text based upon the value from the database
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
String dateForButton = dateFormat.format(mCalendar.getTime());
mDateButton.setText(dateForButton);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putLong(RemindersDbAdapter.KEY_ROWID, mRowId);
}
private void saveState() {
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
SimpleDateFormat dateTimeFormat = new SimpleDateFormat(DATE_TIME_FORMAT);
String reminderDateTime = dateTimeFormat.format(mCalendar.getTime());
if (mRowId == null) {
long id = mDbHelper.createReminder(title, body, reminderDateTime);
if (id > 0) {
mRowId = id;
}
} else {
mDbHelper.updateReminder(mRowId, title, body, reminderDateTime);
}
new ReminderManager(getActivity()).setReminder(mRowId, mCalendar);
}
}
I have two activities and I need to pass some strings and a stringbuilder from TailorThreeActivity.java to EnquireActivity.java.
After displaying the string and stringbuilder data on EnquireActivity screen, I am calling an Intent to send mail by clicking on the "Send Mail" button. The "Send Mail" button will open a mail client and will set all the string and stringbuilder data as the email message body.
I am able to display the value of stringbuilder in EnquireActivity.java, but the other strings coming from TailorThreeActivity.java are not being displayed in the activity. And although the stringbuilder is being displayed in EnquireActivity, neither the strings nor the stringbuilder are displayed in the Email msg body.
This is TailorThreeActivity.java
package com.example.travelplanner;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class TailoredthreeActivity extends Activity implements OnClickListener{
TextView txtday1, txtmon1, txtday2, txtmon2;
EditText et_name,et_email,et_adult,et_child,et_phone;
Button btn;
private int year,year1;
private int month,month1;
private int day,day1;
String date1, date2;
ArrayList<String> getChecked;
static final int DATE_DIALOG_ID = 0;
static final int DATE2_DIALOG_ID = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_tailoredthree);
et_name = (EditText) findViewById(R.id.editname);
et_adult = (EditText) findViewById(R.id.editno_adult);
et_child = (EditText) findViewById(R.id.editno_child);
et_email = (EditText) findViewById(R.id.editmail);
et_phone = (EditText) findViewById(R.id.editphone);
txtday1 = (TextView) findViewById(R.id.txtdate_day);
txtday2 = (TextView) findViewById(R.id.txtdate_day1);
txtmon1 = (TextView) findViewById(R.id.txtdate_mon_year);
txtmon2 = (TextView) findViewById(R.id.txtdate_mon_year1);
btn = (Button)findViewById(R.id.btn_tailorthree_verify);
btn.setOnClickListener(this);
Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
year1 = c.get(Calendar.YEAR);
month1 = c.get(Calendar.MONTH);
day1 = c.get(Calendar.DAY_OF_MONTH);
//get Intents
Bundle extras = getIntent().getExtras();
if(extras!=null)
{
getChecked = extras.getStringArrayList("list");
}
}
#SuppressWarnings("deprecation")
public void showdate(View v) {
showDialog(DATE_DIALOG_ID);
}
#SuppressWarnings("deprecation")
public void showdate1(View v) {
showDialog(DATE2_DIALOG_ID);
}
public void updateDate() {
final String[] MONTHS = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
String mon = MONTHS[month];
txtday1.setText(""+day);
txtmon1.setText(mon+"'"+year);
}
public void updateDate1() {
final String[] MONTHS = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
String mon = MONTHS[month];
txtday2.setText(""+day);
txtmon2.setText(mon+"'"+year);
}
private DatePickerDialog.OnDateSetListener datedialog = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int yy, int mm,
int dd) {
// TODO Auto-generated method stub
month = mm;
day = dd;
year = yy;
date1 = day+"/"+month+"/"+year;
updateDate();
}
};
private DatePickerDialog.OnDateSetListener datedialog2 = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int yy, int mm,
int dd) {
// TODO Auto-generated method stub
month1 = mm;
day1 = dd;
year1 = yy;
date2 = day1+"/"+month1+"/"+year1;
updateDate1();
}
};
protected Dialog onCreateDialog(int id) {
//new DatePick
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this,
datedialog, year, month,day);
case DATE2_DIALOG_ID:
return new DatePickerDialog(this,
datedialog2, year1, month1,day1);
}
return null;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.tailoredthree, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i1 = new Intent(this, EnquireActivity.class);
i1.putExtra(et_name.getText().toString(), "name");
i1.putExtra(et_adult.getText().toString(), "adults");
i1.putExtra(et_child.getText().toString(), "child");
i1.putExtra(et_email.getText().toString(), "email");
i1.putExtra(et_phone.getText().toString(), "phone");
i1.putExtra(date1, "datedept");
i1.putExtra(date2, "datearr");
i1.putStringArrayListExtra("list1", getChecked);
startActivity(i1);
}
}
This is EnquireActivity.java
package com.example.travelplanner;
import java.util.ArrayList;
import java.util.Calendar;
import android.os.Bundle;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
public class EnquireActivity extends Activity implements OnClickListener, OnCheckedChangeListener {
//setting var for datepicker
private int year,year1;
private int month,month1;
private int day,day1;
String date1, date2;
static final int DATE_DIALOG_ID = 0;
static final int DATE2_DIALOG_ID = 1;
Button btn;
StringBuilder stringbuilder, mailbuilder;
String to, subject,msg;
String getname,getadult, getchild, getmail, getphone, getdatedept, getdatearr;
ArrayList<String> getChecked;
CheckBox chk;
EditText et_citylist, et_name, et_adult, et_child, et_mail, et_phone, et_datedepart, et_datearrive;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enquire);
//registering edittexts
et_citylist = (EditText)findViewById(R.id.enquire_edit_city);
et_name = (EditText)findViewById(R.id.enquire_edit_name);
et_adult = (EditText)findViewById(R.id.enquire_edit_adult);
et_child = (EditText)findViewById(R.id.enquire_edit_child);
et_mail = (EditText)findViewById(R.id.enquire_edit_email);
et_phone = (EditText)findViewById(R.id.enquire_edit_phone);
et_datearrive = (EditText)findViewById(R.id.enquire_edit_datearrival);
et_datedepart = (EditText)findViewById(R.id.enquire_edit_datedeparture);
//setting up email button
btn = (Button)findViewById(R.id.btnemail);
btn.setVisibility(View.GONE);
btn.setOnClickListener(this);
//setting up mail content
to = "divyangbhambhani#gmail.com";
subject = "Tour Package Details Summary";
msg = "Tour Enquiry Details:\nName: "+et_name.getText().toString()+"\nDestinations: "+et_citylist.getText().toString()+"\nNo. of Adult Members: "+et_adult.getText().toString()+"\nNo. of Child Members: "+et_child.getText().toString()+"\nDeparture: "+et_datedepart.getText().toString()+"\nArrival: "+et_datearrive.getText().toString()+"\nEmail: "+et_mail.getText().toString()+"\nContact No.: "+et_phone.getText().toString();
//setting checkbox
chk = (CheckBox)findViewById(R.id.chkenquire);
chk.setOnCheckedChangeListener(this);
//setting calender components for datepicker
Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
year1 = c.get(Calendar.YEAR);
month1 = c.get(Calendar.MONTH);
day1 = c.get(Calendar.DAY_OF_MONTH);
//getting Intents from previous activities
Bundle extras = getIntent().getExtras();
if(extras!=null)
{
getChecked = extras.getStringArrayList("list1");
getname = extras.getString("name");
getadult = extras.getString("adults");
getchild = extras.getString("child");
getmail = extras.getString("email");
getphone = extras.getString("phone");
getdatedept = extras.getString("datedept");
getdatearr = extras.getString("datearr");
stringbuilder = new StringBuilder();
for(String value:getChecked){
stringbuilder.append(value).append(" ");
}
}
//adding citylist to edittext
et_citylist.setText(stringbuilder);
et_name.setText(getname);
et_adult.setText(getadult);
et_child.setText(getchild);
et_mail.setText(getmail);
et_phone.setText(getmail);
et_datearrive.setText(getdatearr);
et_datedepart.setText(getdatedept);
}
#SuppressWarnings("deprecation")
public void showdate(View v) {
showDialog(DATE_DIALOG_ID);
}
#SuppressWarnings("deprecation")
public void showdate1(View v) {
showDialog(DATE2_DIALOG_ID);
}
public void updateDate() {
final String[] MONTHS = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
String mon = MONTHS[month];
et_datedepart.setText(date1);
}
public void updateDate1() {
final String[] MONTHS = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
String mon = MONTHS[month];
et_datearrive.setText(date2);
}
private DatePickerDialog.OnDateSetListener datedialog = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int yy, int mm,
int dd) {
// TODO Auto-generated method stub
month = mm;
day = dd;
year = yy;
date1 = day+"/"+month+"/"+year;
updateDate();
}
};
private DatePickerDialog.OnDateSetListener datedialog2 = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int yy, int mm,
int dd) {
// TODO Auto-generated method stub
month1 = mm;
day1 = dd;
year1 = yy;
date2 = day1+"/"+month1+"/"+year1;
updateDate1();
}
};
protected Dialog onCreateDialog(int id) {
//new DatePick
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this,
datedialog, year, month,day);
case DATE2_DIALOG_ID:
return new DatePickerDialog(this,
datedialog2, year1, month1,day1);
}
return null;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.enquire, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Send Mail
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, new String[]{ to});
//email.putExtra(Intent.EXTRA_CC, new String[]{ to});
//email.putExtra(Intent.EXTRA_BCC, new String[]{to});
email.putExtra(Intent.EXTRA_SUBJECT, subject);
email.putExtra(Intent.EXTRA_TEXT, msg);
//need this to prompts email client only
email.setType("message/rfc822");
startActivity(Intent.createChooser(email, "Choose an Email client :"));
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(chk.isChecked())
btn.setVisibility(View.VISIBLE);
else
btn.setVisibility(View.GONE);
}
}
One of the main problems I see is this part of code
i1.putExtra(et_name.getText().toString(), "name");
i1.putExtra(et_adult.getText().toString(), "adults");
i1.putExtra(et_child.getText().toString(), "child");
i1.putExtra(et_email.getText().toString(), "email");
i1.putExtra(et_phone.getText().toString(), "phone");
with
getname = extras.getString("name");
getadult = extras.getString("adults");
getchild = extras.getString("child");
getmail = extras.getString("email");
getphone = extras.getString("phone");
You are not sending correclty these values because when you are using putExtra the first parameter is the key and the second is the value. That's why you are not able to retrieve them in your second activity.
Intent contains name-value pair do-correct in first activity
Intent i = new Intent();
StringBuffer sb = new StringBuffer("Hello");
i.putExtra("email", "jignesh.patel#y7mail.com");
i.putExtra("sub", sb.toString());
Send like this..
For Sending Mail Set these parameters..
String message = "Your_message"; String mail_id = "Email_id"; String
sub = "Mail Subject";
Intent mail = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:" +
mail_id));
mail.putExtra(Intent.EXTRA_SUBJECT,sub);
mail.putExtra(Intent.EXTRA_TEXT, message);
startActivity(Intent.createChooser(mail,"Mail Using"));
..it will work for you..
Im having problem sharing a global variable that I need to retain across multiple activities. This variable is created in TextPlay class and copied onto DailyDataEntry class. I have done some research sharing variables between two activities using Intent but Im looking to share that variable to multiple classes. I think I will have to extends Application but all my other classes are extending Activity already. How am I supposed to extend Application while extending Activity? Thanks a million
///TextPlay Class///
package com.armstrong.y.android.app;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputType;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ToggleButton;
public class TextPlay extends Activity implements View.OnClickListener {
Button chkCmd;
ToggleButton passTog;
EditText input;
TextView display;
EditText etUserId;
Button btnUserId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
baconAndEggs();
passTog.setOnClickListener(this);
chkCmd.setOnClickListener(this);
// Share variables between classes controls
etUserId = (EditText) findViewById(R.id.etUserId);
btnUserId = (Button) findViewById(R.id.btnUserId);
}
private void baconAndEggs() {
// TODO Auto-generated method stub
chkCmd = (Button) findViewById(R.id.bResults);
passTog = (ToggleButton) findViewById(R.id.tbPassword);
input = (EditText) findViewById(R.id.etCommands);
display = (TextView) findViewById(R.id.tvResults);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bResults:
// get the text from the command box then convert it to string
String check = input.getText().toString();
display.setText(check);
if (check.contentEquals("left")) {
display.setGravity(Gravity.LEFT);
} else if (check.contentEquals("center")) {
display.setGravity(Gravity.CENTER);
} else if (check.contentEquals("right")) {
display.setGravity(Gravity.RIGHT);
} else if (check.contentEquals("blue")) {
display.setTextColor(Color.BLUE);
display.setText("blue");
} else if (check.contains("hellow")) {
Random crazy = new Random();
display.setText("hello!!!!");
display.setTextSize(crazy.nextInt(75));
display.setTextColor(Color.rgb(crazy.nextInt(255),
crazy.nextInt(255), crazy.nextInt(255)));
switch (crazy.nextInt(3)) {
case 0:
display.setGravity(Gravity.LEFT);
break;
case 1:
display.setGravity(Gravity.CENTER);
break;
case 2:
display.setGravity(Gravity.RIGHT);
break;
}
} else {
display.setText("invalid");
display.setGravity(Gravity.CENTER);
display.setTextColor(Color.BLACK);
}
break;
case R.id.tbPassword:
// If toggle button is set to ON, password will be ***
if (passTog.isChecked()) {
input.setInputType(InputType.TYPE_CLASS_TEXT
| InputType.TYPE_TEXT_VARIATION_PASSWORD);
} else {
// if toggle is off, its going be plain text
input.setInputType(InputType.TYPE_CLASS_TEXT);
}
break;
}
}
}
///DailyDataEntry Class///
package com.armstrong.y.android.app;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class DailyDataEntry extends Activity {
String strdate;
EditText etGetDate;
Calendar calendarDateToday = Calendar.getInstance();
Calendar calendarDateNext = Calendar.getInstance();
Calendar calendarDatePrevious = Calendar.getInstance();
int counterNext = 0;
int counterPrevious = 0;
Button btnTodayDate;
Button btnPreviousDate;
Button btnGetNextDate;
EditText etDailyCaloriesIn;
EditText etDailyCaloriesOut;
EditText etDailyAnxietyLevel;
EditText etDailySleepQuality;
TextView tvUserId;
Button btnSubmit;
Button btnReset;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.daily_data_entry);
// Toast Message Warning
Toast.makeText(getApplicationContext(),
"DO NOT LEAVE FIELD BLANK OR CRASH IS ON YOU!",
Toast.LENGTH_LONG).show();
btnTodayDate = (Button) findViewById(R.id.btnGetTodayDate);
btnPreviousDate = (Button) findViewById(R.id.btnGetPreviousDate);
btnGetNextDate = (Button) findViewById(R.id.btnGetNextDate);
etGetDate = (EditText) findViewById(R.id.etGetDate);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnReset = (Button) findViewById(R.id.btnReset);
etDailyCaloriesIn = (EditText) findViewById(R.id.etDailyCaloriesIn);
etDailyCaloriesOut = (EditText) findViewById(R.id.etDailyCaloriesOut);
etDailyAnxietyLevel = (EditText) findViewById(R.id.etDailyAnxietyLevel);
etDailySleepQuality = (EditText) findViewById(R.id.etDailySleepQuality);
tvUserId = (TextView) findViewById(R.id.tvUserId);
// When Submit Button is clicked
btnSubmit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Grab User Input from EditText and Convert input String to
// Integer
int check1 = Integer.parseInt(etDailyCaloriesIn.getText()
.toString());
int check2 = Integer.parseInt(etDailyCaloriesOut.getText()
.toString());
int check4 = Integer.parseInt(etDailyAnxietyLevel.getText()
.toString());
int check5 = Integer.parseInt(etDailySleepQuality.getText()
.toString());
strdate = etGetDate.getText().toString();
// Run Legal Value Integrity Check
if (strdate.length() != 8) {
etGetDate.setText("Please enter in the correct format.");
} else if (strdate.equals("")) {
etGetDate.setText("Please enter a date.");
} else if (check1 > 10 || check1 < 1) {
etDailyCaloriesIn.setText("Incorrect Value!");
} else if (check2 > 10 || check2 < 1) {
etDailyCaloriesOut.setText("Incorrect Value!");
} else if (check4 > 10 || check4 < 1) {
etDailyAnxietyLevel.setText("Incorrect Value!");
} else if (check5 > 10 || check5 < 1) {
etDailySleepQuality.setText("Incorrect Value!");
} else {
etGetDate.setText("Submited!");
etDailyCaloriesIn.setText("Submited!");
etDailyCaloriesOut.setText("Submited!");
etDailyAnxietyLevel.setText("Submited!");
etDailySleepQuality.setText("Submited!");
}
}
});
// When Reset Button is Clicked
btnReset.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String empty = "";
etDailyCaloriesIn.setText(empty);
etDailyCaloriesOut.setText(empty);
etDailyAnxietyLevel.setText(empty);
etDailySleepQuality.setText(empty);
etGetDate.setText(empty);
}
});
// Capture Today's Date
btnTodayDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyy");
strdate = sdf.format(calendarDateToday.getTime());
etGetDate.setText(strdate);
}
});
// Capture Previous's Date
btnPreviousDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyy");
if (counterPrevious == 0) {
calendarDatePrevious.add(Calendar.DATE, -1);
}
strdate = sdf.format(calendarDatePrevious.getTime());
etGetDate.setText(strdate);
counterPrevious++;
}
});
// Capture Next's Date
btnGetNextDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyy");
if (counterNext == 0) {
calendarDateNext.add(Calendar.DATE, +1);
}
strdate = sdf.format(calendarDateNext.getTime());
etGetDate.setText(strdate);
counterNext++;
}
});
}
}
Create class that will extends to Application and use it in the following manner whenever you need it:
MyApplication myAppHelper = (MyApplication) context.getApplication();
myAppHelper.setWhatever(whatever);
Whatever whatever = myAppHelper.getWhatever();
I am attempting to create a ToDo list for a class that I am in, and how I have the app is that I have an EditText on top to enter an item in the TDL. and then I am using an extended tablelayout to display the items. I also have a button that calls to a second activity that then has 2 other buttons to get the time and date to (hopefully) display on the TDL item after I hit the Done button on the button (where I would like to go back to the main activity) So far I am testing this on an AVD.
So what I think my issue is that I dont think my second activity is passing back the info that I want. According to the debugger, the onActivityResults method from the first one gets called earlier than the second activity gets called.
Here is the first Activity:
package com.parrishb.todo;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.Button;
public class ToDoActivity extends Activity {
SharedPreferences pref;
public final static int ACTIVITY =1;
public static Globals g;
public ToDoView tdv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_to_do);
final EditText myEditText = (EditText)findViewById(R.id.myEditText);
Button mPickDate = (Button) findViewById(R.id.pickDate);
tdv = (ToDoView)findViewById(R.id.tdv);
myEditText.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if(event.getAction()== KeyEvent.ACTION_DOWN){
if((keyCode == KeyEvent.KEYCODE_DPAD_CENTER) || (keyCode == KeyEvent.KEYCODE_ENTER)){
tdv.addRow(ToDoActivity.this, myEditText.getText().toString());
myEditText.setText("");
return true;
}
}
return false;
}
});
// CLick listener for the date/time button
mPickDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(new Intent(ToDoActivity.this, DatePickerActivity.class), ACTIVITY);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(resultCode== RESULT_OK && requestCode== ACTIVITY){
String append= (new StringBuilder().append(data.getStringExtra("Time"))
.append(" ").append(data.getStringExtra("Date")).toString());
tdv.editRow(ToDoActivity.this, append);
}
}
}
Here is my second activity:
package com.parrishb.todo;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
public class DatePickerActivity extends Activity {
private TextView mDateDisplay;
private Button mPickDate;
private int mYear;
private int mMonth;
private int mDay;
private TextView mTimeDisplay;
private Button mPickTime;
private Button done;
private int mhour;
private int mminute;
static final int TIME_DIALOG_ID = 1;
static final int DATE_DIALOG_ID = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.buttonclick);
mDateDisplay =(TextView)findViewById(R.id.date);
mPickDate =(Button)findViewById(R.id.datepicker);
mTimeDisplay = (TextView) findViewById(R.id.time);
mPickTime = (Button) findViewById(R.id.timepicker);
done = (Button)findViewById(R.id.done);
//Pick time's click event listener
mPickTime.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
showDialog(TIME_DIALOG_ID);
}
});
//PickDate's click event listener
mPickDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//DatePickerActivity.this.finishActivityFromChild(DatePickerActivity.this, ToDoActivity.ACTIVITY);
//finishActivity(ToDoActivity.ACTIVITY);
//return;
//DatePickerActivity.this.finish(ToDoActivity.ACTIVITY);
//finish();
DatePickerActivity.this.finish();
}
});
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
mhour = c.get(Calendar.HOUR_OF_DAY);
mminute = c.get(Calendar.MINUTE);
}
#Override
public void finish(){
Intent resultIntent = new Intent();
Bundle b = new Bundle();
b.putString("Date", mDateDisplay.getText().toString());
b.putString("Time", mTimeDisplay.getText().toString());
resultIntent.putExtras(b);
setResult(Activity.RESULT_OK, resultIntent);
super.finish();
}
//-------------------------------------------update date----------------------------------------//
private void updateDate() {
mDateDisplay.setText(
new StringBuilder()
// Month is 0 based so add 1
.append(mMonth + 1).append("/")
.append(mDay).append("/")
.append(mYear).append(" "));
}
//-------------------------------------------update time----------------------------------------//
public void updatetime()
{
mTimeDisplay.setText(
new StringBuilder()
.append(pad(mhour)).append(":")
.append(pad(mminute)));
}
private static String pad(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
//Datepicker dialog generation
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
updateDate();
}
};
// Timepicker dialog generation
private TimePickerDialog.OnTimeSetListener mTimeSetListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mhour = hourOfDay;
mminute = minute;
updatetime();
}
};
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this,
mDateSetListener,
mYear, mMonth, mDay);
case TIME_DIALOG_ID:
return new TimePickerDialog(this,
mTimeSetListener, mhour, mminute, true);
}
return null;
}
}
I had scratched the second activity and brought the date and time picker into the main activity.