showDialog not displayed Android - java

Inside an Activity, I am calling different fragments , I want the user to be able to change the date by clicking on a textView that displays the current date, the showDialog does not want to be displayed.
dateView.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(View v) {
getActivity().showDialog(999);
}
});
Android Studio tells me that CreateDialog is never used.
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 999) {
return new DatePickerDialog(getContext(),
myDateListener, year, month, day);
}
return null;
}
Full code:
public class Fragment5 extends android.support.v4.app.Fragment {
private DatePicker datePicker;
private Calendar calendar;
private TextView dateView;
TimePicker timePicker2;
private int year, month, day;
public Fragment5() {
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_fragment5, container, false);
dateView = (TextView) rootView.findViewById(R.id.textView3);
calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
showDate(year, month+1, day);
dateView.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(View v) {
getActivity().showDialog(999);
}
});
return rootView;
}
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 999) {
return new DatePickerDialog(getContext(),
myDateListener, year, month, day);
}
return null;
}
private DatePickerDialog.OnDateSetListener myDateListener = new
DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker arg0,
int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
// arg1 = year
// arg2 = month
// arg3 = day
showDate(arg1, arg2+1, arg3);
}
};
private void showDate(int year, int month, int day) {
dateView.setText(new StringBuilder().append(day).append("/")
.append(month).append("/").append(year));
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
public static Bundle myBundl = new Bundle();
private List<ItemSlideMenu> listSliding;
private SlidingMenuAdapter3 adapter;
private Calendar calendar;
private TextView dateView;
TimePicker timePicker2;
final Context context = this ;
private int year, month, day;
private ListView listViewSliding;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
String name1;
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
showDate(year, month+1, day);
//Init component
listViewSliding = (ListView) findViewById(R.id.lv_sliding_menu);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
listSliding = new ArrayList<>();
//Add item for sliding list
listSliding.add(new ItemSlideMenu(R.drawable.home_96,"Accueil" ));
listSliding.add(new ItemSlideMenu(R.drawable.cocktail,"Organiser une Sortie"));
listSliding.add(new ItemSlideMenu(R.drawable.geo,"Autour de moi"));
listSliding.add(new ItemSlideMenu(R.drawable.ami,"Liste d'amis" ));
listSliding.add(new ItemSlideMenu(R.drawable.message,"Contact"));
listSliding.add(new ItemSlideMenu(R.drawable.information,"Credits"));
adapter = new SlidingMenuAdapter3(this, listSliding);
listViewSliding.setAdapter(adapter);
//Display icon to open/ close sliding list
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//Set title
setTitle(listSliding.get(0).getTitle());
//item selected
listViewSliding.setItemChecked(0, true);
//Close menu
drawerLayout.closeDrawer(listViewSliding);
//Display fragment 1 when start
replaceFragment(0);
//Hanlde on item click
listViewSliding.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Set title
setTitle(listSliding.get(position).getTitle());
//item selected
listViewSliding.setItemChecked(position, true);
if (position==2){
Intent i2 = new Intent(getApplicationContext(), MapsActivity.class);
startActivity(i2);
} else
{//Replace fragment
replaceFragment(position);
}//Close menu
drawerLayout.closeDrawer(listViewSliding);
}
});
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.drawer_opened, R.string.drawer_closed){
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
invalidateOptionsMenu();
}
};
drawerLayout.setDrawerListener(actionBarDrawerToggle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
//Create method replace fragment
private void replaceFragment(int pos) {
android.support.v4.app.Fragment fragment = null;
switch (pos) {
case 0:
fragment = new Fragment1();
break;
case 1:
fragment = new Fragment2();
break;
case 2:
fragment = new Fragment3();
break;
case 3 :
fragment = new Fragment4();
break;
}
if(null!=fragment) {
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.main_content,fragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
#SuppressWarnings("deprecation")
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 999) {
return new DatePickerDialog(this,
myDateListener, year, month, day);
}
else if (id ==98) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom);
dialog.setTitle("Title...");
// set the custom dialog components - text, image and button
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment6 fragment = null;
fragment = new Fragment6();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.contact, fragment);
transaction.addToBackStack(null);
transaction.commit();
dialog.dismiss();
}
});
dialog.show();
// if button is clicked, close the custom dialog
}
return null;
}
private DatePickerDialog.OnDateSetListener myDateListener = new
DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker arg0,
int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
// arg1 = year
// arg2 = month
// arg3 = day
showDate(arg1, arg2+1, arg3);
}
};
private void showDate(int year, int month, int day) {
StringBuilder abbes = new StringBuilder().append(day).append("/")
.append(month).append("/").append(year);
Bundle bundle = new Bundle();
bundle.putString("edttext", String.valueOf(abbes));
// set Fragmentclass Arguments
Fragment5 fragobj = new Fragment5();
fragobj.setArguments(bundle);
}
}

