Pass string and stringbuilder from between activities - android

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..

Related

DatePickerDialog showing abnormal behaviour in android 5.1 when timezone is changed

I have to show calender using DatePickerDialog.
The below code is used:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.TextView;
import android.widget.Toast;
public class DatePickerExample extends Activity {
private TextView Output;
private Button changeDate;
private Boolean mEnableNativeCalGridView = null;
String timeZone;
public static TimeZone tz;
private int year;
private int month;
DatePickerDialog d;
public Calendar c;
SimpleDateFormat sdf;
private int day;
public static IntentFilter s_intentFilter;
static final int DATE_PICKER_ID = 1111;
static{
s_intentFilter = new IntentFilter();
s_intentFilter.addAction(Intent.ACTION_TIME_TICK);
s_intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
s_intentFilter.addAction(Intent.ACTION_TIME_CHANGED);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
registerReceiver(m_timeChangedReceiver, s_intentFilter);
Output = (TextView) findViewById(R.id.Output);
changeDate = (Button) findViewById(R.id.changeDate);
// sdf = new SimpleDateFormat("EEE, MMM d, ''yy");//Wed, Jul 4, '01
// Show current date
Output.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(month + 1).append("-").append(day).append("-")
.append(year).append(" "));
// Button listener to show date picker dialog
changeDate.setOnClickListener(new OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
// On button click show datepicker dialog
showDialog(DATE_PICKER_ID);
}
});
}
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case DATE_PICKER_ID:
((DatePickerDialog) dialog).updateDate(
c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH));
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_PICKER_ID:
// open datepicker dialog.
// set date picker for current date
// add pickerListener listner to date picker
sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
tz = TimeZone.getDefault();
System.out.println("TimeZone "+tz.getDisplayName(false, TimeZone.SHORT)+" Timezon id :: " +tz.getID());
timeZone = tz.getDisplayName(false, TimeZone.SHORT);
c= Calendar.getInstance();
c.setTimeZone(tz);
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
d = new DatePickerDialog(DatePickerExample.this, pickerListener, year, month,day);
setMinMaxdate();
return d;
}
return null;
}
////////////////////Fix for issue on OS 5.1 //////////////////////
public long getDateFormatted(String date){
String givenDateString = date;
long timeInMilliseconds = 0;
try {
Date mDate = sdf.parse(givenDateString);
timeInMilliseconds = mDate.getTime();
System.out.println("Date in milli :: " + timeInMilliseconds);
} catch (ParseException e) {
e.printStackTrace();
}
return timeInMilliseconds;
}
//////////////////////////////////////////
private DatePicker.OnDateChangedListener newchange= new OnDateChangedListener(){
#Override
public void onDateChanged(DatePicker view,
int year, int monthOfYear,int dayOfMonth) {
Toast.makeText(getApplicationContext(),
"onDateChanged", Toast.LENGTH_SHORT).show();
}};
DatePicker datePicker;
public void setMinMaxdate() {
//Time zone calculation
//TimeZone.setDefault(tz);
///////////////////////
long calEvtEndDate= getDateFormatted("Sun May 31 23:59:59 "+timeZone+" 2015");//System.currentTimeMillis();
long calEvtStartDate= getDateFormatted("Wed May 13 00:00:00 "+timeZone+" 2015");//System.currentTimeMillis()/2;
// long calEvtEndDate = getDateFormatted("Sun, may 31, '15");
//long calEvtStartDate = getDateFormatted("Wed, may 13, '15");
if(d != null){
datePicker = d.getDatePicker();
if(mEnableNativeCalGridView != null){
datePicker.setCalendarViewShown(mEnableNativeCalGridView.booleanValue());
}
// If Start Date is Greater than End Date then we are showing from valid StartDate
// value and we are not setting the maxdate.
if (calEvtStartDate > calEvtEndDate) {
datePicker.setMinDate(calEvtStartDate);
} else {
if (calEvtStartDate > 0) { // If Only ValidStart date is provided, then setting the minDate.
datePicker.setMinDate(calEvtStartDate);
}
if (calEvtEndDate > 0) { // If Only ValidEnd date is provided, then setting the maxDate.
datePicker.setMaxDate(calEvtEndDate);
}
}
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
System.out.println("-------resumed");
}
public DatePickerDialog.OnDateSetListener pickerListener = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
#Override
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
//view.updateDate(year, month, day);
System.out.println("---------------datesetchange");
year = selectedYear;
month = selectedMonth;
day = selectedDay;
// Show selected date
Output.setText(new StringBuilder().append(month + 1)
.append("-").append(day).append("-").append(year)
.append(" "));
}
};
public void onDestroy() {
super.onDestroy();
unregisterReceiver(m_timeChangedReceiver);
}
private final BroadcastReceiver m_timeChangedReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(Intent.ACTION_TIME_CHANGED) ||
action.equals(Intent.ACTION_TIMEZONE_CHANGED))
{
System.out.println("timezone changed---"+action.toString());
tz = TimeZone.getDefault();
System.out.println("TimeZone "+tz.getDisplayName(false, TimeZone.SHORT)+" Timezon id :: " +tz.getID());
timeZone = tz.getDisplayName(false, TimeZone.SHORT);
// Intent intent1 = getIntent();
// finish();
// startActivity(intent1);
showDialog(DATE_PICKER_ID);
}
}
};
}
When the app is running, I go to the settings and change the Timezone to such a value so that the current date will change. Now when we select any date in the dialog, it behaves abnormally and goes to other date. I have used setMinDate() and setMaxDate() methods. This happens only in Android OS 5.1.
Any idea or help? Thanks in advance.

