What I have is a calendar widget which opens up when pressed and the user can select their dates from the calendar. I have variables to save the dates entered in inside the DateSetup class and I followed the code on using putExtra() to send the data from one class to another, but the values are not showing up.
The process of the application is when the dates have been selected, the user will then be able to select the times with the time picker widget which works.
After the dates and times have been selected, the values are sent to a MySQL database which the dates/times values should be shown. Only the selected times are showing but not the dates from the calendar selected.
DateSetup class
public class DateSetup extends MainActivity implements View.OnClickListener
{
//UI References
private EditText fromDateEtxt;
private EditText toDateEtxt;
// Dates Strings setup
String startDate;
String endDate;
DatePickerDialog fromDatePickerDialog;
DatePickerDialog toDatePickerDialog;
private SimpleDateFormat dateFormatter;
private DataDBAdapter2 Database;
Button btnHistory;
Button btnTime;
Button btnFuture;
Button btnManual;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.date_setup);
fromDateEtxt = (EditText) findViewById(R.id.etxt_fromdate);
fromDateEtxt.setInputType(InputType.TYPE_NULL);
fromDateEtxt.requestFocus();
toDateEtxt = (EditText) findViewById(R.id.etxt_todate);
toDateEtxt.setInputType(InputType.TYPE_NULL);
toDateEtxt.requestFocus();
btnTime = (Button)findViewById(R.id.btnSetDates);
btnFuture = (Button)findViewById(R.id.btnFutureSetups);
btnManual = (Button)findViewById(R.id.btnManualControl);
fromDateEtxt.setOnClickListener(this);
toDateEtxt.setOnClickListener(this);
// Open the database
Database = new DataDBAdapter2(this);
Database.open();
// Set the date format to English (Australia)
dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
btnHistory = (Button)findViewById(R.id.btnHistoryView);
btnHistory.setOnClickListener(this);
//-------------------------------------------
// Start Date (From date)
//-------------------------------------------
Calendar newCalendar = Calendar.getInstance();
fromDatePickerDialog = new DatePickerDialog(this, new OnDateSetListener()
{
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
fromDateEtxt.setText(dateFormatter.format(newDate.getTime()));
//startDate = fromDateEtxt.getText().toString();
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
//-------------------------------------------
// End Date (End date)
//-------------------------------------------
toDatePickerDialog = new DatePickerDialog(this, new OnDateSetListener()
{
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
toDateEtxt.setText(dateFormatter.format(newDate.getTime()));
//endDate = toDateEtxt.getText().toString();
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
// Set dates and continue to set times
btnTime.setOnClickListener(new View.OnClickListener()//OnClickListener()
{
#Override
public void onClick(View view)
{
// Start next activity
Intent i = new Intent(DateSetup.this, TimeSetup.class);
// Send data start data and End Date
//i.putExtra("START", startDate);
//i.putExtra("END", endDate);
i.putExtra("START", fromDateEtxt.getText().toString());
i.putExtra("END", toDateEtxt.getText().toString());
//i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
DateSetup.this.startActivity(i);
}
});
// History view
btnHistory.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v2)
{
Intent myIntent2 = new Intent(DateSetup.this, HistoryView.class);
myIntent2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
DateSetup.this.startActivity(myIntent2);
}
});
// Future Settings View
btnFuture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent myIntent3 = new Intent(DateSetup.this, CurrentView.class);
myIntent3.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
DateSetup.this.startActivity(myIntent3);
}
});
// Manual Control
btnManual.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent myIntent4 = new Intent(DateSetup.this, IrrigationControl.class);
myIntent4.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
DateSetup.this.startActivity(myIntent4);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.date_setup, menu);
//getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onClick(View view)
{
if(view == fromDateEtxt)
{
fromDatePickerDialog.show();
}
else if(view == toDateEtxt)
{
toDatePickerDialog.show();
}
}
}
TimeSetup2 class
public class TimeSetup2 extends TimeSetup
{
Button btnBck;
Button btnSetDatesandTime;
String minutedisplay2;
String hourdisplay2;
private DataDBAdapter2 Database;
private TimePicker timePicker2;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.time_setup2);
btnBck = (Button) findViewById(R.id.btnBack);
btnSetDatesandTime = (Button) findViewById(R.id.btnSet);
timePicker2 = (TimePicker)findViewById(R.id.timePicker2);
Database = new DataDBAdapter2(this);
Database.open();
// Back to previous activity
// http://stackoverflow.com/questions/4038479/android-go-back-to-previous-activity
btnBck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent myIntent = new Intent(TimeSetup2.this, TimeSetup.class);
TimeSetup2.this.startActivity(myIntent);
}
});
// Set time and dates
btnSetDatesandTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
// Generate random number for ID
Random r = new Random();
int i2 = r.nextInt(100-1) + 100;
// Convert from integer to string
String random2 = Integer.toString(i2);
//------------------------------------------------------
// Data from other classes to be sent to the database
//------------------------------------------------------
Intent intent = getIntent();
// Start Date and End date data
String StartD = intent.getStringExtra("START");
String EndD = intent.getStringExtra("END");
// Time Picker 1 Data (Working)
String StartTime1 = intent.getStringExtra("TIMEHOUR1");
String EndTime1 = intent.getStringExtra("TIMEMIN1");
// Time Picker 2 Data
//String StartTime2 = intent.getStringExtra("TIMEHOUR2");
//String EndTime2 = intent.getStringExtra("TIMEMIN2");
hourdisplay2 = timePicker2.getCurrentHour().toString();
minutedisplay2 = timePicker2.getCurrentMinute().toString();
// Send data to the Database
Database.insertData2(random2, StartD, EndD, StartTime1 + ":" + EndTime1, hourdisplay2 + ":" + minutedisplay2);
// Send data to the arduino board
// Show Message that the data has been sent
Toast.makeText(getApplicationContext(), "Irrigation Setups have been sent", Toast.LENGTH_LONG).show();
}
});
}
}
I've been stuck on trying to solve this problem for days. It's probably something really simple I'm missing out but I can't figure it out.
The only data types that are OS-friendly are primitive types (int, long, float, boolean, etc...), so that means that putExtra() allows you to store primitives only. That's why you cant send a Calendar object.
Try to send a String of your period to your next activity.
Related
I am working on a simple app in which i have taken two date pickers they subtract two dates and display the result. But i want that if the two dates are same like 06/04/2017 then two radio button should pop up for selecting full day and half day as soon as it calculates that the two dates are same.
how to do that?
public class Leave extends AppCompatActivity {
TextView date;
private DatePickerDialog datePickerDialog;
TextView date2;
//TextView setDay;
private DatePickerDialog datePickerDialog2;
TextView no_of_days;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_leave);
date = (TextView) findViewById(R.id.date);
date2 = (TextView) findViewById(R.id.date2);
//setDay = (TextView) findViewById(R.id.setDay);
no_of_days = (TextView) findViewById(R.id.no_of_days);
// initiate the date picker and a button
date = (TextView) findViewById(R.id.date);
// perform click event on edit text
date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// calender class's instance and get current date , month and year from calender
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR); // current year
int mMonth = c.get(Calendar.MONTH); // current month
int mDay = c.get(Calendar.DAY_OF_MONTH); // current day
// date picker dialog
datePickerDialog = new DatePickerDialog(Leave.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// set day of month , month and year value in the edit text
date.setText(dayOfMonth + "/"
+ (monthOfYear + 1) + "/" + year);
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
});
// initiate the date picker and a button
date2 = (TextView) findViewById(R.id.date2);
// perform click event on edit text
date2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// calender class's instance and get current date , month and year from calender
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR); // current year
int mMonth = c.get(Calendar.MONTH); // current month
int mDay = c.get(Calendar.DAY_OF_MONTH); // current day
// date picker dialog
datePickerDialog2 = new DatePickerDialog(Leave.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// set day of month , month and year value in the edit text
date2.setText(dayOfMonth + "/"
+ (monthOfYear + 1) + "/" + year);
}
}, mYear, mMonth, mDay);
datePickerDialog2.show();
}
});
no_of_days.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SimpleDateFormat format = new SimpleDateFormat("dd/mm/yyyy");
String date01 = date.getText().toString();
String date02 = date2.getText().toString();
try {
Date d = format.parse(date01);
Date d1 = format.parse(date02);
getDifferenceDays(d, d1);
} catch (ParseException e) {
e.printStackTrace();
}
}
});
Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.leave_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
}
public class SpinnerActivity extends Activity implements AdapterView.OnItemSelectedListener {
SpinnerActivity() throws ParseException {
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
Spinner spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
}
}
private void setupRadios() {
RadioButton radio_full = (RadioButton) findViewById(R.id.radio_full);
RadioButton radio_Half = (RadioButton) findViewById(R.id.radio_Half);
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioleave);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
int buttonId = radioGroup.getCheckedRadioButtonId();
switch (buttonId) {
case R.id.radio_full:
Toast.makeText(getApplicationContext(), "You have selected Full Day Leave", Toast.LENGTH_SHORT).show();
break;
case R.id.radio_Half:
Toast.makeText(getApplicationContext(), "You have selected Half Day Leave", Toast.LENGTH_SHORT).show();
break;
}
}
});
}
public void getDifferenceDays(Date d1, Date d2) {
int daysdiff = 0;
long diff = d2.getTime() - d1.getTime();
long diffDays = diff / (24 * 60 * 60 * 1000) + 1;
daysdiff = (int) diffDays;
no_of_days.setText(Integer.toString(daysdiff));
System.out.println("day count=>" + daysdiff);
}
}
Compare the dates whenever any date is selected from any one of the date picker's as follows :
public class Leave extends AppCompatActivity {
TextView date;
private DatePickerDialog datePickerDialog;
TextView date2;
//TextView setDay;
private DatePickerDialog datePickerDialog2;
TextView no_of_days;
String date1 = "", date2 = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_leave);
date = (TextView) findViewById(R.id.date);
date2 = (TextView) findViewById(R.id.date2);
//setDay = (TextView) findViewById(R.id.setDay);
no_of_days = (TextView) findViewById(R.id.no_of_days);
RadioButton radio_full = (RadioButton) findViewById(R.id.radio_full);
RadioButton radio_Half = (RadioButton) findViewById(R.id.radio_Half);
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioleave);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
int buttonId = radioGroup.getCheckedRadioButtonId();
switch (buttonId) {
case R.id.radio_full:
Toast.makeText(getApplicationContext(), "You have selected Full Day Leave", Toast.LENGTH_SHORT).show();
break;
case R.id.radio_Half:
Toast.makeText(getApplicationContext(), "You have selected Half Day Leave", Toast.LENGTH_SHORT).show();
break;
}
}
});
// initially hide the radio buttons
radio_full.setVisibility(View.GONE);
radio_Half.setVisibility(View.GONE);
// initiate the date picker and a button
date = (TextView) findViewById(R.id.date);
// perform click event on edit text
date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// calender class's instance and get current date , month and year from calender
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR); // current year
int mMonth = c.get(Calendar.MONTH); // current month
int mDay = c.get(Calendar.DAY_OF_MONTH); // current day
// date picker dialog
datePickerDialog = new DatePickerDialog(Leave.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// set day of month , month and year value in the edit text
// assign the value to date1
date1 = dayOfMonth + "/"
+ (monthOfYear + 1) + "/" + year;
date.setText(dayOfMonth + "/"
+ (monthOfYear + 1) + "/" + year);
// check if date2 has been set and compare it with date1
if(!TextUtils.isEmpty(date2)) {
// get difference
getDifferenceDays(date, date2);
if(date1.equals(date2)) {
// pop up radio button
radio_full.setVisibility(View.VISIBLE);
radio_Half.setVisibility(View.VISIBLE);
} else {
// hide radio buttons
radio_full.setVisibility(View.GONE);
radio_Half.setVisibility(View.GONE);
}
}
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
});
// initiate the date picker and a button
date2 = (TextView) findViewById(R.id.date2);
// perform click event on edit text
date2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// calender class's instance and get current date , month and year from calender
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR); // current year
int mMonth = c.get(Calendar.MONTH); // current month
int mDay = c.get(Calendar.DAY_OF_MONTH); // current day
// date picker dialog
datePickerDialog2 = new DatePickerDialog(Leave.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// set day of month , month and year value in the edit text
// assign the value to date2
date2 = dayOfMonth + "/"
+ (monthOfYear + 1) + "/" + year;
date2.setText(dayOfMonth + "/"
+ (monthOfYear + 1) + "/" + year);
// check if date2 has been set and compare it with date1
if(!TextUtils.isEmpty(date1)) {
// get difference
getDifferenceDays(date, date2);
if(date1.equals(date2)) {
// pop up radio button
radio_full.setVisibility(View.VISIBLE);
radio_Half.setVisibility(View.VISIBLE);
} else {
// hide radio buttons
radio_full.setVisibility(View.GONE);
radio_Half.setVisibility(View.GONE);
}
}
}
}, mYear, mMonth, mDay);
datePickerDialog2.show();
}
});
no_of_days.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SimpleDateFormat format = new SimpleDateFormat("dd/mm/yyyy");
String date01 = date.getText().toString();
String date02 = date2.getText().toString();
try {
Date d = format.parse(date01);
Date d1 = format.parse(date02);
getDifferenceDays(d, d1);
} catch (ParseException e) {
e.printStackTrace();
}
}
});
Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.leave_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
}
I had already tried the first two suggestions below, but I tried again and sincerely thanks for the help! The result is the same though. I´ll just edit the post to add more code info.
Hello there! I´m experimenting with a simple ToDo application and managed to change almost everything I wanted besides the date formatted that´s displayed once the user saves the task.
The task itself is added via the AddToDoActivity class which has the following resumed code:
public class AddToDoActivity extends Activity {
// 7 days in milliseconds - 7 * 24 * 60 * 60 * 1000
private static final int SEVEN_DAYS = 604800000;
private static final String TAG = "Lab-UserInterface";
private static String timeString;
private static String dateString;
private static TextView dateView;
private static TextView timeView;
private Date mDate;
private RadioGroup mPriorityRadioGroup;
private RadioGroup mStatusRadioGroup;
private EditText mTitleText;
private RadioButton mDefaultStatusButton;
private RadioButton mDefaultPriorityButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_todo);
mTitleText = (EditText) findViewById(R.id.title);
mDefaultStatusButton = (RadioButton) findViewById(R.id.statusNotDone);
mDefaultPriorityButton = (RadioButton) findViewById(R.id.medPriority);
mPriorityRadioGroup = (RadioGroup) findViewById(R.id.priorityGroup);
mStatusRadioGroup = (RadioGroup) findViewById(R.id.statusGroup);
dateView = (TextView) findViewById(R.id.date);
timeView = (TextView) findViewById(R.id.time);
// Set the default date and time
setDefaultDateTime();
// OnClickListener for the Date button, calls showDatePickerDialog() to show
// the Date dialog
final Button datePickerButton = (Button) findViewById(R.id.date_picker_button);
datePickerButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDatePickerDialog();
}
});
// OnClickListener for the Time button, calls showTimePickerDialog() to show
// the Time Dialog
final Button timePickerButton = (Button) findViewById(R.id.time_picker_button);
timePickerButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showTimePickerDialog();
}
});
// OnClickListener for the Cancel Button,
final Button cancelButton = (Button) findViewById(R.id.cancelButton);
cancelButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
log("Entered cancelButton.OnClickListener.onClick()");
finish();
}
});
//OnClickListener for the Reset Button
final Button resetButton = (Button) findViewById(R.id.resetButton);
resetButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
log("Entered resetButton.OnClickListener.onClick()");
setDefaultDateTime();
mTitleText.setText("");
mDefaultStatusButton.setChecked(true);
mDefaultPriorityButton.setChecked(true);
}
});
// OnClickListener for the Submit Button
// Implement onClick().
final Button submitButton = (Button) findViewById(R.id.submitButton);
submitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
log("Entered submitButton.OnClickListener.onClick()");
// Gather ToDoItem data
Priority priority = getPriority();
Status status = getStatus();
String titleString = mTitleText.getText().toString();
// Date
String fullDate = dateString + " " + timeString;
// Package ToDoItem data into an Intent
Intent data = new Intent();
ToDoItem.packageIntent(data, titleString, priority, status, fullDate);
setResult(Activity.RESULT_OK, data);
finish();
}
});
}
// Do not modify below here
// Use this method to set the default date and time
private void setDefaultDateTime() {
// Default is current time + 7 days
mDate = new Date();
mDate = new Date(mDate.getTime() + SEVEN_DAYS);
Calendar c = Calendar.getInstance();
c.setTime(mDate);
setDateString(c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.MONTH),
c.get(Calendar.YEAR));
dateView.setText(dateString);
setTimeString(c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE),
c.get(Calendar.MILLISECOND));
timeView.setText(timeString);
}
private static void setDateString(int dayOfMonth, int monthOfYear, int year) {
// Increment monthOfYear for Calendar/Date -> Time Format setting
monthOfYear++;
String mon = "" + monthOfYear;
String day = "" + dayOfMonth;
if (monthOfYear < 10)
mon = "0" + monthOfYear;
if (dayOfMonth < 10)
day = "0" + dayOfMonth;
dateString = year + "-" + mon + "-" + day;
}
private static void setTimeString(int hourOfDay, int minute, int mili) {
String hour = "" + hourOfDay;
String min = "" + minute;
if (hourOfDay < 10)
hour = "0" + hourOfDay;
if (minute < 10)
min = "0" + minute;
timeString = hour + ":" + min + ":00";
}
private Priority getPriority() {
switch (mPriorityRadioGroup.getCheckedRadioButtonId()) {
case R.id.lowPriority: {
return Priority.LOW;
}
case R.id.highPriority: {
return Priority.HIGH;
}
default: {
return Priority.MED;
}
}
}
private Status getStatus() {
switch (mStatusRadioGroup.getCheckedRadioButtonId()) {
case R.id.statusDone: {
return Status.DONE;
}
default: {
return Status.NOTDONE;
}
}
}
// DialogFragment used to pick a ToDoItem deadline date
public static class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int day = c.get(Calendar.DAY_OF_MONTH);
int month = c.get(Calendar.MONTH);
int year = c.get(Calendar.YEAR);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
#Override
public void onDateSet(DatePicker view, int dayOfMonth, int monthOfYear,
int year) {
setDateString(dayOfMonth, monthOfYear, year);
dateView.setText(dateString);
}
}
// DialogFragment used to pick a ToDoItem deadline time
public static class TimePickerFragment extends DialogFragment implements
TimePickerDialog.OnTimeSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return
return new TimePickerDialog(getActivity(), this, hour, minute,
true);
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
setTimeString(hourOfDay, minute, 0);
timeView.setText(timeString);
}
}
private void showDatePickerDialog() {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
}
private void showTimePickerDialog() {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "timePicker");
}
private void log(String msg) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i(TAG, msg);
}
}
Here´s the ToDoItem, that actually reads the info from AddToDoActivity:
public class ToDoItem {
public static final String ITEM_SEP = System.getProperty("line.separator");
public enum Priority {
LOW, MED, HIGH
};
public enum Status {
NOTDONE, DONE
};
public final static String TITLE = "title";
public final static String PRIORITY = "priority";
public final static String STATUS = "status";
public final static String DATE = "date";
public final static String FILENAME = "filename";
public final static SimpleDateFormat FORMAT = new SimpleDateFormat(
"dd/MM/yyyy HH:mm:ss", Locale.US);
private String mTitle = new String();
private Priority mPriority = Priority.LOW;
private Status mStatus = Status.NOTDONE;
private Date mDate = new Date();
ToDoItem(String title, Priority priority, Status status, Date date) {
this.mTitle = title;
this.mPriority = priority;
this.mStatus = status;
this.mDate = date;
}
// Create a new ToDoItem from data packaged in an Intent
ToDoItem(Intent intent) {
mTitle = intent.getStringExtra(ToDoItem.TITLE);
mPriority = Priority.valueOf(intent.getStringExtra(ToDoItem.PRIORITY));
mStatus = Status.valueOf(intent.getStringExtra(ToDoItem.STATUS));
try {
mDate = ToDoItem.FORMAT.parse(intent.getStringExtra(ToDoItem.DATE));
} catch (ParseException e) {
mDate = new Date();
}
}
public String getTitle() {
return mTitle;
}
public void setTitle(String title) {
mTitle = title;
}
public Priority getPriority() {
return mPriority;
}
public void setPriority(Priority priority) {
mPriority = priority;
}
public Status getStatus() {
return mStatus;
}
public void setStatus(Status status) {
mStatus = status;
}
public Date getDate() {
return mDate;
}
public void setDate(Date date) {
mDate = date;
}
// Take a set of String data values and
// package them for transport in an Intent
public static void packageIntent(Intent intent, String title,
Priority priority, Status status, String date) {
intent.putExtra(ToDoItem.TITLE, title);
intent.putExtra(ToDoItem.PRIORITY, priority.toString());
intent.putExtra(ToDoItem.STATUS, status.toString());
intent.putExtra(ToDoItem.DATE, date);
}
public String toString() {
return mTitle + ITEM_SEP + mPriority + ITEM_SEP + mStatus + ITEM_SEP
+ FORMAT.format(mDate);
}
public String toLog() {
return "Title:" + mTitle + ITEM_SEP + "Priority:" + mPriority
+ ITEM_SEP + "Status:" + mStatus + ITEM_SEP + "Date:"
+ FORMAT.format(mDate);
}
}
Oh well, after hours tweaking the
public final static SimpleDateFormat FORMAT = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss", Locale.US);
method from ToDoItem, I still cannot successfully convert yyyy-MM-dd to dd/MM/yyyy.
First, I´ve tried the obvious, and changed the expression yyyy-MM-dd to dd/MM/yyyy.
After that, all I got after saving the task was today´s date, even though the date inputted on AddToDoActivity is months or years ahead. If I revert back to yyyy-MM-dd, the date shown on the Task List is the same inputted on AddToDoActivity.
Then I tried to change all mentions of dates on every class to match the exact format that I wanted.
That made everything look good on AddToDoActivity, but again, when I transported the date back to ToDoItem, the app just ignored the previously inputted date and showed today´s date again.
Can anyone help me with this one??
Thanks!!
You are calling setDateString with arguments in the order of year, month, day:
setDateString(c.get(Calendar.YEAR), c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH));
But your method has parameters in the order of day, month, year:
private static void setDateString(int dayOfMonth, int monthOfYear, int year) {
...
}
I also think you made some errors while copying your code into the question, since the setDateString method is duplicated and there is no setTimeString method.
Change:
setDateString(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
to:
setDateString(c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.MONTH), c.get(Calendar.YEAR));
Modify the code as follows in the ToDoListAdapter file getView method
// TODO - Display Time and Date.
// Hint - use ToDoItem.FORMAT.format(toDoItem.getDate()) to get date and time String
final TextView dateView = (TextView) itemLayout.findViewById(R.id.dateView);
dateView.setText(ToDoItem.FORMAT.format(toDoItem.getDate()));
The output will be something similar the the following
Reference:
Completing UI Activity assignment
I have implemented a date picker as following.
private void updateDisplay() {
String str_date = "";
if ((Month + 1) >= 10) {
if (Day < 10) {
str_date = Year + "-" + (Month + 1) + "-0" + Day;
} else {
str_date = Year + "-" + (Month + 1) + "-" + Day;
}
} else {
if (Day < 10) {
str_date = Year + "-0" + (Month + 1) + "-0" + Day;
} else {
str_date = Year + "-0" + (Month + 1) + "-" + Day;
}
}
date.setText("" + str_date);
}
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case DATE_DIALOG_ID:
((DatePickerDialog) dialog).updateDate(Year, Month, Day);
break;
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(viewLoad.getContext(),
mDateSetListener, Year, Month, Day);
}
return null;
}
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
Year = year;
Month = monthOfYear;
Day = dayOfMonth;
updateDisplay();
}
};
Here is my code segment for button.
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnDate:
showDialog(DATE_DIALOG_ID);
break;
This works fine. Now the problem is I need to implement a date picker in a fragment. Can anyone plz explain how to do it.
Edited Code
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
Year = year;
Month = monthOfYear;
Day = dayOfMonth;
updateDisplay();
}
};
Thanx in advance.
Use this CustomDialogFragment that contains use of
TimePicker Dialog fragment
DatePicker Dialog fragment
Simple Dialog Fragment
CustomeDialogFragment Class
public class CustomDialogFragment extends DialogFragment
{
public static final int DATE_PICKER = 1;
public static final int TIME_PICKER = 2;
public static final int DIALOG = 3;
Context mContext;
String mMessage;
boolean finishActivity;
// private Fragment mCurrentFragment;
Activity mActivity;
/**
* this constructor is used for datepicker & Timepicker
*/
public CustomDialogFragment (Fragment fragment ) {
// mCurrentFragment = fragment;
}
public CustomDialogFragment (Activity mActivity ) {
this.mActivity = mActivity;
}
/**
* this constructor is used for simple dialog fragment
*/
public CustomDialogFragment(Context context, String message, final boolean finishActivity) {
mContext = context;
mMessage = message;
this.finishActivity = finishActivity;
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
Bundle bundle = new Bundle();
bundle = getArguments();
int id = bundle.getInt("dialog_id");
switch (id) {
case DATE_PICKER:
return new DatePickerDialog(getActivity(),
(OnDateSetListener)mActivity, bundle.getInt("year"),
bundle.getInt("month"), bundle.getInt("day"));
case TIME_PICKER:
return new TimePickerDialog(getActivity(),
(OnTimeSetListener)mActivity,bundle.getInt("hour"),
bundle.getInt("minute"), true);
case DIALOG:
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext);
alertDialogBuilder.setTitle(R.string.app_name);
alertDialogBuilder.setMessage(mMessage);
alertDialogBuilder.setIcon(R.drawable.ic_launcher);
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setPositiveButton(
getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int arg1) {
dialog.dismiss();
if (finishActivity == true) {
Activity act = (Activity) mContext;
act.finish();
}
}
});
alertDialogBuilder.setNegativeButton(getResources().getString(R.string.cancel_btn_title), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
CustomDialogFragment.this.dismiss();
}
});
return alertDialogBuilder.create();
}
//Define your custom dialog or alert dialog here and return it.
return new Dialog(getActivity());
}
}
& Use date Picker this Way
1) In your Activity Or fragment Implement OnDateSetListener ( after done it will get back result to onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) method)
2) Call DatePicker From Fragment Like this way
CustomDialogFragment dialog = new CustomDialogFragment(YourFragment.this);
Bundle bundle = new Bundle();
bundle.putInt("dialog_id", CustomDialogFragment.DATE_PICKER);
bundle.putInt("year", mYear);
bundle.putInt("month", mMonth);
bundle.putInt("day", mDay);
dialog.setArguments(bundle);
dialog.show(getFragmentManager(), "dialog");
& Call DatePicker From Activity(or FragmentActivity) Like this Way
CustomDialogFragment dialog = new CustomDialogFragment(this);
Bundle bundle = new Bundle();
bundle.putInt("dialog_id", CustomDialogFragment.DATE_PICKER);
bundle.putInt("year", mYear);
bundle.putInt("month", mMonth);
bundle.putInt("day", mDay);
dialog.setArguments(bundle);
dialog.setCancelable(false);
dialog.show(this.getSupportFragmentManager(), "dialog");
& as per Set "dialog_id" u can use TIME_PICKER (for time picker dialog) & DIALOG(for simple dialog)
as per send "dialog_id" according to send data through bundle to CustomDialogFragment.
As my knowledge, cannot use showDialog() in Fragment. It's also deprecated.
Use DialogFragment.
Learn from this tutorial as you need
http://www.kylebeal.com/2011/11/android-datepickerdialog-and-the-dialogfragment/
Hi i added this piece of code to my Android app and it suddenly stopped working(it wont start). I am trying the make sure hat the user is not allowed to proceed if a return date less then the departure date is selected.
String departureDateTemp = dYear+ ""+ ""+dMonth + ""+dDay;
int departureDateTemp2 = Integer.parseInt(departureDateTemp);
String returnDateTemp = rYear+ ""+ ""+rMonth + ""+rDay;
int returnDateTemp2 = Integer.parseInt(returnDateTemp);
if(returnDateTemp2 >= departureDateTemp2){
//MESSAGE
if(buttonR.isChecked()){
String returnDate = txR.getText().toString();
basket.putString("returnDate", returnDate);
type = "Return";
}
else{
type = "Oneway";
}
}
else{
btnSubmit.setEnabled(false);
}
My Full activity is this
public class MainActivity extends FragmentActivity {
private int dYear;
private int dMonth;
private int dDay;
private int rYear;
private int rMonth;
private int rDay;
static final int dDATE_DIALOG_ID = 0;
static final int rDATE_DIALOG_ID = 1;
private RadioButton buttonO = null;
private RadioButton buttonR = null;
private TableRow tr;
TextView txD, txR;
private Button btnDepart,btnReturn, btnSubmit,btnClose;
private Spinner noOfPassengersSpinner,departureSpinner,returnSpinner;
private CheckBox tandCCB;
final Context context = this;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonO = (RadioButton) findViewById(R.id.radioO);
buttonR = (RadioButton) findViewById(R.id.radioR);
txD=(TextView)findViewById(R.id.tvDepartureDate);
txR=(TextView)findViewById(R.id.tvReturnDate);
btnDepart = (Button)findViewById(R.id.btnDepart);
btnReturn = (Button)findViewById(R.id.btnReturn);
tr = (TableRow)findViewById(R.id.tableRow5);
btnSubmit = (Button)findViewById(R.id.btnSubmit);
btnClose = (Button)findViewById(R.id.btnClose);
noOfPassengersSpinner = (Spinner)findViewById(R.id.noOfPassengersSpinner);
departureSpinner = (Spinner)findViewById(R.id.departureSpinner);
returnSpinner = (Spinner)findViewById(R.id.returnSpinner);
tandCCB = (CheckBox)findViewById(R.id.tandCCB);
final Calendar dC = Calendar.getInstance();
final Calendar rC = Calendar.getInstance();
dYear = dC.get(Calendar.YEAR);
dMonth = dC.get(Calendar.MONTH);
dDay = dC.get(Calendar.DAY_OF_MONTH);
rYear = rC.get(Calendar.YEAR);
rMonth = rC.get(Calendar.MONTH);
rDay = rC.get(Calendar.DAY_OF_MONTH);
updateDisplay();
tandCCB.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if(isChecked){
btnSubmit.setEnabled(true);
}
else{
btnSubmit.setEnabled(false);
}
}
});
this.btnClose.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
finish();
System.exit(0);
}
});
this.btnSubmit.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
String depAir = departureSpinner.getSelectedItem().toString();
String desAir = returnSpinner.getSelectedItem().toString();
int numOfPass = Integer.parseInt(noOfPassengersSpinner.getSelectedItem().toString());
Bundle basket = new Bundle();
basket.putString("departureAir", depAir);
basket.putString("destenationAir", desAir);
basket.putInt("numOfPass", numOfPass);
basket.putString("depDate", txD.getText().toString());
String type = "";
String departureDateTemp = dYear+ ""+ ""+dMonth + ""+dDay;
int departureDateTemp2 = Integer.parseInt(departureDateTemp);
String returnDateTemp = rYear+ ""+ ""+rMonth + ""+rDay;
int returnDateTemp2 = Integer.parseInt(returnDateTemp);
if(returnDateTemp2 >= departureDateTemp2){
//MESSAGE
if(buttonR.isChecked()){
String returnDate = txR.getText().toString();
basket.putString("returnDate", returnDate);
type = "Return";
}
else{
type = "Oneway";
}
}
else{
btnSubmit.setEnabled(false);
}
basket.putString("type", type);
Intent intent = new Intent(context, Second.class);
intent.putExtra("basket", basket);
startActivity(intent);
}
});
this.buttonO.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
tr.setVisibility(View.GONE);
}
});
this.buttonR.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
tr.setVisibility(View.VISIBLE);
}
});
this.btnDepart.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
showDialog(dDATE_DIALOG_ID);
}
});
this.btnReturn.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
showDialog(rDATE_DIALOG_ID);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private void updateDisplay() {
txD.setText(
new StringBuilder()
// Month is 0 based so add 1
.append(dYear).append("-")
.append(dMonth + 1).append("-")
.append(dDay).append(" ")
);
txR.setText(
new StringBuilder()
.append(rYear).append("-")
.append(rMonth + 1).append("-")
.append(rDay).append(" ")
);
}
private DatePickerDialog.OnDateSetListener dDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
dYear = year;
dMonth = monthOfYear;
dDay = dayOfMonth;
updateDisplay();
}
};
private DatePickerDialog.OnDateSetListener rDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
rYear = year;
rMonth = monthOfYear;
rDay = dayOfMonth;
updateDisplay();
}
};
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case dDATE_DIALOG_ID:
return new DatePickerDialog(this,
dDateSetListener,
dYear, dMonth, dDay);
case rDATE_DIALOG_ID:
return new DatePickerDialog(this,
rDateSetListener,
rYear, dMonth, rDay);
}
return null;
}
}
This is my console output
[2013-04-26 13:37:44 - Assignment2] ------------------------------
[2013-04-26 13:37:44 - Assignment2] Android Launch!
[2013-04-26 13:37:44 - Assignment2] adb is running normally.
[2013-04-26 13:37:44 - Assignment2] Performing com.example.assignment2.MainActivity activity launch
[2013-04-26 13:37:44 - Assignment2] Automatic Target Mode: using existing emulator 'emulator-5554' running compatible AVD 'tester'
[2013-04-26 13:37:44 - Assignment2] Uploading Assignment2.apk onto device 'emulator-5554'
[2013-04-26 13:37:46 - Assignment2] Installing Assignment2.apk...
[2013-04-26 13:37:49 - Assignment2] Re-installation failed due to different application signatures.
[2013-04-26 13:37:49 - Assignment2] You must perform a full uninstall of the application. WARNING: This will remove the application data!
[2013-04-26 13:37:49 - Assignment2] Please execute 'adb uninstall com.example.assignment2' in a shell.
[2013-04-26 13:37:49 - Assignment2] Launch canceled!
Thanks in advance!
Go to your emulator settings, uninstall your app and reinstall again.
Just run coomand as wrote in your output
adb uninstall com.example.assignment2
from command line
And be shure that you have adb in your PATH enviroment, anyway you can find adb in android-sdk/platform-tools folder
And restart/rerun yor project from your IDE
In my Android application i have a tracker activity in which i retrieve the exercises information(name , period , burned calories) from the sqlite data base based on the selected date and display these information in a linear layout , and my problem that as the user select new date the retrieved data are displayed in another "new " layout appear above the old one but what actually i want to do is to display the new retrieved data on the same layout " change the layout content with the new retrieved data ", i have tried the remove all views method but it didn't work since the data appear for few minutes then dis appear
How i can do this: when the user select a new date the new retrieved data displayed on the same layout " refresh the old data by the new one " not to display them in anew layout . how i can do that ? please help me...
java code
public class Tracker extends BaseActivity
{
private Button date_btn;
private ImageButton left_btn;
private ImageButton right_btn;
private ImageView nodata;
private TextView ex_name;
private TextView ex_BCals;
private LinearLayout excercises_LL;
private LinearLayout content_LL ;
private LinearLayout notes;
private LinearLayout details;
private int year,month,day;
private double tot_excals_burned;
private Calendar localCalendar;
private static final int DATE_DIALOG_ID=0;
private boolean has_ex_details;
private boolean has_meal_details=false;
private Cursor exercises_cursor;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.tracker);
date_btn=(Button)findViewById(R.id.btn_date);
date_btn.setText(FormatDate());
date_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
localCalendar = Calendar.getInstance();
year = localCalendar.get(1);
month= localCalendar.get(2);
day = localCalendar.get(5);
showDialog(DATE_DIALOG_ID);
}
});
left_btn=(ImageButton)findViewById(R.id.btn_left);
left_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
localCalendar.add(5, -1);
date_btn.setText(FormatDate(localCalendar,"EEEE, d/MMM/yyyy"));
RefreshExercisesData();
RefreshNoDataImage();
}
});
right_btn=(ImageButton)findViewById(R.id.btn_right) ;
right_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
localCalendar.add(5, 1);
date_btn.setText(FormatDate(localCalendar,"EEEE, d/MMM/yyyy"));
RefreshExercisesData();
RefreshNoDataImage();
}
});
details=(LinearLayout)findViewById(R.id.ll_details);
notes=(LinearLayout)findViewById(R.id.ll_notes);
excercises_LL=(LinearLayout)findViewById(R.id.ll_exercises);
nodata=(ImageView)findViewById(R.id.nodata_imgV);
RefreshExercisesData();
RefreshNoDataImage();
}
private String FormatDate()
{
localCalendar = Calendar.getInstance();
return new SimpleDateFormat("EEEE, d/MMM/yyyy").format(localCalendar.getTime());
}
private String FormatDate(int year, int month, int day)
{
localCalendar = Calendar.getInstance();
localCalendar.set(year, month, day);
return new SimpleDateFormat("EEEE, d/MMM/yyyy").format(localCalendar.getTime());
}
private String FormatDate(Calendar calendar , String format)
{
return new SimpleDateFormat(format).format(calendar.getTime());
}
private void RefreshExercisesData()
{
tot_excals_burned=0;
DBAdapter db = new DBAdapter(this);
db.open();
String selected_date= date_btn.getText().toString();
Log.e("date", selected_date);
exercises_cursor = db.getExerciseInfo(selected_date);
if(exercises_cursor.getCount() !=0 )
{
has_ex_details=true;
details.setVisibility(0);
nodata.setVisibility(8);
notes.setVisibility(0);
//excercises_LL.removeAllViews();
excercises_LL.setWeightSum(1.0F);
excercises_LL.setVisibility(0);
excercises_LL.setOrientation(LinearLayout.VERTICAL);
LayoutInflater exc_LayoutInflater = (LayoutInflater)getApplicationContext().getSystemService("layout_inflater");
LinearLayout layout = (LinearLayout)exc_LayoutInflater.inflate(R.layout.tracker_header_item,null);
TextView tot_ex_cals_value=((TextView)(layout).findViewById(R.id.tv_tot_cals_value));
TextView exs_title=((TextView)(layout).findViewById(R.id.tv_item_title)) ;
exs_title.setText("Exercises ");
(layout).setPadding(0, 36, 0, 0);
excercises_LL.addView((View)layout, 0);
int i = 1;
if (exercises_cursor.moveToFirst())
{
do
{
content_LL=new LinearLayout(this);
ex_name=new TextView(this);
ex_name.setText( exercises_cursor.getFloat(1)+"," +exercises_cursor.getString(0) + "min ");
ex_name.setTextColor(R.color.black);
content_LL.addView(ex_name,0);
ex_BCals=new TextView(this);
ex_BCals.setText(Round(exercises_cursor.getFloat(2)) +" ");
ex_BCals.setTextColor(R.color.color_black);
content_LL.addView(ex_BCals,1);
tot_excals_burned = tot_excals_burned+exercises_cursor.getFloat(2);
excercises_LL.addView(content_LL, i);
i++;
}
while (exercises_cursor.moveToNext());
}
tot_ex_cals_value.setText(Round(tot_excals_burned) );
}
else if(exercises_cursor.getCount()==0 ||tot_excals_burned==0)
{
has_ex_details=false;
RefreshNoDataImage();
}
exercises_cursor.close();
exercises_cursor.deactivate();
db.close();
}
private void RefreshNoDataImage()
{
if(has_ex_details==false && has_meal_details==false)
{
notes.setVisibility(8);
excercises_LL.setVisibility(8);
nodata.setImageResource(R.drawable.bg_nodata);
nodata.setVisibility(View.VISIBLE);
}
else
nodata.setVisibility(8);
}
protected Dialog onCreateDialog(int id)
{
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, mDateSetListener, this.year, this.month, this.day);
}
return null;
}
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener()
{
public void onDateSet(DatePicker paramDatePicker, int year, int monthofYear, int dayofMonth)
{
Tracker.this.year=year;
month=monthofYear;
day=dayofMonth;
date_btn.setText(FormatDate(year,month,day));
RefreshExercisesData();
RefreshNoDataImage();
}
};
private String Round(double num) {
return String.format("%.1f%n", num);
}}
Its because you defined these variables as static:
public static int icon;
public static String data_text;
public static String text;
As a result only one instance of those variables are created for all instances of that class. So when you create a new Profile each time, they are overwritten with new values. You need to remove the static keyword from variable declarations:
public int icon;
public String data_text;
public String text;
Then you cannot access them as static so you need to access like this:
Profile pli = data[position];
holder.imgIcon.setImageResource(pli.icon);
holder.Datatxt.setText(pli.data_text);
holder.txt.setText(pli.text);
Check out this if you want to learn more about static: http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html