using a simple dialog fragment in android - 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().

Related

how to replace fragments tabs inside mainfragment by using button click

hey guys i'm sufferening to problem how to call tab fragments inside fragment.i am always click on button show unfortunately app closed and in logcat show nullpointer exception.i implemented but gettting errror null object reference
Lead_Fragment Main fragment
in which define the code add all tabs in toolbar and show the view of mainfragment
in which define the code add all tabs in toolbar and show the view of mainfragment
in which define the code add all tabs in toolbar and show the view of mainfragment
package com.example.dashboard;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.admin.bdayevent.R;
public class Lead_Fragment extends Fragment implements TabLayout.OnTabSelectedListener,Frgmentchangelistener {
private TabLayout tabLayout;
private ViewPager viewPager;
Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_lead_fragment, container, false);
tabLayout = (TabLayout)view.findViewById(R.id.leadtabLayout);
//Adding the tabs using addTab() method
tabLayout.addTab(tabLayout.newTab().setText("Step1"));
tabLayout.addTab(tabLayout.newTab().setText("Step2"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
//Initializing viewPager
viewPager = (ViewPager)view.findViewById(R.id.leadmain_container);
//Creating our pager adapter
Lead_Pager adapter = new Lead_Pager(getFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
//Adding onTabSelectedListener to swipe views
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(this);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageScrollStateChanged(int state)
{
}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
public void onPageSelected(int position) {
}
});
Lead_step1 fragment1 = new Lead_step1();
FragmentManager fragmentManager =getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.leadmain_container, fragment1);
// fragmentTransaction.hide(Step1.this);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
return view;
}
public void onTabSelected(TabLayout.Tab tab)
{
viewPager.setCurrentItem(tab.getPosition());
// Toast.makeText(getApplicationContext(),"tab selected "+tab.getPosition(),Toast.LENGTH_SHORT).show();
}
// public void replaceFragment(Fragment fragment, boolean addToBackStack) {
// FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
// if (addToBackStack)
// {
// transaction.addToBackStack(null);
// }
// transaction.replace(R.id.fragment_container, fragment);
// transaction.commit();
// getChildFragmentManager().executePendingTransactions();
// }
public void onTabUnselected(TabLayout.Tab tab)
{
// Toast.makeText(getApplicationContext(),"tab unselected",Toast.LENGTH_SHORT).show();
}
public void onTabReselected(TabLayout.Tab tab)
{
}
void switchFragment1(int target)
{
viewPager.setCurrentItem(target);
}
#Override
public void replaceFragment(Fragment fragment)
{
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.leadmain_container, fragment, fragment.toString());
fragmentTransaction.addToBackStack(fragment.toString());
fragmentTransaction.commit();
}
}
Lead_tab1 this is the first fragment which contain the form like registration page those values stored in sqlite db but when i cliked on button show the null object Rerference(nul pointer) this is the first fragment which contain the form like registration page those values stored in sqlite db but when i cliked on button show the null object Rerference(nul pointer)
package com.example.dashboard;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.admin.bdayevent.R;
import com.example.admin.bdayevent.Registration;
/**
* Created by admin on 4/28/2016.
*/
public class Lead_step1 extends Fragment implements View.OnClickListener{
EditText customername,customermobile,referncename;
Button nextbtn;
String MobilePattern = "[0-9]{10}";
SharedPreferences lead_pref = null;
Lead_Fragment lead_fragment;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view= inflater.inflate(R.layout.lead_step1, container, false);
customername = (EditText) view.findViewById(R.id.lead_customername);
customermobile = (EditText) view.findViewById(R.id.lead_mobileno);
referncename = (EditText) view.findViewById(R.id.lead_referencename);
nextbtn=(Button)view.findViewById(R.id.leadnext);
nextbtn.setOnClickListener(this);
return view;
}
public void onClick(View v)
{
if (customername.getText().toString().trim().equals("")) {
customername.setError("please enter name");
}
else if (customermobile.getText().toString().trim().equals("")) {
customermobile.setError("please enter 10 digit mobileno");
}
else if (referncename.getText().toString().trim().equals("")) {
referncename.setError("please enter refernce name");
}
else if(customermobile.getText().toString().matches(MobilePattern) == false)
{
customermobile.setError("plz enter 10 digit mobile number");
}
else
{
((Lead_Fragment) getParentFragment()).switchFragment1(2);
String Lead_name=customername.getText().toString().trim();
String Lead_Mobile=customermobile.getText().toString().trim();
String Lead_Reference=referncename.getText().toString();
System.out.println("value of leads"+Lead_name+":"+Lead_Mobile+":"+Lead_Reference);
lead_pref = getActivity().getSharedPreferences("lead_pref",getActivity().MODE_PRIVATE);
SharedPreferences.Editor editor = lead_pref.edit();
editor.putString("key_Lead_name", Lead_name);
editor.putString("key_Lead_Mobile", Lead_Mobile);
editor.putString("key_Lead_Reference", Lead_Reference);
editor.commit();
}
}
}
Lead_tab2, this is the second fragment which contain the form like registration page similar to first fragement which in define 3 editetext.
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;
import com.example.admin.bdayevent.Database;
import com.example.admin.bdayevent.R;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Lead_step2 extends Fragment implements View.OnClickListener {
EditText eventname, eventlocation, eventdate, eventtime;
Button submit_btn;
private int mYear, mMonth, mDay, mHour, mMinute;
DatePickerDialog datePickerDialog;
private static final String TIME24HOURS_PATTERN =
" (([0-1]?[0-9])|(2[0-3])):[0-5][0-9] ";
private Pattern pattern;
private Matcher matcher;
SharedPreferences Lead2;
ProgressDialog progressDialog;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.lead_step2, container, false);
eventname = (EditText) view.findViewById(R.id.lead_eventname);
eventlocation = (EditText) view.findViewById(R.id.lead_location);
eventdate = (EditText) view.findViewById(R.id.lead_date);
eventtime = (EditText) view.findViewById(R.id.lead_time);
submit_btn = (Button) view.findViewById(R.id.lead_submitbtn);
eventdate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
datePickerDialog = new DatePickerDialog(getActivity(),
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
eventdate.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
} else {
//datePickerDialog.
}
}
});
eventtime.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
// Launch Time Picker Dialog
TimePickerDialog timePickerDialog = new TimePickerDialog(getActivity(),
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute)
{
boolean isPM = (hourOfDay >= 12);
eventtime.setText(String.format("%02d:%02d %s", (hourOfDay == 12 || hourOfDay == 0) ? 12 : hourOfDay % 12, minute, isPM ? "PM" : "AM"));
}
}, mHour, mMinute, false);
timePickerDialog.show();
} else {
// Hide your calender here
}
}
});
submit_btn.setOnClickListener(this);
return view;
}
#Override
public void onClick(View v)
{
if (eventname.getText().toString().trim().equals("")) {
eventname.setError("please enter eventname");
} else if (eventlocation.getText().toString().trim().equals("")) {
eventname.setError("please enter eventlocation");
} else if (eventdate.getText().toString().trim().equals("")) {
eventdate.setError("please enter evendate");
} else if (eventtime.getText().toString().trim().equals("")) {
eventtime.setError("please enter Eventtime");
}
else if (validateTime(String.valueOf(eventdate.getText())))
{
eventdate.setError("please enter Valid Date");
}
else if(validateDate(String.valueOf(eventtime.getText())))
{
eventtime.setError("please enter Valid Date");
}
else
{
Toast.makeText(getContext(), "Welcome to leadgenration", Toast.LENGTH_SHORT);
// ((Lead_Fragment) getParentFragment()).switchFragment1(2);
new Lead_generation().execute();
}
}
class Lead_generation extends AsyncTask<Void,Void,Boolean>
{
protected void onPreExecute()
{
//System.out.println("value of user is preexecute:" + User_mobile + "" + User_password);
progressDialog = new ProgressDialog(getActivity(),
AlertDialog.THEME_HOLO_LIGHT);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Authenting....plz wait");
progressDialog.show();
}
protected Boolean doInBackground(Void... params)
{
if(Send_Lead())
{
}
return false;
}
protected void onPostExecute(Boolean result)
{
progressDialog.dismiss();
if(result==true)
{
Toast.makeText(getActivity(),"Lead Added Successfully",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getActivity(),"not add Lead",Toast.LENGTH_SHORT).show();
}
}
}
public boolean Send_Lead()
{
Lead2=getActivity().getSharedPreferences("lead_pref", getContext().MODE_PRIVATE);
String Lead_Cutom_name = Lead2.getString("key_firstname","");
String Lead_Custom_contact = Lead2.getString("key_lastname","");
String Lead_Custom_reference = Lead2.getString("key_user_org","");
String Lead_Eventname=eventname.getText().toString().trim();
String Lead_Eventlocation=eventlocation.getText().toString().trim();
String Lead_EventDate=eventdate.getText().toString().trim();
String Lead_EventTime=eventtime.getText().toString().trim();
System.out.println("value of all leads"+Lead_Cutom_name+" "+Lead_Custom_contact+" "
+Lead_Custom_reference+" "+Lead_Eventname+" "+Lead_Eventlocation+" "+Lead_EventDate+" "+Lead_EventTime);
if(Database.ADD_Lead(getActivity(),Lead_Cutom_name,Lead_Custom_contact,Lead_Custom_reference,Lead_Eventname,Lead_Eventlocation,
Lead_EventDate,Lead_EventTime))
{
return true;
}
else
{
return false;
}
}
public boolean validateTime(final String time)
{
matcher = pattern.matcher(time);
return matcher.matches();
}
public boolean validateDate(String date)
{
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
try {
sdf.parse(date);
return true;
} catch (ParseException ex) {
return false;
}
}
}
LOCATFILE
this is the logcat file show background processing also show the any type of error occur in your project
05-11 06:16:53.858 13059-13059/com.example.admin.bdayevent E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.admin.bdayevent, PID: 13059
java.lang.ClassCastException: com.example.dashboard.New_dashboard cannot be cast to com.example.admin.bdayevent.Registration
at com.example.dashboard.Lead_step1.onClick(Lead_step1.java:67)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Try like this
put one container or use the existing container and make a fragment transaction there when you click the button. like this
NEWFragment new_fragment = new NEWFragment();
FragmentTransaction transaction = (context).getSupportFragmentManager().beginTransaction();
transaction.add(R.id.container, new_fragment, new_fragment.toString());
transaction.addToBackStack(new_fragment.toString());
new_fragment.setArguments(bundle);
transaction.commitAllowingStateLoss();