Since,
Callback for creating dialogs that are managed (saved and restored) for you by the Activity.
Implement this method in Activityinstead of Fragment
#Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 999) {
return new DatePickerDialog(getContext(),
myDateListener, year, month, day);
}
return null;
}
Call Fragment like this;
private void showDate(int year, int month, int day) {
StringBuilder abbes = new StringBuilder().append(day).append("/")
.append(month).append("/").append(year);
if(fragment instanceof Fragment4){
((Fragemnt4)fragment).dateView.setText(""+abbes);
}
}
Make dateView public

showDialog() is deprecated. Replace this code
public class Fragment5 extends android.support.v4.app.Fragment {
private DatePicker datePicker;
private Calendar calendar;
private TextView dateView;
TimePicker timePicker2;
private int year, month, day;
DialogFragment dateFragment;
public Fragment5() {
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_fragment5, container, false);
dateView = (TextView) rootView.findViewById(R.id.textView3);
calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
showDate(year, month+1, day);
dateView.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(View v) {
dateFragment = new DatePickerFragment();
dateFragment.show(getFragmentManager(), "datePicker");
}
});
return rootView;
}
private void showDate(int year, int month, int day) {
dateView.setText(new StringBuilder().append(day).append("/")
.append(month).append("/").append(year));
}
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 year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
showDate(year,month,day);
}
} }

What exactly showDialog (int id) method does is show a dialog managed by activity. A call to onCreateDialog(int, Bundle) will be made with the same id the first time this is called for a given id. From thereafter, the dialog will be automatically saved and restored.
You must write your onCreateDialog method in Activity as said by #Burhanuddin Rashid but that could cause complexity in data transition between Activity and Fragment.
Further,
void showDialog (int id)
This method was deprecated in API level 13.
Use the new DialogFragment class with FragmentManager instead; this is also available on older platforms through the Android compatibility package.
PS,
I recommend you to use a DialogFragment
For more info check out this official documentation

Related

Pass data from Activity to Fragment in another Activity