DialogFragment does not update the Display

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);
}
}

on tab change in same page, 2nd time OnCreate() doesn't work

All the functions are running properly, but only one problem exists that if i record details for a day, and if I switch tab to the history tab to see the new record, the viewlist in the history class should display that record. However the viewlist doesnot display the lastest record, and i check the database, the lastest record has been written into database. The only way to see the new record is to close the emulator and restart it.
I found the problem that on startup, the recorder and history tab would both be initialised in OnCreate() method. But after that when I switch between these two tabs, it would not be initialised. Therefore, in the history.class, it would not open the database and read the data. That's the problem. Could somebody please help me, thanks
tab Prototype class
package com.example.tabpro;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
public class TabBar extends TabActivity{
static TabHost tabHost=null;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.tab);
tabHost = (TabHost)findViewById(android.R.id.tabhost);
tabHost = getTabHost();
Intent recorderIntent = new Intent(TabBar.this, Recorder.class);
TabSpec recorderTabSpec = tabHost.newTabSpec("tab1");
recorderTabSpec.setIndicator("Recorder");
recorderTabSpec.setContent(recorderIntent);
tabHost.addTab(recorderTabSpec);
Intent historyIntent = new Intent(TabBar.this,History.class);
TabSpec historyTabSpec = tabHost.newTabSpec("tab2");
historyTabSpec.setIndicator("History");
historyTabSpec.setContent(historyIntent);
tabHost.addTab(historyTabSpec);
tabHost.setCurrentTab(0);
}
public void switchTab(int tab)
{
tabHost.setCurrentTab(tab);
}
}
Recorder.class
package com.example.tabpro;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
public class Recorder extends Activity implements OnSeekBarChangeListener {
int mYear;
int mMonth;
int mDay;
TextView dateDisplay;
Button pickDateButton;
TextView sbHourValue;
TextView sbMinValue;
int hours;
int mins;
static final int DATE_DIALOG_ID = 0;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.recorder);
initialDatePicker();
initialSeekBar();
initialSaveButton();
}
public void initialDatePicker()
{
dateDisplay = (TextView)findViewById(R.id.dateDisplay);
pickDateButton = (Button)findViewById(R.id.pickDate);
pickDateButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
final Calendar currentDate = Calendar.getInstance();
mYear = currentDate.get(Calendar.YEAR);
mMonth = currentDate.get(Calendar.MONTH);
mDay = currentDate.get(Calendar.DAY_OF_MONTH);
dateDisplay.setText(new StringBuilder()
.append(mYear).append("-")
.append(mMonth + 1).append("-")
.append(mDay));
}
public DatePickerDialog.OnDateSetListener mDateSetListener = new OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
dateDisplay.setText(new StringBuilder()
.append(mYear).append("-")
.append(mMonth + 1).append("-")//start from 0
.append(mDay));
}
};
protected Dialog onCreateDialog(int id){
switch(id)
{
case DATE_DIALOG_ID:
return new DatePickerDialog(this,mDateSetListener,mYear, mMonth, mDay);
}
return null;
}
public void initialSeekBar()
{
SeekBar sbHour = (SeekBar)findViewById(R.id.seekBar_hour);
sbHour.setMax(23);
sbHour.setProgress(0);
sbHour.setOnSeekBarChangeListener(this);
sbHourValue = (TextView)findViewById(R.id.textView_hour);
sbHourValue.setText("0"+ " hour(s)");
SeekBar sbMin = (SeekBar)findViewById(R.id.seekBar_min);
sbMin.setMax(59);
sbMin.setProgress(0);
sbMin.setOnSeekBarChangeListener(this);
sbMinValue = (TextView)findViewById(R.id.TextView_min);
sbMinValue.setText("0" + " minute(s)");
}
public void initialSaveButton()
{
Button saveButton = (Button)findViewById(R.id.button_save);
saveButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String time;
String date;
date = dateDisplay.getText().toString();
time = hours + " hour(s) " + mins + " minute(s)";
TabProDB db;
db = new TabProDB(Recorder.this);
db.open();
boolean findSameDay = false;
Cursor c = db.GetAllRecords();
if(c!=null)
{
if (c.moveToFirst())
{
do {
String dateToCompare = c.getString(c.getColumnIndex(TabProDB.KEY_DATE));
if(dateToCompare.equalsIgnoreCase(date))
{
findSameDay = true;
}
} while (c.moveToNext());
}
}
if(findSameDay!=true)
{
long id = db.insertRecord(date, time);
db.close();
Toast.makeText(Recorder.this, "Record Saved" , Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(Recorder.this, "You have already recorded the today: " + date, Toast.LENGTH_SHORT).show();
db.close();
}
switchTabInActivity(1);
}
});
}
public void switchTabInActivity(int index)
{
TabBar parentActivity;
parentActivity = (TabBar)this.getParent();
parentActivity.switchTab(index);
}
#Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
// TODO Auto-generated method stub
if(arg0.getId() == R.id.seekBar_hour){
// update hour value
hours = arg1;
sbHourValue.setText(Integer.toString(arg1)+" hour(s)");
}
else{
// update minute value
mins = arg1;
sbMinValue.setText(Integer.toString(arg1)+" minute(s)");
}
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
}
History.class
package com.example.tabpro;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class History extends Activity implements OnItemClickListener {
int getdbID;
String Date;
String Time;
ListView date_time_ListView;
ArrayList<String> listItems = null;
ArrayAdapter arrayAdapter = null;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.history);
date_time_ListView = (ListView) findViewById(R.id.listView1);
TabProDB db = new TabProDB(this);
try{
listItems = new ArrayList<String>();
db.open();
Cursor c = db.GetAllRecords();
if(c!=null)
{
if (c.moveToFirst())
{
do{
String date1 = c.getString(c.getColumnIndex(TabProDB.KEY_DATE) );
String time1 = c.getString(c.getColumnIndex(TabProDB.KEY_TIME) );
String date_time1 = date1 + "\n" +time1;
listItems.add(date_time1);
}while (c.moveToNext());
}
}
db.close();
}catch (Exception e) {}
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, listItems );
date_time_ListView.setAdapter(arrayAdapter);
date_time_ListView.setOnItemClickListener(this);
date_time_ListView.setOnItemLongClickListener(new OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
AlertDialog.Builder ad = new AlertDialog.Builder(History.this);
ad.setTitle("Delete?");
ad.setMessage("Are you sure you want to delete this record?");
final int positionToRemove = position;
String selectedFromList = (date_time_ListView.getItemAtPosition(position).toString());
String[] splitDateTime = selectedFromList.split("\n");
final String splitDate = splitDateTime[0];
Toast.makeText(History.this, splitDate, Toast.LENGTH_SHORT).show();
String splitTime = splitDateTime[1];
ad.setNegativeButton("Cancel", null);
ad.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
TabProDB db = new TabProDB(History.this);
try
{
db.open();
Cursor c = db.GetAllRecords();
if(c!=null)
{
if(c.moveToFirst())
{
do
{
//search database to find a date that equals the date on the listview
String findDate = c.getString(c.getColumnIndex(TabProDB.KEY_DATE));
if(splitDate.equalsIgnoreCase(findDate))
{
getdbID =c.getInt(c.getColumnIndex(TabProDB.KEY_ROWID));
db.deleteRow(getdbID);
break;
}
else
{
}
}while(c.moveToNext());
}
}
}
catch(Exception e){}
db.close();
listItems.remove(positionToRemove);
arrayAdapter.notifyDataSetChanged();
}
});
ad.show();
return false;
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {
// TODO Auto-generated method stub
Intent i = new Intent(History.this, Update.class);
String str1[] = ((TextView) view).getText().toString().split("\n");
String str2 = str1[0];
String str3 = str1[1];
i.putExtra("date", str2);
i.putExtra("time", str3);
i.putExtra("position", position);
startActivity(i);
}
}
final Intent i = new Intent().setClass(TabBar.this,
Recorder.class);
TabSpec spec1 = tabHost.newTabSpec("Recoder");
spec1.setContent(i);
spec1.setIndicator(getResources().getString(R.string.title_card_post1),
getResources().getDrawable(R.drawable.tab1));
final Intent i = new Intent().setClass(TabBar.this,
History.class);
TabSpec spec1 = tabHost.newTabSpec("History");
spec1.setContent(i);
spec1.setIndicator(getResources().getString(R.string.title_card_post1),
getResources().getDrawable(R.drawable.tab1));
tabHost.addTab(spec1);
tabHost.addTab(spec2);
Try this code and let me know whether this works for you because this solution is working for me and one of my application does have it.

