How to open a fragment from BroadcastReceiver? [duplicate] - android

This question already has answers here:
How can I launch fragment in broadcast receiver
(3 answers)
Closed 7 years ago.
I want to open a fragment through a sms-receiver, how should I implement that? Any help is appreciated.
Receiver source code:
public class SMSReceiver extends BroadcastReceiver {
private String body, vsn;
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle == null)
return;
Object[] pdus = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdus.length; i++) {
SmsMessage sms = SmsMessage.createFromPdu((byte[]) pdus[i]);
body = sms.getMessageBody().toString();
PaymentTransaksi.setSmsDetail(body);
Intent showPaymentForm = new Intent();
showPaymentForm.setClassName("showPaymentForm",
"id.dutapulsa.bayartagihan.PaymentTransaksi");
showPaymentForm.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
}
And this is the fragment source code:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
paymentRootView = inflater.inflate(R.layout.payment_main, container,
false);
return paymentRootView;
}

I know this question is quite old, but I want to share my solution with the community because it is a common task.
1.) In your layout file (e.g. of your MainActivity) create a container, which will be replaced by the current fragment.
2.) Add the following code snippet to your Activity (don't forget to change it a bit, if neccessary)
public void updateFragment(Class<?> clazz, Bundle args) {
String tag = clazz.getName();
FragmentManager fragmentManager = getFragmentManager();
Fragment fragment = fragmentManager.findFragmentByTag(tag);
if (fragment == null) {
fragment = Fragment.instantiate(this, tag, args);
fragment.setRetainInstance(true);
}
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.addToBackStack(tag);
transaction.replace(R.id.container, fragment, tag);
transaction.commit();
}
3.) Now you can simply call this method from your BroadcastReceiver, like this one:
updateFragment(ContentFragment.class, null);
4.) For dialogs I extend from DialogFragment and have the following method in my Activity:
public static void showProgressDialog(Activity activity, String title, String message) {
FragmentManager fragmentManager = activity.getFragmentManager();
Bundle bundle = new Bundle();
bundle.putString(ProgressDialogFragment.ARG_TITLE, title);
bundle.putString(ProgressDialogFragment.ARG_MESSAGE, message);
ProgressDialogFragment mProgressDialog = new ProgressDialogFragment();
mProgressDialog.setArguments(bundle);
mProgressDialog.setRetainInstance(true);
mProgressDialog.show(fragmentManager, "Dialog");
}
Hope I can help! ;-)

Related

Set Fragment EditText from the parent Activty

I have a ProfileFragment class which contains two setters:
public void setPseudo(String pseudo){
textPseudo.setText(pseudo);
}
public void setEmail(String email){
textEmail.setText(email);
}
And in my Activity I would like to call these functions:
user = new ProfileFragment();
if (intent != null) {
user.setPseudo(intent.getStringExtra(USER_PSEUDO));
user.setEmail(intent.getStringExtra(USER_EMAIL));
}
It says "can't resolve method...".
Does it mean I can't do this?
Are you sure you don't have a Profile class with setters? Not a Fragment?
Fragments generally don't use setters, they use arguments.
Reason being: If you call setEmail, and then you called to some view setText within the new Fragment, you get a NullPointerException because that TextView was never initialized
Fragment profileFragment = new ProfileFragment();
Bundle args = new Bundle();
if (intent != null) {
args.putAll(intent.getExtras());
}
profileFragment.setArguments(args);
// Show new Fragment
getSupportFragmentManager()
.replace(R.id.content, profileFragment)
.commit();
And inside your Fragment's onCreateView, you can now use this, for example
final Bundle args = getArguments();
String pseudo = "";
if (args != null) {
pseudo = args.getString(YourActivity.USER_PSEUDO);
}
textPseudo.setText(pseudo);

Launch fragment map with address to search

Im having a issue I dont know how to resolve.
I have a fragment with a editText and a button.
The button launches a fragment map like this:
public void onClick(View view) {
//Fragment fragment = null;
switch (view.getId()) {
case R.id.SearchButton:
Home activity = (Home) getActivity();
if(activity != null)activity.openMapFragment();
break;
}
and the function openMapFragment():
public void openMapFragment(){
Fragment fragment = new gMapFragment();
replaceFragment(fragment);
}
How would i do to send the text inserted on editText field as a address to look for on map fragment?
You should use bundle to pass data to a fragment :
public void openMapFragment(String args){
Fragment fragment = new gMapFragment();
Bundle bundle = new Bundle();
bundle.putString("foo", args);
fragment.setArguments(bundle);
replaceFragment(fragment);
}
And to retrieve data :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//...
String foo = getArguments() != null ? getArguments().getString("foo") : "";
//...
}

How to add fragment on activity in android? [duplicate]