I need to pass data from Activity "MainCalendar" to fragment "AddTaskFragment" in Activity "Add". I have a button in a fragment which opens an Activity "MainCalendar", where I select a date in the calendar, and then I need to send this date into a fragment.
When I click on Choose Button, there is opens a MainCalendar, where user need to choose date, after that, the activity closed, and than I want to put a date from MainCalendar to the text of "Choose Button".
MainCalendar Activity:
MainCalendar.class:
public class MainCalendar extends AppCompatActivity {
private CalendarView Calendar;
private String date;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_calendar);
Calendar = (CalendarView) findViewById(R.id.calendarView);
Calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(#NonNull CalendarView view, int year, int month, int dayOfMonth) {
date = (dayOfMonth+"/"+month+"/"+year);
System.out.println(date);
Intent intent = new Intent(MainCalendar.this, Add.class);
intent.putExtra("DATE_KEY", date);
finish();
}
});
}
Add.class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
BottomNavigationView bottomNav = findViewById(R.id.bottom_nav);
bottomNav.setSelectedItemId(R.id.add);
Button notes_button = findViewById(R.id.notes_btn);
Button tasks_button = findViewById(R.id.tasks_btn);
Button goals_button = findViewById(R.id.goals_btn);
RadioButton rb = findViewById(R.id.choose_day_btn);
String date = null;
Bundle extras = getIntent().getExtras();
if (extras != null) {
//The key argument here must match that used in the other activity
date = extras.getString("DATE_KEY");
}
AddTasksFragment frag = new AddTasksFragment();
Bundle bundle = new Bundle();
bundle.putString("DATE_KEY", date);
frag.setArguments(bundle);
Fragment fragment1 = new AddTasksFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment1).commit();
bottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.notes:
startActivity(new Intent(getApplicationContext(), Notes.class));
overridePendingTransition(0,0);
return true;
case R.id.add:
return true;
case R.id.tasks:
startActivity(new Intent(getApplicationContext(), Tasks.class));
overridePendingTransition(0,0);
return true;
case R.id.goals:
startActivity(new Intent(getApplicationContext(), Goals.class));
overridePendingTransition(0,0);
return true;
case R.id.statistics:
startActivity(new Intent(getApplicationContext(), Statistics.class));
overridePendingTransition(0,0);
return true;
}
return false;
}
});
Fragment fragment = new AddTasksFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment).commit();
tasks_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment = new AddTasksFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment).commit();
}
});
notes_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment = new AddNotesFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment).commit();
}
});
goals_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment = new AddGoalsFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment).commit();
}
});
//
AddTaskFragment.class, which is in Add.class:
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.add_tasks_fragment, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
subtask_btn = (Button) view.findViewById(R.id.add_subtask_btn);
subtask_name = (EditText) view.findViewById(R.id.subtask_name);
task_name = (EditText) view.findViewById(R.id.task_name);
lin_lay = (LinearLayout) view.findViewById(R.id.linear_layout);
sb_lay = (LinearLayout) view.findViewById(R.id.subtask_lay);
apply_btn = (Button) view.findViewById(R.id.apply_btn);
rgDay = (RadioGroup) view.findViewById(R.id.date_group);
rgPriority = (RadioGroup) view.findViewById(R.id.priority_group);
todayBtn = (RadioButton) view.findViewById(R.id.today_btn);
tomorrowBtn = (RadioButton) view.findViewById(R.id.tomorrow_btn);
chooseDayBtn = (RadioButton) view.findViewById(R.id.choose_day_btn);
lowPrBtn = (RadioButton) view.findViewById(R.id.low_btn);
mediumPrBtn = (RadioButton) view.findViewById(R.id.medium_btn);
highPrBtn = (RadioButton) view.findViewById(R.id.high_btn);
firebaseAuth = FirebaseAuth.getInstance();
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
dataBase = FirebaseDatabase.getInstance().getReference(TASKS_KEY);
this.getResources().getDisplayMetrics();
subtask_btn.setOnClickListener(this);
apply_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
writeTask();
}
});
chooseDayBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), MainCalendar.class);
startActivity(intent);
}
});
String data;
data = getActivity().getIntent().getStringExtra(DATE_KEY);
}
#Override
public void onClick(View v) {
addView();
}
private void writeTask() {
String Task;
Task = task_name.getText().toString();
dataBase.push().setValue(Task);
String[] subTasks = new String[sb_lay.getChildCount()];
for (int i = 0; i < sb_lay.getChildCount(); i++) {
View subtaskView = sb_lay.getChildAt(i);
EditText editTextName = (EditText) subtaskView.findViewById(R.id.subtask_name);
subTasks[i] = editTextName.getText().toString();
dataBase.child(Task).child("Subtasks").push().setValue(subTasks[i]);
}
dataBase.child(Task).push().setValue(getDay());
}
private String getDay(){
String day=null;
if(todayBtn.isChecked()){
Date currentTime = Calendar.getInstance().getTime();
day = currentTime.toString();
}
else if(tomorrowBtn.isChecked()){
Date dt = new Date();
Calendar c = Calendar.getInstance();
c.setTime(dt);
c.add(Calendar.DATE, 1);
dt = c.getTime();
day = dt.toString();
}else if(chooseDayBtn.isChecked()) {
day = getArguments().getString("DATE_KEY");
System.out.println(" Date is choosed ----------------------------------------------------------------------------" + day);
chooseDayBtn.setText(day);
}
return day;
}
private void addView(){
final View subtaskView = getLayoutInflater().inflate(R.layout.subtask_raw, null, false);
EditText editText = (EditText)subtaskView.findViewById(R.id.subtask_name);
ImageView imageClose = (ImageView)subtaskView.findViewById(R.id.remove_subtask);
imageClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removeView(subtaskView);
}
});
sb_lay.addView(subtaskView);
String day;
day = getArguments().getString("DATE_KEY");
System.out.println(" Date is choosed " + day);
}
private void removeView(View view){
sb_lay.removeView(view);
}
There are two ways to do that.
The first one is using callback and the second one is using a bundle.
In the first-way, you can create an interface and implement in your fragment and pass it to your activity. when users click the date you callback the parameter using this interface.
The second-way using bundles like this.
in your fragment create a constructor like this and call it in your activity :
public static YourFragment getInstance(obj yourParameter){
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
YourFragment fragobj = new YourFragment ();
fragobj.setArguments(bundle);
return fragobj;
}
in the onCreate method get obj in this way :
String strtext = getArguments().getString("edttext");

