AlertDialog not working in a Fragment - android

Hello I'm doing an app in which a button is pressed and an AlertDialog window pops up with a TimePicker. However it is in a Fragment so AppCompatActivity will not do.
Fragment itself:
public class time_change extends Fragment implements TimePickerFragment.TimeDialogListener {
private static final String DIALOG_TIME = "MainActivity.TimeDialog";
private View v;
private Button timePickerAlertDialog;
private ImageButton back;
#Override
#Nullable
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.pamokos, container, false);
timePickerAlertDialog = (Button) v.findViewById(R.id.alert_dialog_time_picker);
timePickerAlertDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TimePickerFragment dialog = TimePickerFragment.newInstance();
dialog.show(getActivity().getFragmentManager(), "TimePickerFragment");
}
});
back = (ImageButton) v.findViewById(R.id.back_btn1);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Pamokos fr = new Pamokos();
time_change fr2 = new time_change();
android.app.FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.activity_frag, fr);
fragmentTransaction.remove(fr2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
return v;
}
#Override
public void onFinishDialog(String time) {
Toast.makeText(getActivity(), "Selected Time : " + time, Toast.LENGTH_SHORT).show();
}
}
But It shows an error at
dialog.show(getActivity().getFragmentManager(), "TimePickerFragment");
Saying "Cannot resolve method 'show(android.app.FragmentManager, java.lang.String)'"
Full code is from this tutorial https://www.androidtutorialpoint.com/basics/android-alert-dialog-tutorial-working-time-picker-date-picker-list-dialogs/
I'm quite lost.

Replace
TimePickerFragment dialog = TimePickerFragment.newInstance();
dialog.show(getActivity().getFragmentManager(), "TimePickerFragment");
with this
FragmentManager fm = getActivity().getSupportFragmentManager();
TimePickerFragment dialog = new TimePickerFragment ();
dialog.show(fm, "TimePickerFragment");

add
below
import inside your DialogFragment class
import android.support.v4.app.DialogFragment;
Replace
dialog.show(getActivity().getFragmentManager(), "TimePickerFragment");
with
dialog.show(getSupportFragmentManager(), "TimePickerFragment");

Related

How can I update a textview from one fragment to another

I have an activity "MainActivity" that contains two fragments. Fragment1 has a EditText and a button. When the user presses the button the text inside the EditText will be sent to Fragment2 which only has a TextView. But I can't quite figureout how to send the text from EditText in Fragment1 to TextView in Fragment2. If someone could help? Appreciated. Thanks
Fragment1
package org.pctechtips.myfragmentapp;
/**
* Created by george on 5/16/17.
*/
public class ButtonFragment extends Fragment {
Button bt;
EditText editText;
TextView txtView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.button_fragment,
container, false);
txtView = (TextView) view.findViewById(R.id.textView_fragment1);
editText = (EditText) view.findViewById(R.id.editText_fragment1);
bt = (Button) view.findViewById(R.id.button_fragment1);
bt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
buttonClicked(v);
}
});
return view;
}
public void buttonClicked (View view) {
.onButtonClick(edittext.getText().toString());
}
}
MainActivity
package org.pctechtips.myfragmentapp;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*fragments 1 section*/
FragmentManager fm1 = getFragmentManager();
FragmentTransaction ft1 = fm1.beginTransaction();
ButtonFragment bf = new ButtonFragment();
ft1.add(R.id.button_fragment1, bf);
ft1.commit();
/*Fragment 2 section*/
FragmentManager fm2 = getFragmentManager();
FragmentTransaction ft2 = fm2.beginTransaction();
TextviewFragment tf = new TextviewFragment();
ft2.add(R.id.textView_fragment2, tf);
ft2.commit();
}
}
Fragment2
public class TextviewFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.text_fragment, container, false);
}
}
The quick and easy answer is to call getView().findViewById() from the activity (as shown below). The more proper approach is to give your fragments an interface that gets and retrieves the text. Below is the code for the quick and easy method, but when you create a fragment in Android studio it shows you how to do the more proper interface approach.
package org.pctechtips.myfragmentapp;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*fragments 1 section*/
FragmentManager fm1 = getFragmentManager();
FragmentTransaction ft1 = fm1.beginTransaction();
ButtonFragment bf = new ButtonFragment();
ft1.add(R.id.button_fragment1, bf);
ft1.commit();
/*Fragment 2 section*/
FragmentManager fm2 = getFragmentManager();
FragmentTransaction ft2 = fm2.beginTransaction();
TextviewFragment tf = new TextviewFragment();
ft2.add(R.id.textView_fragment2, tf);
ft2.commit();
EditText et = (EditText) ft1.getView().findViewById(YOUR_EDITTEXT_ID);
Button button = (Button) ft1.getView().findViewById(YOUR_BUTTON_ID);
TextView tv = (TextView) ft2.getView().findViewById(YOUR_TEXTVIEW_ID);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tv.setText(et.getText();)
}
});
}
You can do it by several ways. For example via Activity like in Official Docs. But, I'm prefer send broadcast messages via LocalBroadcastManager like in this answer of war_Hero:
In Sending Fragment(Fragment B - Your ButtonFragment)
public class FragmentB {
private void sendMessage() {
Intent intent = new Intent("custom-event-name");
intent.putExtra("message", "your message");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
And in the Message to be Received Fragment(FRAGMENT A - Your TextviewFragment)
public class FragmentA {
#Override
public void onCreate(Bundle savedInstanceState) {
...
// Register receiver
LocalBroadcastManager.getInstance(this).registerReceiver(receiver,
new IntentFilter("custom-event-name"));
}
// This will be called whenever an Intent with an action named "custom-event-name" is broadcasted.
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
}
};
}
And don't forget to unregister receiver:
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
}