My child Activity does not send result back to parent

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.

How to set the date from DatePicker dialog for multiple calls

Good day, can't seem to find a solution for this. i have 2 buttons that when pressed, opens a datepickerdialog, but my problem now is , how can i set them to the appropriate button on OnDateSet method. I am using a DialogFragment for the date and then implementing the DateListener in my activity. I have tried using getTag() but no success in getting the tag. here is what i tried:
public void showfromDatePickerDialog(View v) {
DialogFragment dateFragment = new DateDialogFragment();
dateFragment.show(getSupportFragmentManager(), "fromdatePicker");
}
public void showtoDatePickerDialog(View v) {
DialogFragment dateFragment = new DateDialogFragment();
dateFragment.show(getSupportFragmentManager(), "todatePicker");
}
public void onDateSet(DatePicker view, int year, int month, int day) {
StringBuilder builder = new StringBuilder();
builder.append(day).append("-")
.append(month).append("-")
.append(year);
String text= builder.toString();
if(view.getTag().toString().equals("fromdatePicker")) { // error here
Log.d(TAG, "got here" + text);
fromdate.setText(text);
}
if(view.getTag() == "todatePicker") {
todate.setText(text);
}
any ideas how to implement this? i keep seeing solutions about using 2 different DialogFragment class but am guessing there should be another way. or am i wrong? Thank you
ok, i have a work around for these. which can be helpful for anyone with this problem. if its slightly incorrect please let me know and i can change it. but this is what i did to solve this issue.
in on DateSet:
public void onDateSet(DatePicker view, int year, int month, int day) {
StringBuilder builder = new StringBuilder();
builder.append(day).append("-")
.append(month).append("-")
.append(year);
String text= builder.toString();
FragmentManager fragmanager = getSupportFragmentManager();
if(fragmanager.findFragmentByTag("fromdatePicker") != null) {
Log.d(TAG, "got here" + text);
fromdate.setText(text);
}
// if(view.getTag() == "todatePicker") {
if(fragmanager.findFragmentByTag("todatePicker") != null) {
todate.setText(text);
}
that way you can use the same dateListener for multiple calls and set the date appropriately based on the tag that was passed when calling show on the dialog.
Use below code of DatePicker Dialog.
private int mYear;
private int mMonth;
private int mDay;
Calendar cal4DatePicker = Calendar.getInstance();
Button btnDOB=findviewbyId(R.id.btndob);
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
cal4DatePicker.set(Calendar.YEAR, mYear);
cal4DatePicker.set(Calendar.MONTH, mMonth);
cal4DatePicker.set(Calendar.DAY_OF_MONTH, mDay);
btnDOB.setText(new StringBuilder()
.append(mDay).append("-").append(mMonth).append("-").append(mYear).append(" "));
}
};
on btnDOB you need to set click listner to show this DatePicker Dialog.
I have try same thing with Time Picker only. You can try out and set same for date picker also.
package com.example.toolboxtest;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TimePicker;
public class MainActivity extends FragmentActivity implements OnClickListener {
Button testBtn;
EditText testET;
static final int TIME_DIALOG_ID = 0;
int mHour = 0;
int mMinute = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
testBtn = (Button) findViewById(R.id.testBTn);
testET = (EditText) findViewById(R.id.testET);
testBtn.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.testBTn:
showDialog(TIME_DIALOG_ID);
break;
}
}
private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mHour=hourOfDay;
mMinute = minute;
// myPrefs = ImportantDateReminderActivity.this.getSharedPreferences("myPrefs",MODE_WORLD_WRITEABLE);
// prefsEditor = myPrefs.edit();
// prefsEditor.putInt("hour", mHour);
// prefsEditor.putInt("minute", mMinute);
// prefsEditor.putString("a", a);
// prefsEditor.commit();
if(mHour==12){
//reminderSetTime.setText(new StringBuilder().append("12").append(":").append((minute)+" PM"));
testET.setText(mHour+":"+mMinute+" "+"PM");
}
else
updateTimeDisplay();
}
};
private void updateTimeDisplay() {
try {
Format formatter;
SimpleDateFormat df = new SimpleDateFormat("hh:mm");
Date d = df.parse(mHour + ":" + mMinute);
Calendar gc = new GregorianCalendar();
gc.setTime(d);
//gc.add(Calendar.HOUR, 0);
Date d2 = gc.getTime();
formatter = new SimpleDateFormat("hh:mm a");
String time = formatter.format(d2);
System.out.println("The TIME is: "+time);
testET.setText(time);
String hour = new SimpleDateFormat("hh").format(d2);
String minute = new SimpleDateFormat("mm").format(d2);
String a = new SimpleDateFormat("a").format(d2);
System.out.println("The Hour is: "+hour+ " "+minute+ " " +a);
/*myPrefs = this.getSharedPreferences("myPrefs",MODE_WORLD_WRITEABLE);
prefsEditor = myPrefs.edit();
prefsEditor.putInt("hour", Integer.parseInt(hour));
prefsEditor.putInt("minute", Integer.parseInt(minute));
prefsEditor.putString("a", a);
prefsEditor.putString("complateTime", time);
prefsEditor.commit();*/
//addTwoMonthNotification();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG_ID:
return new TimePickerDialog(this,mTimeSetListener, mHour, mMinute, false);
}
return null;
}
}
Hope it will help you.
Please let me know if there is any issue.

Categories

Resources