Multiple DialogFragment restored after Activity gets killed - android

I have 1 Activity showing 1 DialogFragment and I use setAlwaysFinish app to force the Activity to get killed after onPause.
After pausing & restoring the Activity, I sometimes got 2 or 3 of the same DialogFragment shown. Does anybody know how to prevent this?
Note: I left the Activity with the Dialog still showing. The bug's revealed after several trying with setAlwaysFinish.
Code: Activity
package com.example.testdialog;
import java.util.Calendar;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.View;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void showDialog(View v) {
Calendar today = Calendar.getInstance();
DialogFragment d = DateDialog.newInstance(today.get(Calendar.DAY_OF_MONTH), today.get(Calendar.MONTH), today.get(Calendar.YEAR));
d.show(getSupportFragmentManager(), "mydialog");
}
}
Code: DialogFragment
package com.example.testdialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.DatePicker;
public class DateDialog extends DialogFragment implements OnDateSetListener {
public static final String TAG = "datepicker";
public static final int SEARCH_FLIGHT = 0;
public static final int PASSENGER = 1;
static DateDialog newInstance(int day, int month, int year) {
DateDialog d = new DateDialog();
Bundle bun = new Bundle();
bun.putInt("day", day);
bun.putInt("month", month);
bun.putInt("year", year);
d.setArguments(bun);
return d;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Bundle bun = getArguments();
int year = bun.getInt("year");
int month = bun.getInt("month");
int day = bun.getInt("day");
DatePickerDialog d = new DatePickerDialog(getActivity(), this, year, month, day);
d.setButton(DialogInterface.BUTTON_POSITIVE, "OK", d);
d.setTitle("my dialog");
return d;
}
#Override
public void onDestroyView() {
Dialog d = getDialog();
if (d != null && getRetainInstance())
d.setDismissMessage(null);
super.onDestroyView();
}
}

You can prefent it by using this in your dialogfragment:
#Override
public void show(FragmentManager manager, String tag) {
if (tag != null && tag.equals("FRAGMENT_TAG_MAX_ONE_INSTANCE")) {
// we do not show it twice
if (manager.findFragmentByTag(tag) == null) {
super.show(manager, tag);
}
} else {
super.show(manager, tag);
}
}
and changing:
d.show(getSupportFragmentManager(), "FRAGMENT_TAG_MAX_ONE_INSTANCE");

