Is it possible to pass data from an Activity using Bundle to a Fragment that has no OnCreate
Try this one
public class SampleActivity extends AppCompactActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample);
if (savedInstanceState == null) {
Fragment fragment = new SampleFragment();
Bundle args = new Bundle();
args.putInt("sample_int", 1);
fragment.setArguments(args);
getSupportFragmentManager().beginTransaction()
.add(R.id.container, fragment)
.commit();
}
}
}
public class SampleFragment extends Fragment {
#Override
public void onResume() {
Bundle args = getArguments();
if (args != null) {
int sampleInt = args.getInt("sample_int", -1);
}
}
}
From Activity, you send data with intent as:
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
and in Fragment onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("edttext");
return inflater.inflate(R.layout.fragment, container, false);
}
Related
When passing arguments from the activity to the fragment, the arguments are lost.
Activity:
public class DatePickerFragmentActivity extends AppCompatActivity {
private static final String EXTRA_CRIME_DATE = "CRIME_DATE";
private Date mCrimeDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
mCrimeDate = (Date) getIntent().getSerializableExtra(EXTRA_CRIME_DATE);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragment_container);
if (fragment == null) {
fragment = createFragment();
fm.beginTransaction().add(R.id.fragment_container, fragment).commit();
}
}
private Fragment createFragment(){
return DatePickerFragment.newInstance(mCrimeDate);
}
}
At this point, the fragment still has data in the bundle, checked by debugger.
fm.beginTransaction().add(R.id.fragment_container, fragment).commit();
Fragment:
public class DatePickerFragment extends DialogFragment {
private static final String ARG_DATE = "date";
public static DatePickerFragment newInstance(Date date) {
Bundle args = new Bundle();
args.putSerializable(ARG_DATE, date);
DatePickerFragment fragment = new DatePickerFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDate = (Date) getArguments().getSerializable(ARG_DATE);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.dialog_date, container, false);
}
}
But in this place the bundle is already empty:
mDate = (Date) getArguments().getSerializable(ARG_DATE);
The layout of my application looks like this:
ListView Activity/Fragment -> ViewPager Activity/Fragment -> DatePicker Activity/Fragment
i'm trying to send data from my activity class to its tab fragment, but in the fragment adapter it received no data and produced error nullPointerException.
here is my code
from activity
Intent receivedIntent = getIntent();
String tenant = null;
if ((bundle = receivedIntent.getExtras()) != null) {
tenant = (String) bundle.get("tenant");
}
TabFragment tabFragment = new TabFragment();
bundle.putString("tenant", tenant);
tabFragment.setArguments(bundle);
to fragment
Bundle getTenant = this.getArguments();
if(getTenant != null) {
tenant = getTenant.getString("tenant");
System.out.println("Tab fragment: " + tenant);
}else {
System.out.println("Tab fragment: null");
}
pager adapter
case 0:
TabFragment tabFragment = new TabFragment();
tabFragment.setArguments(bundle);
return tabFragment;
In your fragment do this
if(getArguments() != null) {
tenant = getArguments().getString("tenant");
System.out.println("Tab fragment: " + tenant);
}else {
System.out.println("Tab fragment: null");
}
instead of
Bundle getTenant = this.getArguments();
if(getTenant != null) {
tenant = getTenant.getString("tenant");
System.out.println("Tab fragment: " + tenant);
}else {
System.out.println("Tab fragment: null");
}
Use below code:
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
and in Fragment onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("edttext");
return inflater.inflate(R.layout.fragment, container, false);
}
Another way You are able to pass data using Interface like Below:
1 step: I created public interface in my Activity and setter for it:
Private OnAboutDataReceivedListener mAboutDataListener;
public interface OnAboutDataReceivedListener {
void onDataReceived(YourModelClass model);
}
public void setAboutDataListener(OnAboutDataReceivedListener listener) {
this.mAboutDataListener = listener;
}
2 step: I implemented this interface in my Fragment and set listener:
public class YourActivity extends BaseFragment implements YourBaseActivity.OnAboutDataReceivedListener
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mActivity = (YourActivity) getActivity();
mActivity.setAboutDataListener(this);
}
3 step: I overrided interface's method:
#Override
public void onDataReceived(YourClassModel model) {
}
Activity A
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ActivityA);
Bundle b = new Bundle();
b.putString("mobile", "123456789");
FragmentA fragmentA = new FragmentA ();
fragmentA .setArguments(b);}
FragmentA
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_fragmentA, container, false);
String txtMobile = getArguments().getString("mobile");
Log.i("mobile2",txtMobile);
mobile.setText(txtMobile);}
I have tried above solution but showing error that
Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
May be It's about the way you are adding fragment to the class:
Bundle b = new Bundle();
b.putString("mobile", "123456789");
FragmentA fragmentA = new FragmentA ();
fragmentA .setArguments(b);
fm.beginTransaction()
.replace(placeholder, new FragmentA(), tabId)
.commit();
can you provide more data about how did you add it ?
Create your fragment like this
public static MyFragment newInstance(String string) {
Bundle args = new Bundle();
args.putString("string",string);
MyFragment fragment = new MyFragment();
fragment.setArguments(args);
return fragment;
}
And then in Fragment onCreate use getArguments() for pulling that String. Don't forget to check getArguments() for null.
Try to fetch the argument in onCreate method of fragment with default value constructor:
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String txtMobile = getArguments().getString("mobile", "");
}
and make sure you commit the fragment transaction after settting the arguments in fragment. :)
First check that your argument is not null.
For example
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_fragmentA, container, false);
if(getArguments()!=null){
String txtMobile = getArguments().getString("mobile");
Log.i("mobile2",txtMobile);
mobile.setText(txtMobile);
}
}
try this:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null){
String txtMobile = savedInstanceState.getString("mobile");
}
}
you can use inteface to pass data from activity to fragment
In your activity
public interface FragmentRefreshListener {
void onRefresh(String mydata);
}
public FragmentRefreshListener fragmentRefreshListener;
public void setFragmentRefreshListener(FragmentRefreshListener fragmentRefreshListener) {
this.fragmentRefreshListener = fragmentRefreshListener;
}
public FragmentRefreshListener getFragmentRefreshListener() {
return fragmentRefreshListener;
}
Then inside your fragment add below code
((MainActivity) getActivity()).setFragmentRefreshListener(new MainActivity.FragmentRefreshListener() {
#Override
public void onRefresh(String mydata) {
// write your logic here
}
});
use following in your activity to pass data from activity to fragment
getFragmentRefreshListener().onRefresh("dummy text");
I am trying to send data from activity to fragment,but in fragment i am getting null instead of my values,following is my code can any one help me with this?
String nofrndthere="nofrnds";
String frndthere="frnds";
if(jsonary.length()==0)
{
// Toast.makeText(MainActivity.this,"Null",Toast.LENGTH_SHORT).show();
Bundle bundle = new Bundle();
bundle.putString("nofrndsavailable", nofrndthere);
HomeFragment fragobj = new HomeFragment();
fragobj.setArguments(bundle);
}
else if(jsonary.length()!=0)
{
// Toast.makeText(MainActivity.this,"Not Null",Toast.LENGTH_SHORT).show();
Bundle bundle = new Bundle();
bundle.putString("frndsavailable", frndthere);
HomeFragment fragobj = new HomeFragment();
fragobj.setArguments(bundle);
}
HomeFragment
public class HomeFragment extends Fragment {
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
private FragmentTabHost tabHost;
private SearchView searchView;
private String strtext;
private String strtextss,strtextfnrdval;
public HomeFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
tabHost = new FragmentTabHost(getActivity());
tabHost.setup(getActivity(), getChildFragmentManager(), R.layout.my_parent_fragment);
Bundle bundle = this.getArguments();
strtext = bundle.getString("user_login_id");
if (getArguments() != null) {
strtextss = bundle.getString("nofrndsavailable");
strtextfnrdval= bundle.getString("frndsavailable");
}
System.out.println("DATASSSSS : " +strtextss+strtextfnrdval);
System.out.println("<<<<<<<<<<<<<< Session ID : " + strtext+strtextss+strtextfnrdval);
Bundle arg1 = new Bundle();
arg1.putInt("Arg for Frag1", 1);
if(strtext!=null) {
arg1.putString("user_logid", strtext);
}
tabHost.addTab(tabHost.newTabSpec("one").setIndicator(getTabIndicator(tabHost.getContext(), R.drawable.icon_profile_tabs,"Home")), DiscoverFragment.class, arg1);
Bundle arg2 = new Bundle();
arg2.putInt("Arg for Frag2", 2);
if(strtext!=null) {
arg2.putString("user_logid_sectab", strtext);
}
tabHost.addTab(tabHost.newTabSpec("Sec").
setIndicator(getTabIndicator(tabHost.getContext(), R.drawable.icon_frnds_tab,"Invite")), ShopFragment.class, arg2);
Bundle arg3 = new Bundle();
arg3.putInt("Arg for Frag3", 3);
if(strtext!=null) {
arg3.putString("user_logid_thirdtab", strtext);
}
tabHost.addTab(tabHost.newTabSpec("Third").
setIndicator(getTabIndicator(tabHost.getContext(), R.drawable.icon_wish_tab,"Wish")), Thirdtab.class, arg3);
Bundle arg4 = new Bundle();
arg4.putInt("Arg for Frag4", 4);
if(strtext!=null) {
arg4.putString("user_logid_fourthtab", strtext);
}
if(strtextss == getArguments().getString("nofrndsavailable"))
{
// Toast.makeText(getActivity(), "Null in home", Toast.LENGTH_SHORT).show();
System.out.println("Null in home");
tabHost.addTab(tabHost.newTabSpec("Four").
setIndicator(getTabIndicator(tabHost.getContext(), R.drawable.icon_notification_tab, "Alert")), FourthTabs.class, arg4);
}
else if(strtextfnrdval == getArguments().getString("frndsavailable"))
{
// Toast.makeText(getActivity(), "Not Null in home", Toast.LENGTH_SHORT).show();
System.out.println("NotNull in home");
tabHost.addTab(tabHost.newTabSpec("Four").
setIndicator(getTabIndicator(tabHost.getContext(), R.drawable.icon_fnrdalert, "Alert")), FourthTabs.class, arg4);
}
return tabHost;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
public View getTabIndicator(Context context, int icon,String text) {
View view = LayoutInflater.from(context).inflate(R.layout.tab_layout, null);
ImageView iv = (ImageView) view.findViewById(R.id.indicatorImageView);
iv.setImageResource(icon);
TextView txt = (TextView) view.findViewById(R.id.txttb);
txt.setText(text);
return view;
}
}
before you open the fragment this is how you can attach the bundle to it. following code should be in your activity to put the bundle in the fragment.
Fragment fragment = new YourFragmentClass();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
now that you have attached the bundle open the fragment .
Things which you have to do is Override onCreate() method in your fragment and this is how you will receive the bundle.
private String mParam1; // these are global variable to get the data
private String mParam2; // after you receive the data, it can be used under `onActivityCreated()`
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1,null);
mParam2 = getArguments().getString(ARG_PARAM2,null);
// I have updated the code thisis how you can check which string is empty.
// cause if you try to do some work on null object you will get error
if(mParam1 == null){
// it is empty
}else{
// it is not empty
}
if(mParam2 == null){
// it is empty
}else{
// it is not empty
}
}
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// here you can use mParam1 and mParam2
}
Update
with conversation I had with you, you can start your fragment though your activity like this to tell the fragment if the array is null or not
HomeFragment fragobj = new HomeFragment();
Bundle bundle = new Bundle();
if(jsonary.length()==0){
bundle.putBoolean("isAvailable", false);
}else{
bundle.putBoolean("isAvailable", true);
}
fragobj.setArguments(bundle);
and in the onCreate() method of your fragment this is how you can read the boolean value
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
boolean mParam1 = getArguments().getBoolean("isAvailable",false);
}
}
Updated
ok now i realize what you are doing (fragment is already started before setting the bundle), you can try this. (it is quite cheeky )
make a method inside your HomeFragment
public static void setData(boolean isAvailable){
// here you will get the actual data
}
Now in your Activity when you get the JSONArray depending on that you can that you can do this.
HomeFragment.setData(true/false)
From your question I think you are getting user_login_id as null from bundle
Bundle bundle = this.getArguments();
strtext = bundle.getString("user_login_id");
This is because you have not put any string with user_login_id in your bundle
if(jsonary.length()==0)
{
// Toast.makeText(MainActivity.this,"Null",Toast.LENGTH_SHORT).show();
Bundle bundle = new Bundle();
bundle.putString("nofrndsavailable", nofrndthere);
bundle.putString("user_login_id", <userid>); //put user id here
HomeFragment fragobj = new HomeFragment();
fragobj.setArguments(bundle);
}
else if(jsonary.length()!=0)
{
// Toast.makeText(MainActivity.this,"Not Null",Toast.LENGTH_SHORT).show();
Bundle bundle = new Bundle();
bundle.putString("frndsavailable", frndthere);
bundle.putString("user_login_id",<userid>);// put user id here
HomeFragment fragobj = new HomeFragment();
fragobj.setArguments(bundle);
}
I am new to Fragments. I tried simple fragment example. But it throws the error. I don't know what is wrong.
public class NewActivity extends Activity {
int mStackLevel = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
Fragment newFragment = NewFragment
.newInstance(mStackLevel);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.simple_fragment, newFragment).commit();
} else {
mStackLevel = savedInstanceState.getInt("level");
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("level", mStackLevel);
}
public static class NewFragment extends Fragment {
int mNum;
Context context;
static NewFragment newInstance(int num) {
NewFragment f = new NewFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNum = getArguments() != null ? getArguments().getInt("num") : 1;
context = getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.example_fragment, container,
false);
return v;
}
}
}
My logcat shows:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.FragmentExample/com.example.FragmentExample.NewActivity}: java.lang.IllegalArgumentException: No view found for id 0x7f07003c for fragment NewFragment{40ff0850 #0 id=0x7f07003c}
ft.add(R.id.simple_fragment, newFragment).commit();
you missed setContentView for your Activity. Your Fragment can not be added without a View hierarchy.
Note : Your Fragment is hosted by an activity. So you need to set the content to the activity first.
Just replace this method with your method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(Your_layout_file);
if (savedInstanceState == null) {
Fragment newFragment = NewFragment
.newInstance(mStackLevel);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.simple_fragment, newFragment).commit();
} else {
mStackLevel = savedInstanceState.getInt("level");
}
}
you missed this line setContentView(Your_layout_file);
This answer highlights a silly mistake that may occur, that arises when nesting fragments or you are converting activities to fragments.
If you are trying to replace a fragment within a fragment with the fragmentManager but you are not inflating the parent fragment that can cause an issue.
In BaseFragment.java OnCreateView:
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.replace(R.id.container, new DifferentFragment())
.commit();
}
return super.onCreateView(inflater, container, savedInstanceState);
Replace super.onCreateView(inflater, container, savedInstanceState);
with inflating the correct layout for the fragment:
return inflater.inflate(R.layout.base_fragment, container, false);