app ends while clicking datepicker button - android

My program contains a button named date to show calendar view. but app ends while clicking it. pls give me a solution.My program contains a button named date to show calendar view. but app ends while clicking it. pls give me a solution.
FirstActivity.java
package example.showevent1;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.os.Bundle;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.support.v4.app.*;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;
public class FirstActivity extends FragmentActivity implements OnItemSelectedListener, OnDateSetListener {
/** Called when the activity is first created. */
private static final String DATE_FORMAT = "yyyy-MM-dd";
classdbOpenHelper eventsData;
TextView userSelection;
Button okButton;
Button date1;
public EditText date;
private Calendar mCalendar;
private static final String[] items = { "Yalahanka", "Rajai nagar", "Sivaji Nagar", "Koramangala", "RT Nagar", "Banashankari", "Yashwanthpura", "Hebbal" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
okButton = (Button) findViewById(R.id.button2);
date1 = (Button) findViewById(R.id.button1);
userSelection = (TextView) findViewById(R.id.textView1);
Spinner my_spin = (Spinner) findViewById(R.id.spinner1);// data1
my_spin.setOnItemSelectedListener(this);
ArrayAdapter aa = new ArrayAdapter(this, android.R.layout.simple_spinner_item, items);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
my_spin.setAdapter(aa);
okButton.setOnClickListener(new clicker());
eventsData = new classdbOpenHelper(this);
date1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDatePicker();
}
});
}
static final String YEAR = "year";
static final String MONTH = "month";
static final String DAY = "day";
static final String HOUR = "hour";
static final String MINS = "mins";
static final String CALENDAR = "calendar";
private void showDatePicker() {
Object ft = getFragmentManager().beginTransaction();
DatePickerDialogFragment newFragment = new DatePickerDialogFragment();
Bundle args = new Bundle();
args.putInt(YEAR, mCalendar.get(Calendar.YEAR));
args.putInt(MONTH, mCalendar.get(Calendar.MONTH));
args.putInt(DAY, mCalendar.get(Calendar.DAY_OF_MONTH));
newFragment.setArguments(args);
newFragment.show((FragmentManager) ft, "datePicker");
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int pos, long arg3) {
userSelection.setText(items[pos]);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
userSelection.setText("");
}
class clicker implements Button.OnClickListener {
public void onClick(View v) {
String datevalue = date1.getText().toString();
String Userselectvalue = userSelection.getText().toString();
SQLiteDatabase db = eventsData.getWritableDatabase();
ContentValues cv = new ContentValues();
// cv.put(classdbOpenHelper.KEY_COUNTED,
// metersave.getText().toString());
cv.put(classdbOpenHelper.KEY_DESC, Userselectvalue);
cv.put(classdbOpenHelper.KEY_DATE, datevalue);
db.insert(classdbOpenHelper.DATABASE_TABLE, null, cv);
}
public void onDestroy() {
eventsData.close();
}
}
#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);
updateButtons();
}
private void updateButtons() {
// Set the date button text
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
String dateForButton = dateFormat.format(mCalendar.getTime());
date1.setText(dateForButton);
}
}
DatePickerDialogFragment.java
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.*;
public class DatePickerDialogFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Bundle args = getArguments();
Fragment editFragment = getFragmentManager().findFragmentByTag(FirstActivity.ACCESSIBILITY_SERVICE);
OnDateSetListener listener = (OnDateSetListener) editFragment;
return new DatePickerDialog(getActivity(), listener,
args.getInt(FirstActivity.YEAR),
args.getInt(FirstActivity.MONTH),
args.getInt(FirstActivity.DAY));
}
}

You are getting a Nullpointer because you never actually initialize the Calendar object:
mCalendar

Related

how to show current date in edit text view