Multiple DialogFragment restored after Activity gets killed

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.

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.

Refreshing a fragment View on back from settings change

What I'm trying to accomplish is have my view refresh when someone comes back from the settings and changes their preference. I thought this would work but it is not. Any ideas on how i can accomplish this?
import java.text.SimpleDateFormat;
import java.util.Calendar;
import com.projectcaruso.naturalfamilyplanning.R;
import android.annotation.SuppressLint;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.TextView;
public class ChartingFragment extends Fragment implements OnDateSetListener {
SharedPreferences mPreferences;
Boolean symptothermal;
Boolean mucus_stamps;
Boolean fertile_infertile;
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
// TODO Auto-generated method stub
}
public void showDatePickerDialog(View v) {
DatePickerFragment newFragment = new DatePickerFragment();
newFragment.show(getChildFragmentManager(), "datePicker");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
}
private void init() {
mPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
symptothermal = mPreferences.getBoolean("symptothermal", true);
mucus_stamps = mPreferences.getBoolean("mucus_stamps", true);
fertile_infertile = mPreferences.getBoolean("fertile_infertil", true);
}
#SuppressLint("SimpleDateFormat")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view;
view = setcontrolvisability(inflater);
return view;
}
#Override
public void onResume() {
super.onResume();
View vg = getView().findViewById(R.id.charting);
vg.invalidate();
init();
}
private View setcontrolvisability(LayoutInflater inflater) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment_charting, null);
TextView temp;
if (!symptothermal) {
temp = (TextView) view.findViewById(R.id.temp);
temp.setVisibility(View.GONE);
temp = (TextView) view.findViewById(R.id.tempvalue);
temp.setVisibility(View.GONE);
}
if (!mucus_stamps) {
temp = (TextView) view.findViewById(R.id.stamp);
temp.setVisibility(View.GONE);
temp = (TextView) view.findViewById(R.id.stampvalue);
temp.setVisibility(View.GONE);
}
if (!fertile_infertile) {
temp = (TextView) view.findViewById(R.id.fertile);
temp.setVisibility(View.GONE);
temp = (TextView) view.findViewById(R.id.fertileswitch);
temp.setVisibility(View.GONE);
}
temp = (TextView) view.findViewById(R.id.dateselected);
SimpleDateFormat dfDate_day= new SimpleDateFormat("MM/dd/yyyy");
String dt="";
Calendar c = Calendar.getInstance();
dt=dfDate_day.format(c.getTime());
temp.setText(dt);
return view;
}
}
I'd suggest to use startActivityForResult and pass a Bundle if sub-activity (FragmentActivity) has been changed.
1) From your Activity start Preference Activity:
Intent intent = new Intent(this, PreferenceActivity.class);
if (!this.isFinishing())
startActivityForResult(intent, REQUEST_UPDATE);
2) Override onActivityResult
#Override
protected void onActivityResult(int reqCode, int resCode, Intent data) {
super.onActivityResult(reqCode, resCode, data);
Log.d(TAG, "Received Result: " + reqCode + " / " + resCode);
}
3) in Subactivity (PreferenceActivity) monitor which keys have been changed and pass it as a bundle if you like
public class PrefsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener,
OnPreferenceChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
#Override
public boolean onPreferenceChange(Preference arg0, Object arg1) {
getParent().setResult(MainActivity.RESULT_PREFERENCES_CHANGED); // constant
}
#Override
public void onResume() {
super.onResume();
getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
super.onPause();
}
}

