Android - Add new buttons in listview dynamically - android

I've a Listview with two linear layouts and there is one button add new row . When i click add new row button i want to create new row of buttons dynamically. After that click on that created button i want to show an time picker dialog . When user click set time button i want to set that time in that button. My problem is All the buttons(with different id) are added fine and when click that button time picker dialog was pop up. But after click set time button the time will not set . How can i add this time to the button. How can i handle this button ?
It is my piece of code inside of listview onscroll listener
final LinearLayout l1 = LinearLayout) List_Layout.getChildAt(0);
LinearLayout l12 = (LinearLayout) List_Layout.getChildAt(1);
final Button button = new Button(getApplicationContext());
final Button button1 = new Button(getApplicationContext());
add_button.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
button.setLayoutParams(lparams);
button1.setLayoutParams(lparams);
button.setId(0);
button1.setId(1);
l1.addView(button, lparams);
l12.addView(button1, lparams);
}
}
button.setOnClickListener(new OnClickListener()
{
#SuppressWarnings("deprecation")
public void onClick(View v)
{
showDialog(TIME_DIALOG_ID);
}
}
button1.setOnClickListener(new OnClickListener()
{
#SuppressWarnings("deprecation")
public void onClick(View v)
{
// TODO Auto-generated method stub
Log.e("tag 1", button1.getTag()+"");
showDialog(TIME_DIALOG_ID);
}
});
Rest of the codes for timepicker dialog is works fine
It's just sample code
Please anyone help me get out from this riddle.
Edit:
static final int TIME_DIALOG_ID = 998;
private int hour;
private int minute;
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG_ID:
return new TimePickerDialog(this,
timePickerListener, hour, minute,false);
}
return null;
}
private TimePickerDialog.OnTimeSetListener timePickerListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int selectedHour,
int selectedMinute) {
hour = selectedHour;
minute = selectedMinute;
}
}

You need to set text of button or button1 to the time that was actually picked by the user. To do so, code some button.setText(<formatted time>) in the timePickerListener.
Here's some line of code, I use to format date and time from a java.util.Date object:
Date date = new Date();
java.text.DateFormat dateFormat = DateFormat.getMediumDateFormat(context);
java.text.DateFormat timeFormat = DateFormat.getTimeFormat(context);
button.setText(String.format("%s %s", dateFormat.format(date), timeFormat.format(date)));
In your case of the time picker you can just format the selected values into a string:
button.setText(String.format("%02d:%02d", selectedHour, selectedMinute));

Related

Time Picker Fragments Differentiation

I have run into a problem where my app is properly building and buttons are working as expect, but the text field I am editing with two time picker fragments is being edited by both the start time picker and end time picker.
public class MainActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button_start = (Button) findViewById(R.id.start_picker_button);
button_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment timePicker1 = new TimePickerStartFragment();
timePicker1.show(getSupportFragmentManager(),"time picker start");
}
});
Button button_end = (Button) findViewById(R.id.end_picker_button);
button_end.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment timePicker2 = new TimePickerEndFragment();
timePicker2.show(getSupportFragmentManager(),"time picker end");
}
});
}
#Override
public void onTimeSet(TimePicker TimePickerStartFragment, int hourOfDay, int minute) {
TextView textView = (TextView)findViewById(R.id.textView);
textView.setText("Hour: " + hourOfDay + " " + "Minute: " + minute);
My application looks like two buttons, one for a start time fragment and the other for an end time fragment. I have two seperate time picker fragment java files. However, when I set the end time fragment it still modifies the start time text. I want to have the start time picker only modify the start time text and the end time picker modify the end time text.
To further clarify when the select start time button is pressed TimePickerStratFragment is opened and a time is selected, this modifies a text field called textView. However when the time end button fragment is selected it also modifies the text view. I want the time end button to not modify the text view.
Add a String value to check which time picker is opened, because onTimeSet is fired for both fragments use something like this
String timeTag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button_start = (Button) findViewById(R.id.start_picker_button);
button_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
timeTag = "from";
DialogFragment timePicker1 = new TimePickerStartFragment();
timePicker1.show(getSupportFragmentManager(),"time picker start");
}
});
Button button_end = (Button) findViewById(R.id.end_picker_button);
button_end.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
timeTag = "to";
DialogFragment timePicker2 = new TimePickerEndFragment();
timePicker2.show(getSupportFragmentManager(),"time picker end");
}
});
}
#Override
public void onTimeSet(TimePicker TimePickerStartFragment, int hourOfDay, int minute) {
if(Objects.equals(timeTag, "from")) {
TextView textView = (TextView)findViewById(R.id.textView);
textView.setText("Hour: " + hourOfDay + " " + "Minute: " + minute);
}
if(Objects.equals(timeTag, "to")) {
}
}