THIS MY CODE
package com.clip.android;
/**
*
* #author abhishek
*
*/
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.Toast;
public class ClaimRegister extends ClaimActivity implements OnClickListener{
EditText polid;
/*DatePicker claimDate;*/
String userValue;
String getClaimDate;
Spinner Spinner;
String clmType;
ImageButton calIcon;
EditText claimDate;
/*TextView b1;*/
double a = 4.32;
double b = Math.pow(10.0,8.0);
int year,day,month;
List<String> claimTypes=new ArrayList<String>();
/* List<Customer> customers = new ArrayList<Customer>();*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_claim_register);
setHeader("Register Your Claim", true, true);
claimDate = (EditText)findViewById(R.id.editText1);
polid = (EditText)findViewById(R.id.polid);
/*claimDate = (DatePicker)findViewById(R.id.dp);*/
Spinner=(Spinner) findViewById(R.id.spin);
userValue = polid.getText().toString();
calIcon = (ImageButton)findViewById(R.id.imageButton1);
calIcon.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
/*claimDate.setMinDate((long)(c.getTimeInMillis()-(a*b)));
claimDate.init(year, month, day, null);*/
claimDate.setText(String.valueOf(c.getTimeInMillis()-(a*b)));
DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,int monthOfYear, int dayOfMonth)
{
Calendar cl = Calendar.getInstance();
cl.set(year, monthOfYear, dayOfMonth-1);
if(cl.before(Calendar.getInstance())){
claimDate.setText(dayOfMonth+"-"+(monthOfYear)+"-"+year);
}else {
claimDate.setText("");
Toast.makeText(ClaimRegister.this, "Date Shold Be Within Current Date.", Toast.LENGTH_SHORT).show();
return;
}
year = year;
month = monthOfYear;
day = dayOfMonth;
}
}, year, month, day;
((Dialog) datePickerListener).show();
}
});
AsyncCall drop = new AsyncCall();
drop.execute();
}
private class AsyncCall extends AsyncTask<String, Void, Void>{
#Override
protected Void doInBackground(String... params) {
Log.d("doBack", "0000");
claimTypes = com.clip.webservice.GetAQuote.GetLineofBusiness("CLMTYPE", "getClmType");
return null;
}
protected void onPostExecute(Void result)
{
Log.d("onPost", "lol");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ClaimRegister.this, android.R.layout.simple_spinner_dropdown_item,claimTypes);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Log.d("onPost", "123");
Spinner.setAdapter(adapter);
Log.d("onPost", "hiiii");
Spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(getApplicationContext(), "type = "+ item, Toast.LENGTH_LONG).show();
clmType= Spinner.getSelectedItem().toString();
}
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
String item=parent.getSelectedItem().toString();
Toast.makeText(getApplicationContext(), "type = "+ item, Toast.LENGTH_LONG).show();
clmType= Spinner.getSelectedItem().toString();
}
});
}
}
public void submit(View view)
{
userValue = polid.getText().toString();
if(userValue.trim().equals("")&& userValue != null){
Toast.makeText(this, "Policy Id is required", Toast.LENGTH_LONG).show();
}
else{
Intent intent = new Intent(this,ClaimRegisterPage.class);
intent.putExtra("getclmType", clmType);
intent.putExtra("userValue", userValue);
Log.d("In submit", "userValue = "+userValue);
startActivity(intent);
}
}
}
ERROR:-
04-26 11:45:04.450: E/AndroidRuntime(2813): FATAL EXCEPTION: main
04-26 11:45:04.450: E/AndroidRuntime(2813): Process: com.clip.android, PID: 2813
04-26 11:45:04.450: E/AndroidRuntime(2813): java.lang.ClassCastException: com.clip.android.ClaimRegister$1$1 cannot be cast to android.app.Dialog
04-26 11:45:04.450: E/AndroidRuntime(2813): at com.clip.android.ClaimRegister$1.onClick(ClaimRegister.java:96)
04-26 11:45:04.450: E/AndroidRuntime(2813): at android.view.View.performClick(View.java:5198)
04-26 11:45:04.450: E/AndroidRuntime(2813): at android.view.View$PerformClick.run(View.java:21147)
04-26 11:45:04.450: E/AndroidRuntime(2813): at android.os.Handler.handleCallback(Handler.java:739)
04-26 11:45:04.450: E/AndroidRuntime(2813): at android.os.Handler.dispatchMessage(Handler.java:95)
04-26 11:45:04.450: E/AndroidRuntime(2813): at android.os.Looper.loop(Looper.java:148)
04-26 11:45:04.450: E/AndroidRuntime(2813): at android.app.ActivityThread.main(ActivityThread.java:5417)
04-26 11:45:04.450: E/AndroidRuntime(2813): at java.lang.reflect.Method.invoke(Native Method)
04-26 11:45:04.450: E/AndroidRuntime(2813): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
04-26 11:45:04.450: E/AndroidRuntime(2813): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
What Set current date as default date and i want to allow user 15 days behind from current date not below than that date.Please help to resolve this.
DatePickerDialog is a Dialog But DatePickerDialog.OnDateSetListener is not a Dailog that can be cast. So show DatePickerDialog instead of showing datePickerListener. It's the line of error
((Dialog) datePickerListener).show();
See the example how DatePickerDialog is created and used.
//Current date
String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
// editText is the EditText that should display it
editText.setText(currentDateTimeString);
For 15 days limit, you can use if else condition before setting the date to edit text.So if user Selects date before 15 days the edit text remains empty
There are couple of errors that I've noticed in the code,
1) Replace
calIcon.setOnClickListener(new Button.OnClickListener()
with
calIcon.setOnClickListener(new View.OnClickListener()
2) Below type-casting is causing the crash
((Dialog) datePickerListener).show();
You should create an instance of Dialog, build it with require attributes and set the listener. Then call the show() method on it. Refer, Datepicker: How to popup datepicker when click on button and store value in variable
Resolved Code
package com.clip.android;
/**
*
* #author abhishek
*
*/
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.Toast;
public class ClaimRegister extends ClaimActivity implements OnClickListener{
EditText polid;
String userValue;
String getClaimDate;
Spinner Spinner;
String clmType;
ImageButton calIcon;
EditText claimDate;
double a = 1.296;
double b = Math.pow(10.0,9.0);
static final int DATE_PICKER_ID = 0;
int year,day,month;
List<String> claimTypes=new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_claim_register);
setHeader("Register Your Claim", true, true);
claimDate = (EditText)findViewById(R.id.editText1);
polid = (EditText)findViewById(R.id.polid);
Spinner=(Spinner) findViewById(R.id.spin);
userValue = polid.getText().toString();
calIcon = (ImageButton)findViewById(R.id.imageButton1);
claimDate.setEnabled(false);
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
claimDate.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(day).append("-").append(month + 1).append("-")
.append(year).append(" "));
calIcon.setOnClickListener(new OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(View v) {
// On button click show datepicker dialog
showDialog(DATE_PICKER_ID);
}
});
AsyncCall drop = new AsyncCall();
drop.execute();
}
private class AsyncCall extends AsyncTask<String, Void, Void>{
#Override
protected Void doInBackground(String... params) {
Log.d("doBack", "0000");
claimTypes = com.clip.webservice.GetAQuote.GetLineofBusiness("CLMTYPE", "getClmType");
return null;
}
protected void onPostExecute(Void result)
{
Log.d("onPost", "lol");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ClaimRegister.this, android.R.layout.simple_spinner_dropdown_item,claimTypes);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Log.d("onPost", "123");
Spinner.setAdapter(adapter);
Log.d("onPost", "hiiii");
Spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(getApplicationContext(), "type = "+ item, Toast.LENGTH_LONG).show();
clmType= Spinner.getSelectedItem().toString();
}
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
String item=parent.getSelectedItem().toString();
Toast.makeText(getApplicationContext(), "type = "+ item, Toast.LENGTH_LONG).show();
clmType= Spinner.getSelectedItem().toString();
}
});
}
}
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
//disabled the dates lesser than 15 days from current date onload of date picker dialog
DatePickerDialog dp = new DatePickerDialog(this, pickerListener, year, month,day);
Calendar c = Calendar.getInstance();
dp.getDatePicker().setMinDate(((long)(c.getTimeInMillis()-(a*b))));
return dp;
}
return null;
}
private DatePickerDialog.OnDateSetListener pickerListener = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
// Show selected date
claimDate.setText(new StringBuilder().append(day)
.append("-").append(month + 1).append("-").append(year)
.append(" "));
}
};
public void submit(View view)
{
userValue = polid.getText().toString();
//Validation for Policy Id since it's mandatory
if(userValue.trim().equals("")&& userValue != null){
Toast.makeText(this, "Policy Id is required", Toast.LENGTH_LONG).show();
}
else{
Intent intent = new Intent(this,ClaimRegisterPage.class);
intent.putExtra("getclmType", clmType);
intent.putExtra("userValue", userValue);
Log.d("In submit", "userValue = "+userValue);
startActivity(intent);
}
}
}