TimePickerDialog is not displaying / showing

I have a TimePickerDialog that I would like to show the user when she pushes on a button, so that she can choose a time to set the display to (some time other than the current time). Currently when the button is pushed the current time is displayed in a TextView and a Toast. Also the screen Darkens and a small box in the center of screen appears. The TimePickerDialog does not display to the user.
Here's the code;
import java.util.Calendar;
import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class AddAlarmActivity extends FragmentActivity implements TimePickerDialog.OnTimeSetListener, TimePickerDialog.OnDismissListener {
Button setTime;
public int hour_local;
public int minute_local;
public Dialog onCreateDialog;
public TimePicker timePicker;
public TextView displayAlarm;
static final int TIME_DIALOG_ID = 999;
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_alarm);
//add a TextView thing to this part
setTime = (Button) findViewById(R.id.button_set_time);
displayAlarm = (TextView) findViewById(R.id.tvDisplayTime);
setTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onCreateDialog(savedInstanceState);
showTimePickerDialog(timePicker);
displayAlarm.setText(hour_local + ":" + minute_local);
}
});
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
hour_local = c.get(Calendar.HOUR_OF_DAY);
minute_local = c.get(Calendar.MINUTE);
Context context = getApplicationContext();
CharSequence text = hour_local + ":" + minute_local;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getApplicationContext(), this, hour_local, minute_local,
DateFormat.is24HourFormat(getApplicationContext()));
}
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new DialogFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
public void onDismiss(DialogInterface dialog){
System.out.println("oui c'est très bon !");
}
public void onTimeSet(TimePicker view, int hour_l, int minute_l) {
hour_local = hour_l;
minute_local = minute_l;
System.out.println("voila");
}
}
I would advice that you follow the developer sites way of doing it:
Create a static class that handles the dialog fragment
public static class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// Do something with the time chosen by the user
}
}
Call this method in your button on click listener:
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
Source here.
public class AddAlarmActivity extends FragmentActivity {
Button setTime;
public static int hour_local;
public static int minute_local;
public Dialog onCreateDialog;
public TimePicker timePicker;
public static TextView displayAlarm;
public static int hour_alarm;
public static int minute_alarm;
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_alarm);
setTime = (Button) findViewById(R.id.button_set_time);
displayAlarm = (TextView) findViewById(R.id.tvDisplayTime);
final Calendar c = Calendar.getInstance();
hour_local = c.get(Calendar.HOUR_OF_DAY);
minute_local = c.get(Calendar.MINUTE);
displayAlarm.setText(hour_local + ":" + minute_local);
setTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showTimePickerDialog(timePicker);
}
});
}
public void onTimeSet(TimePicker view, int hour_l, int minute_l) {
// intentionally blank
}
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
/*New static class*/
public static class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
hour_local = c.get(Calendar.HOUR_OF_DAY);
minute_local = c.get(Calendar.MINUTE);
Context context = getActivity();
CharSequence text = hour_local + ":" + minute_local;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour_local, minute_local,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hour_l, int minute_l) {
hour_alarm = hour_l;
minute_alarm = minute_l;
displayAlarm.setText(hour_alarm + ":" + minute_alarm);
}
}
}
TimePickerDialog dialog = new TimePickerDialog(this,OnTimeSet,DateTime.Now.Hour,DateTime.Now.Minute,true);
dialog.Show();
void OnTimeSet (object sender, TimePickerDialog.TimeSetEventArgs e)
{
}

Categories

Resources