how to call dialog fragment with listview and search filter from a fragment and save selected item value in parent fragment as string?

public class fragment_oneway_flight extends Fragment {
private Spinner spinner1 ;
Context thiscontext;
private int mYear, mMonth, mDay, mHour, mMinute;
int countadult= 1;
int countchild= 0;
int countinfant= 0;
private ProgressDialog pDialog,pDialog1;
TextView quantity_adult_textview, quantity_child_textview, quantity_infant_textview, textview_city_slct_from_oneway, textview_city_slct_to_oneway;
private ImageButton increment_adult_Button, decrement_adult_Button, increment_child_Button, decrement_child_Button, increment_infant_Button, decrement_infant_Button;
private Button prcdtoonwyrslt;
public fragment_oneway_flight() {
// Required empty public constructor
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
thiscontext = container.getContext();
View rootView = inflater.inflate(R.layout.fragment_oneway_flight, container, false);
LinearLayout select_dep_date = (LinearLayout) rootView.findViewById(R.id.date_from_select_oneway);
select_dep_date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment dFragment = new DatePickerFragment();
// Show the date picker dialog fragment
dFragment.show(getFragmentManager(), "Date Picker");
}
});
LinearLayout city_slct_from_oneway = (LinearLayout) rootView.findViewById(R.id.city_slct_from_oneway);
city_slct_from_oneway.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogBoxFragment DialogBoxFragment = new DialogBoxFragment ();
DialogBoxFragment.show(getFragmentManager(),"dialog");
}
});
LinearLayout city_slct_to_oneway = (LinearLayout) rootView.findViewById(R.id.city_slct_to_oneway);
city_slct_to_oneway.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogBoxFragment2 DialogBoxFragment2 = new DialogBoxFragment2 ();
DialogBoxFragment2.show(getFragmentManager(),"dialog2");
}
});
prcdtoonwyrslt = (Button) rootView.findViewById( R.id.prcdtoonwyrslt );
prcdtoonwyrslt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), activity_flight_result_oneway.class);
pDialog1 = new ProgressDialog(getActivity());
pDialog1.setMessage("Please Wait...");
pDialog1.setCancelable(false);
String countadult = quantity_adult_textview.getText().toString();
String countchild = quantity_child_textview.getText().toString();
String countinfant = quantity_infant_textview.getText().toString();
String selectedfromcity = textview_city_slct_from_oneway.getText().toString();
String selectedtocity = textview_city_slct_to_oneway.getText().toString();
intent.putExtra("adultsnos", countadult);
intent.putExtra("childsnos", countchild);
intent.putExtra("infantsnos", countinfant);
intent.putExtra("fromcity", selectedfromcity);
intent.putExtra("tocity", selectedtocity);
startActivity(intent);
}
});
// button function start
increment_adult_Button = (ImageButton) rootView.findViewById( R.id.increment_adult_Button );
decrement_adult_Button = (ImageButton) rootView.findViewById( R.id.decrement_adult_Button );
increment_child_Button = (ImageButton) rootView.findViewById( R.id.increment_child_Button );
decrement_child_Button = (ImageButton) rootView.findViewById( R.id.decrement_child_Button );
increment_infant_Button = (ImageButton) rootView.findViewById( R.id.increment_infant_Button );
decrement_infant_Button = (ImageButton) rootView.findViewById( R.id.decrement_infant_Button );
quantity_adult_textview = (TextView) rootView.findViewById(R.id.quantity_adult_textview);
quantity_child_textview = (TextView) rootView.findViewById(R.id.quantity_child_textview);
quantity_infant_textview = (TextView) rootView.findViewById(R.id.quantity_infant_textview);
increment_adult_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countadult++;
if(countadult>7){
countadult=7;
}
display(countadult);
}
});
decrement_adult_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countadult--;
if(countadult<1){
countadult=1;
}
display(countadult);
}
});
increment_child_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countchild++;
if(countchild>5){
countchild=5;
}
display(countchild);
}
});
decrement_child_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countchild--;
if(countchild<0){
countchild=0;
}
display(countchild);
}
});
increment_infant_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countinfant++;
if(countinfant>5){
countinfant=5;
}
display(countinfant);
}
});
decrement_infant_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countinfant--;
if(countinfant<0){
countinfant=0;
}
display(countinfant);
}
});
// button function end
setSpinnerContent( rootView );
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> id, View rootView, int pos, long arg3) {
if (pos == 0) {
Toast.makeText(getActivity().getApplicationContext(),
"Select Class", Toast.LENGTH_SHORT)
.show();
} else if (pos == 1) {
Toast.makeText(getActivity().getApplicationContext(),
"You have selected Economy", Toast.LENGTH_SHORT)
.show();
} else if (pos == 2) {
Toast.makeText(getActivity().getApplicationContext(),
"You have selected Premium Economy", Toast.LENGTH_SHORT)
.show();
} else if (pos == 3) {
Toast.makeText(getActivity().getApplicationContext(),
"You have selected Business", Toast.LENGTH_SHORT)
.show();
}else if (pos == 4) {
Toast.makeText(getActivity().getApplicationContext(),
"You have selected First Class", Toast.LENGTH_SHORT)
.show();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
Toast.makeText(getActivity().getApplicationContext(), "Nothing to select", Toast.LENGTH_LONG).show();
}
});
return rootView;
}
private void setSpinnerContent( View rootView ) {
spinner1 = (Spinner) rootView.findViewById( R.id.spinner_flight );
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.flight_class_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter( adapter );
}
public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{
#Override
public Dialog onCreateDialog(Bundle savedInstanceState){
final Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
/*
Initialize a new DatePickerDialog
DatePickerDialog(Context context, DatePickerDialog.OnDateSetListener callBack,
int year, int monthOfYear, int dayOfMonth)
*/
DatePickerDialog dpd = new DatePickerDialog(getActivity(), R.style.DateDialog,this,year,month,day);
return dpd;
}
public void onDateSet(DatePicker view, int year, int month, int day){
// Do something with the chosen date
TextView dep_date_flight = (TextView) getActivity().findViewById(R.id.text_dep_date);
// Create a Date variable/object with user chosen date
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(0);
cal.set(year, month, day, 0, 0, 0);
Date chosenDate = cal.getTime();
// Format the date using style and locale
DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.US);
String formattedDate = df.format(chosenDate);
// Display the chosen date to app interface
dep_date_flight.setText(formattedDate);
}
}
private void display(int number) {
quantity_adult_textview.setText(String.valueOf(countadult));
quantity_child_textview.setText(String.valueOf(countchild));
quantity_infant_textview.setText(String.valueOf(countinfant));
}
public static class DialogBoxFragment extends DialogFragment {
//declaring variables
private ListView listviewforresults;
//Adapter for listview
ArrayAdapter<String> list1adapter;
//Edittext for search
EditText searchdata;
//ArrayList for listview
ArrayList<String> data=new ArrayList<String>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView1 = inflater.inflate(R.layout.fragment_city_select_flight, container, false);
prepareDummyData();
listviewforresults=(ListView)rootView1.findViewById(R.id.showdata);
searchdata=(EditText)rootView1.findViewById(R.id.searchdata);
//set data to Adapter
list1adapter=new ArrayAdapter<String>(getActivity(), country_list,R.id.results,data);
listviewforresults.setAdapter(list1adapter);
//search data when text changes in edittext
searchdata.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
list1adapter.getFilter().filter(s);
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
listviewforresults.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
String selectedFromList = (String) listviewforresults.getItemAtPosition(position).toString();
TextView textview_city_slct_from_oneway = (TextView) getActivity().findViewById(R.id.textview_city_slct_from_oneway);
textview_city_slct_from_oneway.setText(selectedFromList);
getDialog().dismiss();
}
});
getDialog().setTitle("dialog");
return rootView1;
}
public void prepareDummyData()
{
data.add("Chennai");
data.add("Mumbai");
data.add("Bangalore");
data.add("Madurai");
data.add("Coimbatore");
data.add("Newdelhi");
}
}
public static class DialogBoxFragment2 extends DialogFragment {
//declaring variables
private ListView listviewforresults2;
//Adapter for listview
ArrayAdapter<String> list2adapter;
//Edittext for search
EditText searchdata;
//ArrayList for listview
ArrayList<String> data=new ArrayList<String>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView2 = inflater.inflate(R.layout.fragment_city_select_flight2, container, false);
prepareDummyData2();
listviewforresults2=(ListView)rootView2.findViewById(R.id.showdata);
searchdata=(EditText)rootView2.findViewById(R.id.searchdata);
//set data to Adapter
list2adapter=new ArrayAdapter<String>(getActivity(), country_list,R.id.results,data);
listviewforresults2.setAdapter(list2adapter);
//search data when text changes in edittext
searchdata.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
list2adapter.getFilter().filter(s);
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
listviewforresults2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
String selectedFromList2 = (String) listviewforresults2.getItemAtPosition(position).toString();
TextView textview_city_slct_to_oneway = (TextView) getActivity().findViewById(R.id.textview_city_slct_to_oneway);
textview_city_slct_to_oneway.setText(selectedFromList2);
getDialog().dismiss();
}
});
getDialog().setTitle("dialog2");
return rootView2;
}
public void prepareDummyData2() {
data.add("Chennai");
data.add("Mumbai");
data.add("Bangalore");
data.add("Madurai");
data.add("Coimbatore");
data.add("Newdelhi");
}
}
}
the above code is full fragment code with gialog innerclass too. im a beginner can you gys help me out of it?
and actually what i need is i have to click the from and to area in tab view fragment. after slecting it opens a dialog with search filter and listview. after clicking any list item it should diaplay in textview on parent fragment and after that i should be able wo pass the value to next fragment using put intent method.
currently im getting null value when i pass it to the next fragment.
i dont know why.
i have attached an image to get you the clear view. please check it.see here