Data exchange via Intent between Fragments works on pre-5.0 but not on Android 5.0

As a part of The Big Nerd Ranch's Android Guide example Criminal Intent,
I am updating a button with date/time entered in the
Date/TimePicker. Button and Date/TimePicker reside in different
fragments. I am transferring data between them using an Intent. It
works fine on Pre-Lollipop devices but doesn't seem to update button
text on Android 5.0 or Lollipop devices. What am I missing?
Full code can be seen at Github.
CrimeFragment.java
package com.sudhirkhanger.android.criminalintent;
import java.util.Date;
import java.util.UUID;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
public class CrimeFragment extends Fragment {
private Crime mCrime;
private EditText mTitleField;
private Button mDateButton;
private Button mTimeButton;
private CheckBox mSolvedCheckBox;
private static final String TAG = "CriminalFragment";
public static final String EXTRA_CRIME_ID = "com.sudhirkhanger.android.criminalintent.crime_id";
private static final String DIALOG_DATE = "date";
private static final String DIALOG_TIME = "time";
private static final int REQUEST_DATE = 0;
private static final int REQUEST_TIME = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UUID crimeId = (UUID) getArguments().getSerializable(EXTRA_CRIME_ID);
mCrime = CrimeLab.get(getActivity()).getCrime(crimeId);
}
private void updateDateAndTime() {
Date d = mCrime.getDate();
CharSequence c = DateFormat.format("EEEE, MMM dd, yyyy", d);
CharSequence t = DateFormat.format("h:mm a", d);
mDateButton.setText(c);
mTimeButton.setText(t);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_crime, parent, false);
mTitleField = (EditText) v.findViewById(R.id.crime_title);
mTitleField.setText(mCrime.getTitle());
mTitleField.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence c, int start, int before,
int count) {
mCrime.setTitle(c.toString());
}
public void beforeTextChanged(CharSequence c, int start, int count,
int after) {
// This space intentionally left blank
}
public void afterTextChanged(Editable c) {
// This one too
}
});
mDateButton = (Button) v.findViewById(R.id.crime_date);
mDateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentManager fm = getActivity().getSupportFragmentManager();
DatePickerFragment dialog = DatePickerFragment
.newInstance(mCrime.getDate());
dialog.setTargetFragment(CrimeFragment.this, REQUEST_DATE);
dialog.show(fm, DIALOG_DATE);
}
});
mTimeButton = (Button) v.findViewById(R.id.crime_time);
mTimeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentManager fm = getActivity().getSupportFragmentManager();
TimePickerFragment dialog = TimePickerFragment
.newInstance(mCrime.getDate());
dialog.setTargetFragment(CrimeFragment.this, REQUEST_TIME);
dialog.show(fm, DIALOG_TIME);
}
});
updateDateAndTime();
mSolvedCheckBox = (CheckBox) v.findViewById(R.id.crime_solved);
mSolvedCheckBox.setChecked(mCrime.isSolved());
mSolvedCheckBox
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// Set the crime's solved property
mCrime.setSolved(isChecked);
}
});
return v;
}
public static CrimeFragment newInstance(UUID crimeId) {
Bundle args = new Bundle();
args.putSerializable(EXTRA_CRIME_ID, crimeId);
CrimeFragment fragment = new CrimeFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK)
return;
if (requestCode == REQUEST_DATE) {
Date date = (Date) data
.getSerializableExtra(DatePickerFragment.EXTRA_DATE);
mCrime.setDate(date);
updateDateAndTime();
} else if (requestCode == REQUEST_TIME) {
Date date = (Date) data
.getSerializableExtra(TimePickerFragment.EXTRA_TIME);
mCrime.setDate(date);
updateDateAndTime();
}
}
}
DatePickerFragment.java
package com.sudhirkhanger.android.criminalintent;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.View;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
public class DatePickerFragment extends DialogFragment {
public static final String EXTRA_DATE = "com.sudhirkhanger.android.criminalintent.date";
private Date mDate;
public static DatePickerFragment newInstance(Date date) {
Bundle args = new Bundle();
args.putSerializable(EXTRA_DATE, date);
DatePickerFragment fragment = new DatePickerFragment();
fragment.setArguments(args);
return fragment;
}
private void sendResult(int resultCode) {
if (getTargetFragment() == null)
return;
Intent i = new Intent();
i.putExtra(EXTRA_DATE, mDate);
getTargetFragment().onActivityResult(getTargetRequestCode(),
resultCode, i);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
mDate = (Date) getArguments().getSerializable(EXTRA_DATE);
// Create a Calendar to get the year, month, and day
final Calendar calendar = Calendar.getInstance();
// calendar.setTime(mDate);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
View v = getActivity().getLayoutInflater().inflate(
R.layout.dialog_date, null);
DatePicker datePicker = (DatePicker) v
.findViewById(R.id.dialog_date_datePicker);
datePicker.init(year, month, day, new OnDateChangedListener() {
public void onDateChanged(DatePicker view, int year, int month,
int day) {
// Translate year, month, day into a Date object using a
// calendar
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
mDate = new GregorianCalendar(year, month, day, hour, minute)
.getTime();
// Update argument to preserve selected value on rotation
getArguments().putSerializable(EXTRA_DATE, mDate);
}
});
return new AlertDialog.Builder(getActivity())
.setView(v)
.setTitle(R.string.date_picker_title)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
sendResult(Activity.RESULT_OK);
}
}).create();
}
}
The problem isn't with the communication between the Fragments, it's that for some reason the default CalendarView DatePicker in Lollipop never calls the OnDateChanged() method, so mDate in DatePickerFragment.java never gets changed; DatePickerFragment sends back to CrimeFragment the same value it received from CrimeFragment, so it only looks like the communication between the two Fragments isn't working.
The Lollipop DatePicker does call OnDateChanged() when it's in SpinnerView mode, so CrimeFragment's date will then get properly updated. Unfortunately, Lollipop ignores the android:calendarViewShown="false" directive in the DatePicker's tag in the dialog_date.xml file. The only way to force the DatePicker to display as spinners is to include a android:datePickerMode="spinner" directive in the DatePicker's xml tag. You will get a warning that this directive is supported in API 21 only, but it will be ignored by devices running pre-5.0 Android.You have to keep the calendarViewShown="false" directive for pre-5.0 devices.
DatePickerDialog appears to have been fixed in Android 5.0, so you could also use that resource in DatePickerFragment to make things work.

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

