How to save Date and Time state of Fragment - java

I have two EditText. First, use to open DatePicker, and the second use to open TimePicker.
I have created DialogFragment for two-component. Both works.All in the Fragment.
This is my Fragment. When select DatePicker the value of Time disappears and When I select TimePicker Date also disappear. I have already saveInstance. Pls, help!! Thx
DialogFragment datePicker;
TimePickerFragment timePicker;
EditText departureEdt;
EditText departureTimeEdt;
String selectedDate;
String selectedTime;
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
if (outState != null) {
outState.putString("selectedDate", selectedDate);
outState.putString("selectedTime", selectedTime);
}
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
selectedDate = savedInstanceState.getString("selectedDate");
selectedTime = savedInstanceState.getString("selectedTime");
departureEdt.setText(selectedDate);
departureTimeEdt.setText(selectedTime);
}
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final FragmentManager fm = ((AppCompatActivity) getActivity()).getSupportFragmentManager();
View view = inflater.inflate(R.layout.transportation_fragment, container, false);
departureEdt = view.findViewById(R.id.departure_date);
departureEdt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
datePicker = new DatePickerFragment();
datePicker.setTargetFragment(TransportationFragment.this, 1);
datePicker.show(fm, "datePicker");
}
});
departureTimeEdt = view.findViewById(R.id.departure_time);
departureTimeEdt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
timePicker = new TimePickerFragment();
timePicker.setTargetFragment(TransportationFragment.this, 1);
timePicker.show(fm, "timePicker");
}
});
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) {
// get date from string
selectedDate = data.getStringExtra("selectedDate");
selectedTime = data.getStringExtra("selectedTime");
// set the value of the editText
departureEdt.setText(selectedDate);
departureTimeEdt.setText(selectedTime);
}
}
}

Related

How to pass data from Activity A to fragment in Activity B?

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".
Add Activity with a fragment,
MainCalendar Activity:MainCalendar
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);
}
As I understood, you Have to activities (Activity A and Activity B) and you have a fragment in Activity B. What you want to do is sending some data from activity A to that fragment for whatever reason.
Let's have a note first, You can't directly send data to any fragment of activity without launching it. So in order to send this data to the fragment you have to pass it from Activity A to Activity B as a first step and then send it from Activity B to the Fragment as a second step.
The type of data is very important. If you are sending a custom type (a model java class) you have to define it as Parcelable or if it is a primitive type such as int or float so you can send it directly
this is how to do it in Java
ActivityA.java
class ActivityA extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activityA);
// define your data here
int data = 5;
// define an intent to send the data to the second activity
Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
intent.putExtra("DATA_KEY", data);
startActivity(intent);
}
}
Then what we need to do is
receiving the data in the Activity B
Inflating the fragment
pass the data to the fragment
class ActivityB extends Activity{
Int data;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activityB);
Bundle extras = getIntent().getExtras();
if (extras != null) {
//The key argument here must match that used in the other activity
data = extras.getInt("DATA_KEY");
}
// Fragment instance
FragmentClass frag = new FragmentClass();
Bundle bundle = new Bundle();
bundle.putInt("DATA_KEY", data );
frag.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, mFeedFragment);
fragmentTransaction.commit();
}
}
and then receive it the same way we received it in the Activity B