This question already has answers here:
Start a fragment via Intent within a Fragment
(5 answers)
Closed 6 years ago.
i want to replace activity to a fragment, this code is not working.
Intent intent = new Intent(Activity.this, Fragment.class);
startActivity(intent);
finish();
You cannot switch from an Activity to Fragment, because a Fragment does not have its own existence without an Activity. i.e. a Fragment works inside an Activity.
Basically, Fragments are mainly used to create multi-pane screens.
Inside an Activity if you can replace Fragments (associated with the Activity) as mentioned in the above code examples to change the UI.
Try like this in your activity
#Override
public void replaceFragment(Fragment fragment, boolean addToBackStack) {
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
if (addToBackStack) {
transaction.addToBackStack(null);
} else {
getSupportFragmentManager().popBackStack(null,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
transaction.replace(R.id.flContent, fragment);
transaction.commitAllowingStateLoss();
getSupportFragmentManager().executePendingTransactions();
}
and use like this
YourFragment mYourFrag = new YourFragment ();
replaceFragment(mYourFrag , false);
Create a Fragmen class like
public class FragmentName extends android.support.v4.app.Fragment {}
And then you are able to cast a activity to view like:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View returner = null;
Intent intent = new Intent([CONTEXT],[CLASSNAME.class]);
Bundle args = this.getArguments();
final Window w = [LocalActivityManager].startActivity("Title", intent);
final View wd = w != null ? w.getDecorView() : null;
if (wd != null) {
ViewParent parent = wd.getParent();
if(parent != null) {
ViewGroup v = (ViewGroup)parent;
v.removeView(wd);
}
wd.setVisibility(View.VISIBLE);
wd.setFocusableInTouchMode(true);
if(wd instanceof ViewGroup) {
((ViewGroup) wd).setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
}
}
returner = wd;
return returner;
}

Getting arguments from a bundle

I'm trying to pass arguments from my Activity to a Fragment and I'm using this code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
String message = getIntent().getStringExtra(Intent.EXTRA_TEXT);
DetailActivityFragment fragment = new DetailActivityFragment();
Bundle bundle = new Bundle();
bundle.putString(INTENT_EXTRA, message);
fragment.setArguments(bundle);
}
I'm getting the value of the message variable through an Intent Extra and that works fine, so far.
Then I'm passing it as an argument to my fragment but then, when I call getArguments() from that specific Fragment it returns a null Bundle.
Does anybody have a solution to this?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
if (bundle != null && bundle.containsKey(DetailActivity.INTENT_EXTRA)) {
forecast = bundle.getString(DetailActivity.INTENT_EXTRA);
} else if (bundle == null) {
Toast.makeText(getActivity(), "Error", Toast.LENGTH_LONG).show();
}
}
The upper method displays a Toast message "Error" when I run the app...
The best way to use arguments with your fragment is to use the newInstance function of the fragment.Create a static method that gets your params and pass them in the fragment through the new instance function as below:
public static myFragment newInstance(String param1, String param2) {
myFragment fragment = new myFragment ();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
And then on create set your global arguments:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
on your main activity you will create the fragment like
myFragment __myFragment = myFragment.newInstance("test","test");
That should work
This is a correct approach
Send (in the Activity):
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
final DetailActivityFragment frg = new DetailActivityFragment ();
ft.replace(R.id.container, frg);
final Bundle bdl = new Bundle();
bdl.putString("yourKey", "Some Value");
frg.setArguments(bdl);
ft.commit();
Receive (in the Fragment):
final Bundle bdl = getArguments();
String str = "";
try
{
str = bdl.getString("yourKey");
}
catch(final Exception e)
{
// Do nothing
}

How to pass Arguments to Fragment from Activity

I have an activity which instantiates and populates a Fragment through a adopter class. I want to pass values/objects to this Fragment adopter class so that i can dictate layout etc.
I have tried passing bundles using the setArgument method but my code bombs out and not sure why. As i understand, i can collect the bundle at the onCreate method in the adopter class. I see the arguments are set correctly immediately after the commented code but alas it crashes after that and i don't understand why. If i remove the bundle code it doesnt crash. :(
Below is my code, does anybody know where i should put the bundle code, commented out?
public class LoginScreen extends ActionBarActivity {
private final String ARG_SELECTED_LAYOUT_ID = "selectedLayoutId";
private final int DEFAULT_LAYOUT = R.layout.layout_list;
private int mSelectedLayoutId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
mSelectedLayoutId = DEFAULT_LAYOUT;
if (savedInstanceState != null) {
mSelectedLayoutId = savedInstanceState.getInt(ARG_SELECTED_LAYOUT_ID);
}
addLayoutTab(
actionBar, R.layout.layout_list, R.drawable.ic_list, "list");
addLayoutTab(
actionBar, R.layout.layout_grid, R.drawable.ic_grid, "grid");
addLayoutTab(
actionBar, R.layout.layout_staggered_grid, R.drawable.ic_staggered, "staggered");
addLayoutTab(
actionBar, R.layout.layout_spannable_grid, R.drawable.ic_spannable, "spannable");
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(ARG_SELECTED_LAYOUT_ID, mSelectedLayoutId);
}
private void addLayoutTab(ActionBar actionBar, int layoutId, int iconId, String tag) {
ActionBar.Tab tab = actionBar.newTab()
.setText("")
.setIcon(iconId)
.setTabListener(new TabListener(layoutId, tag));
actionBar.addTab(tab, layoutId == mSelectedLayoutId);
}
public class TabListener implements ActionBar.TabListener {
private LayoutFragment mFragment;
private final int mLayoutId;
private final String mTag;
public TabListener(int layoutId, String tag) {
mLayoutId = layoutId;
mTag = tag;
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
mFragment = (LayoutFragment) getSupportFragmentManager().findFragmentByTag(mTag);
if (mFragment == null) {
mFragment = (LayoutFragment) LayoutFragment.newInstance(mLayoutId);
ft.add(R.id.content, mFragment, mTag);
} else {
ft.attach(mFragment);
}
/*
Bundle bundle = new Bundle();
bundle.putInt("noTiles", 4);
mFragment.setArguments(bundle);
*/
mSelectedLayoutId = mFragment.getLayoutId();
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
if (mFragment != null) {
ft.detach(mFragment);
}
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
}
}
Logcat
03-03 11:56:53.675 32507-32507/weebuns.predictionking E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: weebuns.predictionking, PID: 32507
java.lang.RuntimeException: Unable to start activity ComponentInfo{weebuns.predictionking/weebuns.predictionking.LoginScreen}: java.lang.NullPointerException: Attempt to invoke virtual method 'void weebuns.predictionking.LayoutFragment.setArguments(android.os.Bundle)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void weebuns.predictionking.LayoutFragment.setArguments(android.os.Bundle)' on a null object reference
To pass argument to your fragment, it's recommended to create a public static method to instanciate your fragment like :
public static MyFragment newInstance(String firstArg) {
MyFragment f = new MyFragment ();
Bundle args = new Bundle();
args.putString("ARG1", firstArg);
f.setArguments(args);
return f;
}
And then retrieve your args in onCreateView() method like :
String arg = getArguments().getString("ARG1");
Use the static method to instanciate a new fragment with your arguments in other fragment or activities like :
MyFragment f = MyFragment.newInstance(myArg);
It's hard to say without seeing the logcat, but surely you are missing to call the commit() method on the FragmentTransaction. Also remember to set the arguments to the fragment before calling ft.commit().
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
mFragment = (LayoutFragment) getSupportFragmentManager().findFragmentByTag(mTag);
if (mFragment == null) {
Bundle bundle = new Bundle();
bundle.putInt("noTiles", 4);
mFragment = (LayoutFragment) LayoutFragment.newInstance(mLayoutId);
mFragment.setArguments(bundle);
//ft.add(R.id.content, mFragment, mTag).commit();
ft.add(R.id.content, mFragment, mTag);
} else {
ft.attach(mFragment);
}
mSelectedLayoutId = mFragment.getLayoutId();
}
In your activity
Bundle args = new Bundle();
args.putString("Menu", "Your String");
Fragment detail = new FragmeantOne();
detail.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, detail).commit();
In your Fragment.. in onCreateView()
String menu = getArguments().getString("Menu");
someTextView.setText(menu);
You can use Bundle to transfer data from activity to fragments or transfre data from fragment to fragment.
Bundle bundle = new Bundle();
DisplayDataList fragment = new DisplayDataList();
bundle.putString("listitem", "Buyer,Seller");
fragment.setArguments(bundle);
getFragmentManager().beginTransaction().replace(
R.id.frame_container, fragment).addToBackStack(null).commit();
Where you want to recieve that bundle i.w in DisplayDataList Fragment class. You have to use getArguments() method.
DisplayDataList
Bundle bundle = getArguments();
String getdata = bundle.getString("listitem");
System.out.println("Data got-->>> " + getdata);
Hope this will help you.
You can use Bundle to transfer data between activity and fragment/Dialog fragment
Send data From Your Activity to Fragment() -> onClickBtn()
val f = PaymentBottomSheet()
val bundle = Bundle()
bundle.putString("coins", walletBinding.edCoins.text.toString())
bundle.putString("method", getJsonData()[adapter.selected].method)
bundle.putString("name", walletBinding.edNickName.text.toString())
bundle.putString("acc", walletBinding.edAccountId.text.toString())
f.arguments = bundle
f.show(supportFragmentManager, f.tag)
Retrieved Data from Your Activity (Your fragment code look like this) onCreateView()
val bundle = Bundle(arguments)
coins = bundle.getString("coins")
method = bundle.getString("method")
name = bundle.getString("name")
id = bundle.getString("acc")
Timber.d("Coins $coins, Method $method, Name $name, ID $id")
Thank You

Categories

Resources