Getting data from a DatePickerDialog to a fragment

As above I am trying to work out how to pass back the date selected by the user. I have worked out how to get the date selected by using the onDateSet method but I do not know how to feed this back to the parent fragment, and then set the EditText text to the date selected.
package com.example.androidvehicle;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
public class fragmentServicing extends Fragment {
callBack mCallBack;
Button mot;
Button servicing;
Button tax;
EditText txtService;
final int Date_Dialog_ID=0;
int cDay,cMonth,cYear; // this is the instances of the current date
Calendar cDate;
int sDay,sMonth,sYear; // this is the instances of the entered date
int id_dialog = 1;
int yr, day, month = 0;
// interfacing back to activity
public interface callBack
{
public void onItemSelected(String id);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_servicing, container, false);
txtService = (EditText) view.findViewById(R.id.txtServiceDate);
mot = (Button) view.findViewById(R.id.buttonMOT);
servicing = (Button) view.findViewById(R.id.buttonService);
servicing.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// this will then pass back to the activity the string hello
mCallBack.onItemSelected("hello");
getActivity().showDialog(1);
}
});
mot.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getActivity().showDialog(1);
}
});
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallBack = (callBack) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
// this is an override for when the dialog is created
protected Dialog onCreateDialog(int id)
{
switch(id)
{
// this will return a date picker dialog if 1 is passed
// could use another number for another dialog
case 1:
// passes it the current date
return new DatePickerDialog(getActivity(), mDateSetListener, yr, month, day);
}
return null;
}
// this returns the date back that has been selected by the user
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
yr = year;
month = monthOfYear;
day = dayOfMonth;
Log.d("date selected", "year "+ yr+ " month " +month+" day "+day);
}
};
}
You can set DateListner on Edittext onClicklistner..
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
public class DateListener implements OnClickListener, OnDateSetListener {
private Activity activity;
private int year;
private int monthOfYear;
private int dayOfMonth;
private View touchedView;
public DateListener(Activity activity) {
this.activity = activity;
final Calendar c = Calendar.getInstance();
this.year = c.get(Calendar.YEAR);
this.monthOfYear = c.get(Calendar.MONTH);
this.dayOfMonth = c.get(Calendar.DAY_OF_MONTH);
}
public int getYear() {
return year;
}
public int getMonth() {
return monthOfYear;
}
public int getDay() {
return dayOfMonth;
}
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
this.year = year;
this.monthOfYear = monthOfYear + 1;
this.dayOfMonth = dayOfMonth;
updateDisplay();
updateEditText();
}
#Override
public void onClick(View v) {
touchedView = v;
new DatePickerDialog(activity,
this, this.getYear(), this.getMonth(), this.getDay()).show();
}
private void updateDisplay() {
((TextView) touchedView).setText(
new StringBuilder()
.append(pad(dayOfMonth)).append(".")
.append(pad(monthOfYear)).append(".")
.append(pad(year)));
}
private void updateEditText() {
((EditText) touchedView).setText(
new StringBuilder()
.append(pad(dayOfMonth)).append(".")
.append(pad(monthOfYear)).append(".")
.append(pad(year)));
}
private static String pad(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
}
In Your Fragment
DateListener dateListener = new DateListener(getActivity());
edittext.setOnClickListener(dateListener);

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.

Categories

Resources