Android: How to set time from time picker in two different EditText fields (start/end)?

I am trying to get the time when the user clicks on the EditText StartTime and EndTime. The problem is that I don't know how to distinguish the EditTexts at the TimePickerFragment. Any help, please?
public void initializeTime () {
startTimeEditText = (EditText) findViewById(R.id.startTimeEditText);
startTimeEditText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Initialize a new time picker dialog fragment
DialogFragment dFragment = new TimePickerFragment();
// Show the time picker dialog fragment
dFragment.show(getSupportFragmentManager(),"TimePicker");
}
});
endTimeEditText = (EditText) findViewById(R.id.endTimeEditText);
endTimeEditText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Initialize a new time picker dialog fragment
DialogFragment dFragment = new TimePickerFragment();
// Show the time picker dialog fragment
dFragment.show(getSupportFragmentManager(),"TimePicker");
}
});
}
TimePickerFragment.java:
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// Do something with the time chosen by the user
EditText startTimeEditText = (EditText) getActivity().findViewById(R.id.startTimeEditText);
EditText endTimeEditText = (EditText) getActivity().findViewById(R.id.endTimeEditText);
flag = getArguments().getString("Flag");
Log.v(TAG,flag);
Toast.makeText(getActivity(), "Toast"+flag, Toast.LENGTH_LONG).show();
if (startTimeEditText.isActivated()){
startTimeEditText.setText(String.valueOf(hourOfDay) + ":" + String.valueOf(minute));
}
else if (endTimeEditText.isActivated()){
endTimeEditText.setText(String.valueOf(hourOfDay) + ":" + String.valueOf(minute));
}
}
TimePickerFragment should not mess with the layout of the rest of the Activity: the best way here is to pass a listener to the TimePickerFragment. Take a look at TimePicker.setOnTimeChangedListener(...), I know it's not a Fragment, but the idea is the same.
Another solution is to use an event bus (for example including the EventBus library) and posting a new event when the user select a date: in this way any component of your app can subscribe to this event and act accordingly.

How to update dialogue in android

I have a popup dialog where the user inputs data, including a date. To select the date, I have a button to open another window with a date picker. When I select the date and it returns to the first dialog, the text field with the date is not changed unless I open the date picker a second time. How would I refresh or update the first dialog immediately after I return to it from the date picker window?
Here is the code for the first dialog:
public void addEntry(View view) {
final Dialog d = new Dialog(this);
d.setContentView(R.layout.dialog);
d.setTitle("Add Entry");
d.setCancelable(true);
d.show();
...
chooseDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str = selectDate();
date.setText(str);
}
});
}
Here is the code for the second window where you would choose the date:
public String selectDate(){
final Dialog datePicker = new Dialog(this);
datePicker.setContentView(R.layout.choose_date);
datePicker.setTitle("Choose Date...");
datePicker.setCancelable(true);
datePicker.show();
Button selectFinalDate = (Button) datePicker.findViewById(R.id.selectDate);
final DatePicker dp = (DatePicker) datePicker.findViewById(R.id.datePicker1);
selectFinalDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
strDateTime = (dp.getMonth() + 1) + "/" + dp.getDayOfMonth() + "/" + dp.getYear();
datePicker.dismiss();
}
});
return strDateTime;
};
Thanks!!
Put date.setText(datechoosen) in the second dialog on click and it will set the textView or button or whatever view that shows the date on the first dialog. Make it static in case it is not accessible in the second dialog but check if it is not null before accessing it.
not tested, but should work.
...
date.setText(str);
view.invalidate(); // the view that you are showing in the dialog
...
so in your code, you update this :
/**
* global variable for your dialog view
*/
View view =null;
// in your addEntry(View view)
...
Dialog d = new Dialog(this);
view = LayoutInflater.from(this).inflate(R.layout.dialog, null);
d.setContentView(view);
...
// selectDate()
...
date.setText(str);
view.invalidate(); // the view that you are showing in the dialog
...
see this answer