Null Pointer Exception on an EditText in a Fragment [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I am building a signUp page in which i want a date picker but whenever i click on User Fragment to open Sign up Page then the app crashes, and the error is nullPointerException in EditText. Please Help me to solve it.
Here is the Code of UserFragment.java
public class UserFragment extends Fragment {
public EditText et_Date;
public static final int REQUEST_CODE = 11;
String selectedDate;
private OnFragmentInteractionListener mListener;
public DatePickerDialog.OnDateSetListener setListener;
View view;
public UserFragment() {
}
public static UserFragment newInstance() {
UserFragment fragment = new UserFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.adduser_fragment, container, false);
et_Date = (EditText) view.findViewById(R.id.etdate);
final FragmentManager fm = ((AppCompatActivity)getActivity()).getSupportFragmentManager();
et_Date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AppCompatDialogFragment newFragment = new DatePickerFragment();
newFragment.setTargetFragment(UserFragment.this,REQUEST_CODE);
newFragment.show(fm, "DatePicker");
}
});
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK){
selectedDate = data.getStringExtra("SelectedDate");
et_Date.setText(selectedDate);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if(context instanceof OnFragmentInteractionListener){
mListener= (OnFragmentInteractionListener) context;
}else{
throw new RuntimeException(context.toString()+"must implement OnFragmentInterationListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
public void onFragmentInteraction(Uri uri);
}
}
Your editText with id etdate is actually in layout adduser_fragment? This error may be because of view is in another layout(and you forgot that). Sorry for answer, I don't have enough reputation to post comment.

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 get data from DialogFragment to Mainactivity

How con I get text from TextView in DialogFragment to MainActivity or how i make event in MainActivity when Button in DialogFragment clicked. pleas help me i tried like this in below:but it dose not work what is the problem.
public class MainActivity extends AppCompatActivity {
Button b; Button b2; String name;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
name = data.getStringExtra("name").toString();
Toast.makeText(MainActivity.this,name+ "", Toast.LENGTH_LONG).show();}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b=(Button)findViewById(R.id.b);
b=(Button)findViewById(R.id.b);
b2=(Button)findViewById(R.id.b2);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
b2.setText(name);}});}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.mainmenu, menu);
return true;}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
FragmentManager manager = getFragmentManager();
fragment afr = new fragment();
afr.setTargetFragment(afr, 1);
afr.show(manager, "dialog");
return true;}}
class fragment extends DialogFragment {
View v; Intent intent; EditText t1; Button b1; String name;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment, container, false);
t1=(EditText) v.findViewById(R.id.t1);
b1=(Button) v.findViewById(R.id.b1);
intent = new Intent();
int resultCode = 1;
getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, intent);
getDialog().dismiss();
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name=t1.getText().toString();
intent.putExtra("name", name);
fragment.this.dismiss();
}}); return v;}}
You can use interfaces.
Declare interface in fragment and implement it in MainActivity.
https://developer.android.com/training/basics/fragments/communicating.html
In DialogFragment declare
public IDialogCallback {
void onTextWritted(String text);
void onDialogBtnClick()
}
Then declare field in Dialog:
OnDialogCallback mCallback
Later:
#Override
public void onAttach(Context context) {
super.onAttach(context);
mCallback = (ITailLiftCallback) context;
}
Now you can call mCallback.onTextWritted() or mCallback.onDialogBtnClick in DialogFragment. In first case you may put text from TextView and second - put it in OnClickListener of a button.
Then make MainActivity implements IDialogCallback and it is all! :)

I need to create a first and last button for my ViewPager