How to access parameters from one method to another one

I'm stuck at here in this program,I want to access parameters of DatePickerFragment into TimePickerFragment.Please help.
public class datepicker extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_datepicker);
Button btn = (Button) findViewById(R.id.datepick);
Button btn2 = (Button) findViewById(R.id.timepick);
// TextView textview = (TextView) findViewById(R.id.textView1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogFragment dFragment = new DatePickerFragment();
// Show the date picker dialog fragment
dFragment.show(getFragmentManager(), "Date Picker");
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogFragment dFragment = new TimePickerFragment();
// Show the time picker dialog fragment
dFragment.show(getFragmentManager(),"Time Picker");
}
});
}
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dpd = new DatePickerDialog(getActivity(),
AlertDialog.THEME_HOLO_DARK, this, year, month, day);
return dpd;
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the chosen date
Button textview = (Button) getActivity().findViewById(R.id.datepick);
textview.setText(day + ":" + (month + 1) + ":" + year);
}
}
public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener{
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Get a Calendar instance
final Calendar calendar = Calendar.getInstance();
// Get the current hour and minute
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
TimePickerDialog tpd = new TimePickerDialog(getActivity(),
AlertDialog.THEME_DEVICE_DEFAULT_LIGHT, this, hour, minute, false);
return tpd;
}
public void onTimeSet(TimePicker timePicker, int i, int i1) {
Button tv = (Button) getActivity().findViewById(R.id.timepick);
tv.setText(i + ":" + i1);
DatePickerFragment b = new DatePickerFragment();
b.onDateSet(view ,int year,int month,int day);
}
}}
I need year,month,day in TimePickerFragment method.Please solve it asap.Thanks in advance.