TimePicker Dialog retrieves on create time, not current time if activity remains open it wont change

TimePicker Dialog retrieves onCreate time, not current time if activity remains open it wont change ... I am wanting the dialog to always show current time not just when the activity started. i am currently using the following in the onCreate:
final Calendar onscene = Calendar.getInstance();
buildingfireonsceneHour = onscene.get(Calendar.HOUR_OF_DAY);
buildingfireonsceneMinute = onscene.get(Calendar.MINUTE);
Pass the updateTimer() function the current time just before you open the dialog, for example:
mTimePickerDialog = new TimePickerDialog(this, null, 0, 0, false);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Calendar calendar = Calendar.getInstance();
mTimePickerDialog.updateTime(calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE));
mTimePickerDialog.show();
}
});
** Addition **
I believe you want to override the onPrepareDialog() function like this:
#Override
protected void onPrepareDialog (int id, Dialog dialog, Bundle args) {
super.onPrepareDialog(id, dialog, args);
if(id != DATE_DIALOG_ID) {
final Calendar c = Calendar.getInstance();
((TimePickerDialog) dialog).updateTime(c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE));
}
}

Where to place the clickListeners in my code?

The app has initial message screen that is displayed the first time it run where a date is obtained from user using datepicker then from next time it goes directly to main.xml. This is the logic i tried
in onCreate()
if(<date set>)
{
<open main.xml>
<listeners>
}
else
{
<get date from user>
<set flag>
setContentView(R.layout.initial_msg);
<make changes in main.xml according to date>
}
The problem is the first time it executes it obtains the date but the listeners are not loaded, i think this is because the code is not executed at all. when i place the listener outside the if block i get a null pointer exception. But when i close the app and start it again it works as this time it opens if() block not else().
public class pgactivity extends Activity
{
/** Called when the activity is first created. */
SharedPreferences prefs;
Calendar c=Calendar.getInstance();
Calendar tempDate;
TextView tv1,tv2;
Menu theMenu;
LayoutInflater li;
int week;
DatePickerDialog.OnDateSetListener d=new DatePickerDialog.OnDateSetListener()
{
//#override
public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth)
{
c.set(Calendar.DATE,dayOfMonth);
c.set(Calendar.MONTH,monthOfYear);
c.set(Calendar.YEAR,year);
if(checkValidity())
{
SharedPreferences.Editor editor=prefs.edit();
//set the flag that indicates concieved_date has been added
editor.putBoolean("concieved_date", true);
int datepref;
datepref=c.get(Calendar.DATE);
datepref=datepref*1000000;
datepref+=c.get(Calendar.MONTH)*10000;
datepref+=c.get(Calendar.YEAR);
editor.putInt("date",datepref);
editor.commit();
setContentView(R.layout.main);
setData();
}
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//check if concieved date is set from the prefs file "app_data"
//if yes open application page else open initial message screen to set the date
prefs=getApplicationContext().getSharedPreferences("app_data",Context.MODE_APPEND);
if(prefs.getBoolean("concieved_date", false))
{
setContentView(R.layout.main);
setData();
//Listener for the temp button 'false'
//It resets the flag used to indicate if date is set or not. used for testing purpose
Button btn1=(Button)findViewById(R.id.setfalse);
btn1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
SharedPreferences.Editor editor=prefs.edit();
editor.putBoolean("concieved_date", false);
editor.commit();
TextView tv3=(TextView)findViewById(R.id.test);
tv3.setText("entered listener");
}
});
//Listener for the weekly_tip text view
//when clicked open the layout giving the full description
TextView tv2=(TextView)findViewById(R.id.weekly_tip);
tv2.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent j=new Intent(pgactivity.this,weekly.class);
Bundle b=new Bundle();
b.putInt("cur_week",week);
j.putExtras(b);
startActivity(j);
}
});
//Listener for open_remainders button to switch to Remainders page
Button btn2=(Button)findViewById(R.id.open_remainders);
btn2.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent i=new Intent(pgactivity.this,RemaindersPage.class);
startActivity(i);
}
});
}
else
{
setContentView(R.layout.initial_msg);
//click listener for textview 2
TextView tv1=(TextView)findViewById(R.id.init_msg);
tv1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
SharedPreferences.Editor editor=prefs.edit();
editor.putBoolean("concieved_date", true);
editor.commit();
new DatePickerDialog(pgactivity.this,d,
c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH)).show();
}
});
}
}
void setData()
{
Long sec,tempSec;
int date,day,month,year;
date=prefs.getInt("date", 10101010);
day=date/1000000;
date=date%1000000;
month=date/10000;
date=date%10000;
year=date;
c.set(year, month, day);
tempDate=c;
//insert value to concieved_date textfield
tv1=(TextView)findViewById(R.id.concieved_date);
tv1.setText(android.text.format.DateFormat.format("dd MMM yyyy", tempDate));
//insert value to delivery_date
tv1=(TextView)findViewById(R.id.delivery_date);
tempDate.add(Calendar.DATE, 280);
tv1.setText(android.text.format.DateFormat.format("dd MMM yyyy", tempDate));
//insert value to days_to_delivery
tv1=(TextView)findViewById(R.id.days_to_delivery);
c=Calendar.getInstance(); //c has current date
sec=tempDate.getTimeInMillis()-c.getTimeInMillis(); //find diff in millisecs
sec=sec/86400000;
tv1.setText(sec.toString());
//insert value for days_into_pregnancy
tv1=(TextView)findViewById(R.id.days_into_pregnancy);
tempSec=280-sec;
tv1.setText(tempSec.toString());
//insert value for current_week
tv1=(TextView)findViewById(R.id.current_week);
tempSec=tempSec/7;
week=tempSec.intValue();
tv1.setText(tempSec.toString());
}
//user method to check the date validity : check if date entered is a reasonable value
boolean checkValidity()
{
Long duration;
tempDate=Calendar.getInstance(); //get today's date in c
//check if user date is on or before today's date
if(tempDate.before(c))
{
AlertDialog.Builder ad=new AlertDialog.Builder(this);
ad.setMessage("Specified date should be on or before today's date");
ad.setNeutralButton("OK",new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0,int arg1){}
}
);
ad.show();
return false;
}
//check if diff between user date and todays date is more than 280 days
duration=tempDate.getTimeInMillis()-c.getTimeInMillis();
duration/=86400000;
if(duration>280)
{
AlertDialog.Builder ad=new AlertDialog.Builder(this);
ad.setMessage("Specified date can be atmost 280 days before today's date");
ad.setNeutralButton("OK",new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0,int arg1){}
}
).show();
return false;
}
return true;
}
}
If you need your listeners in the else-block, too, you can put this code before the if-block.
If the layout changes if the if or the else is executed, you can use the onClick-attribute in your XML-Layout definition.
To save your data, you can use SharedPreferences.

Categories

Resources