Reload Fragment after DialogFragment dismisses

I have Index.class as the Activity, when the user choose Profile, it will call fragment Profile
if (id == R.id.nav_profile){
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.setCustomAnimations(R.anim.enter,R.anim.exit,R.anim.enter,R.anim.exit);
transaction.replace(R.id.flContent, new Profile(), "ProfileFragment");
transaction.addToBackStack(null);
viewPager.getAdapter().notifyDataSetChanged();
transaction.commit();
}
Now in Profile Fragment, when the user clicks a button it will call DevRegistration Activity
case 1:
btnBeDeveloper.setText("Developer Console");
btnBeDeveloper.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent index = new Intent(getActivity(), DevRegistration.class);
startActivity(index);
}
});
break;
Then in DevRegistration class, after I click the register button, it will display a dialog fragment class.
What I want to do is when I click the button inside the dialog fragment, how can I refresh the profile fragment?
Dialog Fragment Class:
public class df_SuccessDevRegistration extends DialogFragment {
Button btnDevGoProfile;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
View rootView = inflater.inflate(R.layout.fragment_success_developer_registration, container, false);
btnDevGoProfile = (Button) rootView.findViewById(R.id.btnDevGoProfile);
btnDevGoProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dismiss();
getFragmentManager().popBackStack();
getActivity().finish();
Profile fragment = (Profile)
getSupportFragmentManager().findFragmentByTag("ProfileFragment");
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction()
transaction.detach(fragment);
transaction.attach(fragment);
transaction.commit();
}
});
return rootView;
}
}
By the way, I dont know why getSupportFragmentManager isnt working. It shows an error cannot resolve method... when I used getFragmentManager() it crashes.
You could also try this to refresh the current fragment
FragmentTransaction ftran = getActivity().getFragmentManager().beginTransaction();
ftran .detach(this).attach(this).commit();
In your dev registration activity , get your fragment :
Profile profileFragment = getSupportFragmentManager().findFragmentByTag("ProfileFragment");
To refresh it you can try :
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.detach(profileFragment);
transaction.attach(profileFragment);
transaction.commit();
EDIT:
Can you try this ?
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
View rootView = inflater.inflate(R.layout.fragment_success_developer_registration, container, false);
btnDevGoProfile = (Button) rootView.findViewById(R.id.btnDevGoProfile);
return rootView;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
btnDevGoProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getSupportFragmentManager().popBackStack();
Profile fragment = (Profile)
getActivity().getSupportFragmentManager().findFragmentByTag("ProfileFragment");
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction()
transaction.detach(fragment);
transaction.attach(fragment);
transaction.commit();
getActivity().finish();
dismiss();
}
});
}
Hope this helps.

Android: activity does not work after backing from a fragment