I have same issue and dont know real way to solve it but this way can help you
private void showLostPassDialog() {
if (!dialogShown) {
dialogShown = true;
DialogFragment newFragment = new LostPassDialogFragment();
newFragment.setCancelable(false);
newFragment.show(getSupportFragmentManager(), "dialog");
}
}
and when destroy dialog set dialogShown=false as i did :
public static class LostPassDialogFragment extends SherlockDialogFragment {
....
#Override
public void onDestroy() {
// TODO Auto-generated method stub
dialogShown = false;
super.onDestroy();
}
hope to b e useful

Whenever you close the dialog, close it properly by calling
dialog.dismiss();
dialog.cancel();

For me this same problem occurred when I usedgetDialog().setOnDismissListener() inside DialogFragment.
After going through DialogFragment's documentation I found this:
Note: DialogFragment own the Dialog.setOnCancelListener and
Dialog.setOnDismissListener callbacks. You must not set them yourself.
To find out about these events, override onCancel(DialogInterface) and
onDismiss(DialogInterface) Source: here
Removing getDialog().setOnDismissListener() and implementing onDismiss(DialogInterface) fixed this.

Related

Using Loader to display data in an AlertDialog?

I am looking for a way to display some data that are retrieved with a loader from an SQLite DB in an AlertDialog. Clicking a name in a ListView will transfer the DB entry ID to the DialogFragment, and based on this, additional data should be loaded.
The loading as such does work but it seems to happen after the AlertDialog is displayed because the message box only shows Null as a value. Does anybody know if it is possible at all to transfer data into a AlertDialog like this? Thanks for your help!
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
#SuppressLint("SimpleDateFormat")
public class BirthdayDetailsMessage extends DialogFragment implements
LoaderCallbacks<Cursor> {
static String DATE_FORMAT;
static final String CALENDAR = "calendar";
private long mRowId;
private String mName;
private String mDate;
private boolean mYearKnown;
private String mAge;
private Calendar mCalendar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCalendar = Calendar.getInstance();
DATE_FORMAT = PrefDateFormat.getPrefDateFormat(getActivity());
Bundle arguments = getArguments();
mRowId = arguments.getLong(ReminderProvider.COLUMN_ROWID);
getLoaderManager().initLoader(0, null, this);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Birthday: "+ mDate +"\n\n"+"Age: "+ mAge)
.setTitle(mName)
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
return builder.create();
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(getActivity(), ContentUris.withAppendedId(
ReminderProvider.CONTENT_URI, mRowId), null, null, null, null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor reminder) {
if (reminder.getCount() == 0) {
new Handler().post(new Runnable() {
#Override
public void run() {
((OnFinishEditor) getActivity()).finishEditor();
}
});
return;
}
mName = reminder.getString(reminder
.getColumnIndexOrThrow(ReminderProvider.COLUMN_NAME));
mYearKnown = (reminder.getInt(reminder
.getColumnIndexOrThrow(ReminderProvider.COLUMN_YEAR))==0? false:true);
Long dateInMillis = reminder.getLong(reminder
.getColumnIndexOrThrow(ReminderProvider.COLUMN_DATE));
Date date = new Date(dateInMillis);
mCalendar.setTime(date);
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
mDate = dateFormat.format(mCalendar.getTime());
if (mYearKnown == true){
mAge = String.valueOf(GetDiffYears.getDiffYears(mCalendar));
}else{
mAge = "age not known";
}
}
#Override
public void onLoaderReset(Loader<Cursor> arg0) {
// nothing to reset for this fragment
}
}
EDIT:
I removed the onCreateDialog method and used the following View instead
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.dialog_fragment, container,
false);
getDialog().setTitle("Name");
Date = (TextView) v.findViewById(R.id.date);
Age = (TextView) v.findViewById(R.id.age);
getLoaderManager().initLoader(0, null, this);
return v;
}
private void updateValues() {
getDialog().setTitle(mName);
Date.setText("Geburtstag: "+ mDate);
Age.setText("Alter: " + mAge);
}
In included updateValues() in onLoadFinished, and created an layout XML for the message body...this way it seems to work properly.
What you will want to do is use a call back method from your Loader to create the dialog. I would not put the Loader in the dialog class, but either in the calling class or as a separate class. Then call/create the dialog in onLoadFinished. The implementation would be similar with AsyncTask.
Alternately, you could create the dialog with some default text, and retain a reference to it in your calling class. Then in your onLoadFinished update the values of the dialog. I'm pretty sure that one would work, but I haven't tested it.

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

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

using a simple dialog fragment in android