Display TimePicker when textField is focused

I am just getting into android apps and now trying to work with an interface that allows the user to enter time into a text box. The time picker dialog will display when a text box is focused. But now when I click the text box, the date picker dialog does not display.
WorkDetails.java
public void onFocusChange(View v, boolean hasFocus) {
EditText txtTime = (EditText) findViewById(R.id.editText6);
txtTime.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus)
{
TimePick time = new TimePick(v);
FragmentTransaction ft = getFragmentManager().beginTransaction();
time.show(ft, "TimePicker");
}
}
});
}
TimePick.java
#SuppressLint("ValidFragment")
public class TimePick extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
private TextView time;
public TimePick(View view)
{
time=(EditText)view;
}
public Dialog onCreateDialog(Bundle savedInstanceState)
{
final Calendar c= Calendar.getInstance();
int hour=c.get(Calendar.HOUR_OF_DAY);
int minute=c.get(Calendar.MINUTE);
//Toast.makeText(getActivity(),this,"Date: "+year+"-",+month+"-"+day,Toast.LENGTH_SHORT).show();
return new TimePickerDialog(getActivity(),this,hour,minute, DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view,int hourofDay, int minute)
{
time.setText(Integer.toString(hourofDay) + ":" + Integer.toString(minute));
}
}
editText = (EditText)findViewById(R.id.editText);
editText2 = (EditText)findViewById(R.id.editText2);
editText3 = (EditText)findViewById(R.id.editText3);
editText2.setOnFocusChangeListener(new View.OnFocusChangeListener()
{
#Override
public void onFocusChange(View v, boolean hasFocus)
{
String input;
EditText editText;
if(!hasFocus)
{
TimePick time = new TimePick(v);
FragmentTransaction ft = getFragmentManager().beginTransaction();
time.show(ft, "TimePicker");
}
}
});
editText2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TimePick time = new TimePick(v);
FragmentTransaction ft = getFragmentManager().beginTransaction();
time.show(ft, "TimePicker");
}
});
}
public class TimePick extends DialogFragment implements TimePickerDialog.OnTimeSetListener
{
private TextView time;
public TimePick(View view)
{
time=(EditText)view;
}
public Dialog onCreateDialog(Bundle savedInstanceState)
{
final Calendar c= Calendar.getInstance();
int hour=c.get(Calendar.HOUR_OF_DAY);
int minute=c.get(Calendar.MINUTE);
//Toast.makeText(getActivity(),this,"Date: "+year+"-",+month+"-"+day,Toast.LENGTH_SHORT).show();
return new TimePickerDialog(getActivity(),this,hour,minute, DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view,int hourofDay, int minute)
{
time.setText(Integer.toString(hourofDay) + ":" + Integer.toString(minute));
}
}
try to set android:clickable="true" and android:focusableInTouchMode="false" in xml file.

ShowDialog in Fragment for DateTimePickerDialog

I am trying to follow along this tutorial: http://www.learn-android-easily.com/2013/01/using-timepickerdialog-and.html
However, showDialog cannot be resolved because I am using a fragment. How can I use a DateTime Picker Dialog inside of a class that extends a fragment?
Thanks.
EDIT: Show code:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.date_and_time_picker);
// get the references of buttons
btnSelectDate=(Button)findViewById(R.id.buttonSelectDate);
btnSelectTime=(Button)findViewById(R.id.buttonSelectTime);
// Set ClickListener on btnSelectDate
btnSelectDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Show the DatePickerDialog
showDialog(DATE_DIALOG_ID);
}
});
// Set ClickListener on btnSelectTime
btnSelectTime.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Show the TimePickerDialog
showDialog(TIME_DIALOG_ID); //not resolved in fragment
}
});
}
This is working for me in a fragment
Time currDate = new Time(Time.getCurrentTimezone());
currDate.setToNow();
DatePickerDialog d = new DatePickerDialog(this, datePickerListener,
currDate.year, currDate.month, currDate.monthDay);
d.show();
private DatePickerDialog.OnDateSetListener datePickerListener =
new DatePickerDialog.OnDateSetListener()
{
public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDay)
{
// Do as you need
}
};

Categories