i have an activity like WelcomeActivity and a fragment like GuideFragment.
i have a button in WelcomeActivity which cause a navigation to GuideFragment. Also i have a button in GuideFragment which navigates back to the WelcomeActivity.
For first time it goes to GuideFragment by clicking on the button and cames back to WelcomeActivity by pressing btn_back. Hwever after coming back to activity, the button does not work any more.
whats wrong with my code?
activity clas:
public class WelcomeActivity extends FragmentActivity
{
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
GuideFragment guideFragment = new GuideFragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
guideFragment = new GuideFragment();
}
public void onGuideClick(View view)
{
fragmentTransaction.replace(android.R.id.content, guideFragment);
fragmentTransaction.addToBackStack(null);
fragmentManager.popBackStack();
fragmentTransaction.commit();
}
}
and fragment class:
public class GuideFragment extends Fragment
{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// create ContextThemeWrapper from the original Activity Context with the custom theme
Context contextThemeWrapper = new ContextThemeWrapper(getActivity(), R.style.guideFrag);
// clone the inflater using the ContextThemeWrapper
LayoutInflater localInflater = inflater.cloneInContext(contextThemeWrapper);
// inflate the layout using the cloned inflater, not default inflater
View view = inflater.inflate(R.layout.fragment_guide, container, false);
Button button = (Button) view.findViewById(R.id.btn_back);
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
getActivity().getFragmentManager ().popBackStack();
}
});
return view;
}
}
Thanks
Remove fragmentManager.popBackStack(); from onGuideClick(View view). Also the transaction should not be a member field.
public void onGuideClick(View view) {
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(android.R.id.content, guideFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
You also initiate the GuideFragment twice, once is enough.
I changed WelcomeActivity like this:
public class WelcomeActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
}
public void onGuideClick(View view)
{
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
GuideFragment guideFragment = new GuideFragment();
fragmentTransaction.replace(android.R.id.content, guideFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}

Incompatible types of fragment

Hi I have small app in android where Im using fragments with navigation drawer for menu. But now I want show in my fragments dialog popup window when user click on something and there I get these errors:
MainActivity:
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new FindPeopleFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
First error I get on fragment = new HomeFragment(); >>incompatible types.
Second error on HomeFragment at onCreateView method >> method does not override or implement a method from a supertype
HomeFragment:
public class HomeFragment extends FragmentActivity {
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
final RelativeLayout rlPolievkaShowDialog=(RelativeLayout)rootView.findViewById(R.id.rlPolievkaButton);
rlPolievkaShowDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return rootView;
}
private void showDialog() {
DialogFragment newFragment = DialogFragmentAlergeny.newInstance();
newFragment.show(getSupportFragmentManager(), "dialog");
}
}
DialogFragmentAlergeny:
public class DialogFragmentAlergeny extends DialogFragment {
public static DialogFragmentAlergeny newInstance() {
DialogFragmentAlergeny frag = new DialogFragmentAlergeny();
return frag;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
View view = getActivity().getLayoutInflater().inflate(R.layout.alergeny_dialog, null);
alertDialogBuilder.setView(view);
alertDialogBuilder.setTitle(getString(R.string.alergeny_dialog_title));
alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return alertDialogBuilder.create();
}
}
How Fix it:
HomeFragment must extend Fragment
You must use/import android.support.v4.app.Fragment, android.support.v4.app.DialogFragment, android.support.v4.app.FragmentActivity everywhere where needed.
newFragment.show(getActivity().getSupportFragmentManager(), "dialog"); use getsupportManager not FragmentManager()
Use FragmentManager fragmentManager = getSupportFragmentManager(); not FragmentManager()
Thats all thx all for help.
HomeFragment is not a fragment but a FragmentActivity...change extends class to Fragment
public class HomeFragment extends FragmentActivity { ... }

Android: Error using calling AlertDialog from inside Fragment

Why do i always get error when i try to call AlertDialog from my fragment?
At first i try to put it in OnCreate but it also get the same error log...
MainFragment.java
public class MainFragment extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_fragment);
if (savedInstanceState == null) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
LoginFragment fragment = new LoginFragment();
ft.add(R.id.simple_fragment, fragment).commit();
}
}
}
LoginFragment.java
public class LoginFragment extends Fragment implements OnClickListener {
Helper application;
static LoginFragment newInstance() {
LoginFragment f = new LoginFragment();
Bundle args = new Bundle();
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(getActivity().getApplicationContext());
dlgAlert.setMessage("TEST");
dlgAlert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
dlgAlert.setCancelable(false);
dlgAlert.create().show();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_login, container, false);
Button inner = (Button) v.findViewById(R.id.btnSignUp);
inner.setOnClickListener(LoginFragment.this);
return v;
}
#Override
public void onClick(View v) {
}
}
and this is the error log
12-19 10:14:25.295: E/AndroidRuntime(1083): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myfirstapp/com.example.fragment.MainFragment}: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
anyone has ever encountered this before?
Just try
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(getActivity());
If you are dealing with nested fragments. When a fragment has it's own child fragments you need to use getChildFragmentManager().

Categories

Resources