I am trying to launch a timePicker on click of edittext
I have constructed most of the things !
Buffet_offerings_breakfast_menu2.java
import java.util.Calendar;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import com.androidbegin.jsonparsetutorial.R;
public class Buffet_offerings_breakfast_menu2 extends Fragment{
RadioGroup radioGroup;
EditText from;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
from=(EditText) getActivity().findViewById(R.id.from_lunch_edit_text_id);
from.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// show the time picker dialog
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
}); // this is on onCreate() method..
}
public void onTimePicked(Calendar time)
{
// display the selected time in the TextView
from.setText(DateFormat.format("h:mm a", time));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
final View view=inflater.inflate(R.layout.buffet_offerings_breakfast_menu2, container, false);
radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup1);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener(){
public void onCheckedChanged(RadioGroup group, int checkedId) {
// checkedId is the RadioButton selected
if(checkedId == R.id.SelectDaysRG_ID)
{
view.findViewById(R.id.linearLayout_individualdays).setVisibility(View.VISIBLE);
}
else if(checkedId == R.id.WeekdaysRG_ID)
{
view.findViewById(R.id.linearLayout_individualdays).setVisibility(View.INVISIBLE);
}
else if(checkedId == R.id.WeekendsRG_ID)
{
view.findViewById(R.id.linearLayout_individualdays).setVisibility(View.INVISIBLE);
}
}
});
return view;
}
}
TimePickerFragment.java
import java.util.Calendar;
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.TimePicker;
public class TimePickerFragment extends DialogFragment implements OnTimeSetListener
{
private TimePickedListener mListener;
public Dialog onCreateDialog(Bundle savedInstanceState)
{
// use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
}
#Override
public void onAttach(Activity activity)
{
// when the fragment is initially shown (i.e. attached to the activity), cast the activity to the callback interface type
super.onAttach(activity);
try
{
mListener = (TimePickedListener) activity;
}
catch (ClassCastException e)
{
throw new ClassCastException(activity.toString() + " must implement " + TimePickedListener.class.getName());
}
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute)
{
// when the time is selected, send it to the activity via its callback interface method
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
mListener.onTimePicked(c);
}
public static interface TimePickedListener
{
public void onTimePicked(Calendar time);
}
}
I am getting two errors as::
Error1::
for line
newFragment.show(getSupportFragmentManager(), "timePicker");
As -
The method getSupportFragmentManager() is undefined for the type new View.OnClickListener(){}
Error2::
for line
return new TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
As -
TimePickerDialog cannot be resolved to a type
How can i resolve this !
For the first error you can store the getSupprotFragmentManager() in a private variable declared in the class and then use it here.
Use getFragmentmanager() instead of getSupportFragmentManager() in your Fragment class.
Implement TimePickedListener interface in ur FragmentActivity and update the fragment
public class MainActivity extends FragmentActivity implements TimePickedListener {
Calendar time =null;
Fragment_Main fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onTimePicked(Calendar time){
fragment = (Fragment_Main) getSupportFragmentManager().findFragmentById(R.id.new_homescreen_two_fragment);
fragment.onTimePicked(time);
}
}
And this will be in ur fragment.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
view = inflater.inflate(R.layout.buffet_offerings_breakfast_menu2, container, false);
from = (EditText) view.findViewById(R.id.etDepDate);
from.setText("Here");
from.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// show the time picker dialog
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "timePicker");
}
}); // this is on onCreate() method..
return view;
}
public void onTimePicked(Calendar time) {
// display the selected time in the TextView
from.setText(DateFormat.format("h:mm a", time));
}
I think your problem is from getSupportFragmentManager() at newFragment.show(getSupportFragmentManager(), "timePicker");. Your TimePickerDialog is a Fragmentwhich is committed into Buffet_offerings_breakfast_menu2 fragment (nested fragment). So use getChildFragmentManager() instead of getSupportFragmentManager().

What would I use to grab a TextView from the MainActivity within a DialogFragment?