Hello need help with a class trying to figure out how to create a first and last button in a fragment that will jump to the first item in a ViewPager and the last item in a ViewPager I'm a bit lost with how to implement. Here is the fragment.
public class CrimeFragment extends Fragment {
private static final String ARG_CRIME_ID = "crime_id";
private static final String DIALOG_DATE = "DialogDate";
private static final int REQUEST_DATE = 0;
private Crime mCrime;
private EditText mTitleField;
private Button mDateButton;
private CheckBox mSolvedCheckBox;
private Spinner mSpinner;
private Button mFirstButton;
private Button mLastButton;
public static CrimeFragment newInstance(UUID crimeId) {
Bundle args = new Bundle();
args.putSerializable(ARG_CRIME_ID, crimeId);
CrimeFragment fragment = new CrimeFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) {
return;
}
if (requestCode == REQUEST_DATE) {
Date date =
(Date) data.getSerializableExtra(DatePickerFragment.EXTRA_DATE);
mCrime.setDate(date);
updateDate();
}
}
private void updateDate() {
mDateButton.setText(mCrime.getDate().toString());
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UUID crimeId = (UUID) getArguments().getSerializable(ARG_CRIME_ID);
mCrime = CrimeLab.get(getActivity()).getCrime(crimeId);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_crime, container, false);
mTitleField = (EditText)v.findViewById(R.id.crime_title);
mTitleField.setText(mCrime.getTitle());
mTitleField.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(
CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(
CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
mDateButton = (Button) v.findViewById(R.id.crime_date);
updateDate();
mDateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager manager = getFragmentManager();
DatePickerFragment dialog = DatePickerFragment.newInstance(mCrime.getDate());
dialog.setTargetFragment(CrimeFragment.this, REQUEST_DATE);
dialog.show(manager, DIALOG_DATE);
}
});
mSpinner = (Spinner) v.findViewById(R.id.crime_severity);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getActivity(),
R.array.severity_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(adapter);
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
mCrime.setSeverity((String) mSpinner.getSelectedItem());
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
mSolvedCheckBox = (CheckBox) v.findViewById(R.id.crime_solved);
mSolvedCheckBox.setChecked(mCrime.isSolved());
mSolvedCheckBox.setOnCheckedChangeListener(
new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
mCrime.setSolved(isChecked);
}
});
mFirstButton = (Button) v.findViewById(R.id.first_crime_button);
mFirstButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
mLastButton = (Button) v.findViewById(R.id.last_crime_button);
mLastButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return v;
}
}
Here is the Activity with the ViewPager.
public class CrimePagerActivity extends FragmentActivity{
private static final String EXTRA_CRIME_ID = "com.martin.android.criminalintent.crime_id";
private ViewPager mViewPager;
private List<Crime> mCrimes;
public static Intent newIntent(Context packageContext, UUID crimeId) {
Intent intent = new Intent(packageContext, CrimePagerActivity.class);
intent.putExtra(EXTRA_CRIME_ID, crimeId);
return intent;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crime_pager);
UUID crimeId = (UUID) getIntent().getSerializableExtra(EXTRA_CRIME_ID);
mViewPager = (ViewPager) findViewById(R.id.activity_crime_pager_view_pager);
mCrimes = CrimeLab.get(this).getCrimes();
FragmentManager fragmentManager = getSupportFragmentManager();
mViewPager.setAdapter(new FragmentStatePagerAdapter(fragmentManager) {
#Override
public Fragment getItem(int position) {
Crime crime = mCrimes.get(position);
return CrimeFragment.newInstance(crime.getId());
}
#Override
public int getCount() {
return mCrimes.size();
}
});
for (int i = 0; i < mCrimes.size(); i++) {
if (mCrimes.get(i).getId().equals(crimeId)) {
mViewPager.setCurrentItem(i);
break;
}
}
}
}
For the First button Im pretty sure I just need to set item to 0? For last button I need to set item to size - 1 just not sure how to do that.
In your CrimePagerActivity, write two method's to jump to the ViewPager first page and last page.
CrimePagerActivity.java:
public void jumpToFirstPage() {
mViewPager.setCurrentItem(0);
}
public void jumpToLastPage() {
mViewPager.setCurrentItem(mCrimes.size() - 1);
}
Call those method's from mFirstButton and mLastButton click listener method:
CrimeFragment.java:
mFirstButton = (Button) v.findViewById(R.id.first_crime_button);
mFirstButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((CrimePagerActivity)getActivity()).jumpToFirstPage();
}
});
mLastButton = (Button) v.findViewById(R.id.last_crime_button);
mLastButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((CrimePagerActivity)getActivity()).jumpToLastPage();
}
});
Hope this will work perfectly.
Ok this was a answer that I was given by the teacher incase anyone is interested.
mFirstButton = (Button) v.findViewById(R.id.first_crime_button);
mFirstButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ViewPager pager = (ViewPager) getActivity().findViewById(R.id.activity_crime_pager_view_pager);
pager.setCurrentItem(0);
}
});
mLastButton = (Button) v.findViewById(R.id.last_crime_button);
mLastButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ViewPager pager = (ViewPager) getActivity().findViewById(R.id.activity_crime_pager_view_pager);
pager.setCurrentItem(CrimeLab.get(getActivity()).getCrimes().size()-1);
}
});
Create two button and on click set
viewPager.setCurrentItem(0); // for top
and
viewPager.setCurrentItem(mCrimes.size()); // for last

Categories