I'm writing a simple app that opens up a time picker dialog, asks for input, checks it against the system time, and tells you whether or not it is correct. However, I need to grab the TextView that displays whether it is true or false, and change it within the TimePickerFragment which is a DialogFragment. What should I do?
TimePickerFragment.java
package com.example.timechecker;
import java.util.Calendar;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.widget.TimePicker;
public class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {
int hour;
int minutes;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
minutes = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, 12, 00,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
//Grab the Text View from the Main Activity
// MainActivity m = new MainActivity();
// m.grabText text = new m.grabText();
//Check if given Picker value is == to the system time, display whether or not it is so
if (hourOfDay == hour && minutes == minute) {
text.setText("You are correct!");
} else {
text.setText("You are incorrect!");
}
}
}
MainActivity.java
package com.example.timechecker;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//Creates the dialog with the Time Picker
public void checkTime(View view) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
//Class to grab the Text View for the Dialog Fragment
public class grabText {
TextView text = (TextView) findViewById(R.id.whatTime);
//Uses a method to set the Text View text
public void setText(String string) {
text.setText(string);
}
}
}
When you call findViewById in any activity then i searches in activity layout only. therefore to get the TextView from a dialog you need a reference to that dialog and then you call dialog.findViewById(id_of_field) and this will give you desired TextView.
Hope this Helps
I recently did this, I was able to do this by making MainActivity.java the parent of my DialogFragment.
MainActivity.Java
Add this to MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
mActivity = this;
After, make it global here:
public class MainActivity extends Activity {
MainActivity mActivity;
DialogFragment
Add this to DialogFragment:
public void setParent(MainActivity parent) {
mParent = parent;
}
After, make it global here:
public class ClearDialogModern extends DialogFragment {
MainActivity mParent;
EDIT: Here's where you setParent. Put this in your MainActivity.java onCreate:
newDialogFragment = new DialogFragment();
newDialogFragment.setParent(mActivity);
How to use:
You can now use mParent to reference the MainActivity.java.

Get value from DialogFragment [duplicate]

This question already has answers here:
Receive result from DialogFragment
(15 answers)
Closed 9 years ago.
I want the DialogFragment to return a value to me that was entered in editQuantity when dismissed.
But i am not getting any way to make it work. I can do this by passing the value through the intent but that destroys the progress of the current activity.
Is there any way other than passing through intent that will return me value?
package com.example.myprojectname;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.InputType;
import android.util.Log;
import android.widget.EditText;
public class QuantityDialogFragment extends DialogFragment implements OnClickListener {
private EditText editQuantity;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
editQuantity = new EditText(getActivity());
editQuantity.setInputType(InputType.TYPE_CLASS_NUMBER);
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.app_name)
.setMessage("Please Enter Quantity")
.setPositiveButton("OK", this)
.setNegativeButton("CANCEL", null)
.setView(editQuantity)
.create();
}
#Override
public void onClick(DialogInterface dialog, int position) {
String value = editQuantity.getText().toString();
Log.d("Quantity: ", value);
dialog.dismiss();
}
}
Assuming that you want to foward result to the calling Activity:) try this code snippet:
public class QuantityDialogFragment extends DialogFragment implements OnClickListener {
private EditText editQuantity;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
editQuantity = new EditText(getActivity());
editQuantity.setInputType(InputType.TYPE_CLASS_NUMBER);
return new AlertDialog.Builder(getActivity()).setTitle(R.string.app_name).setMessage("Please Enter Quantity")
.setPositiveButton("OK", this).setNegativeButton("CANCEL", null).setView(editQuantity).create();
}
#Override
public void onClick(DialogInterface dialog, int position) {
String value = editQuantity.getText().toString();
Log.d("Quantity: ", value);
MainActivity callingActivity = (MainActivity) getActivity();
callingActivity.onUserSelectValue(value);
dialog.dismiss();
}
}
and on Your activity add :
public class MainActivity extends FragmentActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
QuantityDialogFragment dialog = new QuantityDialogFragment();
dialog.show(getSupportFragmentManager(), "Dialog");
}
/**
* callback method from QuantityDialogFragment, returning the value of user
* input.
*
* #param selectedValue
*/
public void onUserSelectValue(String selectedValue) {
// TODO add your implementation.
}
}
Taking this idea a little further, I created a listener interface inside the dialog and implemented it in the main activity.
public interface OnDialogResultListener {
public abstract void onPositiveResult(String value);
public abstract void onNegativeResult();
}
public void setOnDialogResultListener(OnDialogResultListener listener) {
this.onDialogResultListener = listener;
}
Call onNegativeResult() inside an overriden onCancel(DialogInterface) and onPositiveResult(String) where you want your dialog to return the value.
Note: don't forget to dismiss() your dialog after calling onPositiveResult() or the dialog window will stay opened.
Then inside your main activity you can create a listener for the dialog, like so:
QuantityDialogFragment dialog = new QuantityDialogFragment();
dialog.setOnDialogResultListener(new QuantityDialogFragment.OnDialogResultListener() {
#Override
public void onPositiveResult(String value) {
//Do something...
}
#Override
public void onNegativeResult() {
//Do something...
}
});
This will make your dialog easier to reuse later.

Categories

Resources