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);
}
Related
i have an activity with multiple buttons , when clicking a button a new activity with two fragments get opened .
i am trying to display a Recyclerview in one of those fragments depending on the button pressed .
the problem is the bundle is null so the recyclerview doesnt show .
the bundle is not null in onAttach,but its null in settextview method
fragment
public class MyFragment extends Fragment {
private OnFragmentInteractionListener mListener;
private static TextView input ;
private static RecyclerView rv ;
private Handler mhandler = new Handler();
public Bundle bundle;
public String data;
public MyFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.fragment_my, container, false);
input =view.findViewById(R.id.input);
rv =view.findViewById(R.id.rv);
return view;
}
public void setTextView(String text){
input.setText(text);
String[] numberList = input.getText().toString();
final Integer[] numbers = new Integer[numberList.length];
ArrayList<String> List ;
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
ListAdapter adapter = new ListAdapter() ;
rv.setAdapter(adapter);
System.out.println("setextview "+bundle);
if(bundle != null){
if (sort1.equals("se")) {
ClassA m1 = new ClassA();
List = m1.etap(numbers);
adapter.setList(mystepsList);
}else if (sort1.equals("in")) {
ClassB = new ClassB();
List = m1.etap(numbers);
adapter.setList(mystepsList);
} }
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
bundle = getActivity().getIntent().getExtras();
sort1 =b.getString("value");
System.out.println("onAttach "+bundle);
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}}
You can it if get extra is null or null, if not null again you can cross check with the key you want to get via containsKey() to check if bundle have data respective to this key or not.
Bundle bundle = getIntent.getExtras();
if (bundle!=null && bundle.containsKey("value") {
boolean value = bundle.getStringExtra("value");
} else {
Log.i("MainActivity", "Bundle is Null or don't have key");
}
Try this code to pass data from activity to fragment
In Activity
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
In Fragment
Bundle bundle= getArguments();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle bundle= getArguments();
if(bundle!=null){
String strtext = bundle.getString("edttext");
}
return inflater.inflate(R.layout.fragment, container, false);
}
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) {
}
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);
}
I want to send data from my activity to my fragment. What I'm doing now is the following.
String itemDescription = workAssignmentItem.getDescription();
Bundle bundle = new Bundle();
bundle.putString("itemDescription", itemDescription);
FirstFragment.newInstance(bundle);
Then in my Fragment I do:
public static FirstFragment newInstance(Bundle bundle) {
FirstFragment fragment = new FirstFragment();
fragment.setArguments(bundle);
return fragment;
}
However, when I try to do 'getArguments().getString("itemDescription");'in my onCreate, as so:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
description = getArguments().getString("itemDescription");
}
it will not work. getArguments returns null. I'm not quite sure why it returns null, since multiple sources on the internet say this is the way to do it.
Can anyone point me in the right direction?
thanks in advance
You dont need bundle to pass a single string in Fragment
String itemDescription = workAssignmentItem.getDescription();
FirstFragment.newInstance(itemDescription);
Fragment Change to like this :
public static FirstFragment newInstance(String itemDescription){
FirstFragment fragment=new FirstFragment();
bundle args=new Bundle();
args.putString("itemDescription",itemDescription);
fragment.setArguments(args);
return fragment;
}
and onCreate like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
description = getArguments().getString("itemDescription");
}
So actually i had this problem
"Bundle NULL"
I resolve it by implementing the method onFragmentResult.
Context : I want to pass my selected contact inside a fragment into a spinner inside an another fragment
Where i pass my data into the Bundle :
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.item_done) {
// Create a String array to store the names of the selected contacts
ArrayList<String> selectedContacts = new ArrayList<>();
for (int i=0; i < listView.getCount(); i++) {
if (listView.isItemChecked(i)) {
selectedContacts.add(listView.getItemAtPosition(i).toString());
}
}
// Add the String array to the bundle
Bundle bundle = new Bundle();
bundle.putStringArrayList("SELECTED_CONTACTS", selectedContacts);
Log.d("ContactsFragment", "Setting result with selectedContacts: " + selectedContacts);
getParentFragmentManager().setFragmentResult("SELECTED_CONTACTS", bundle);
return true;
}
return super.onOptionsItemSelected(item);
}
}
and here is where i retreive my data :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_sender, container, false);
// Find the spinner views in the layout and set their adapters
responsesSpinner = view.findViewById(R.id.responses_spinner);
contactsSpinner = view.findViewById(R.id.contacts_spinner);
getParentFragmentManager().setFragmentResultListener("SELECTED_CONTACTS", this, new FragmentResultListener() {
#Override
public void onFragmentResult(#NonNull String requestKey, #NonNull Bundle bundle) {
if (requestKey.equals("SELECTED_CONTACTS")) {
ArrayList<String> selectedContacts = bundle.getStringArrayList("SELECTED_CONTACTS");
Log.d("SenderFragment", "Received selectedContacts: " + selectedContacts);
if (selectedContacts != null && selectedContacts.size() > 0) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, selectedContacts);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
contactsSpinner.setAdapter(adapter);
}
}else{
Toast.makeText(getContext(), "not working", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
I need to know how to get array list using Bundle in fragment , in the examples I have seen they are using ints or strings. how to get fragments ? In my activity it was working good getting the arraylist
my updated code
public class SingleViewActivity extends FragmentActivity {
ImageView imageView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page_view);
ArrayList<Listitem> personArrayList = new ArrayList<Listitem>();
// add some ListItem's...
DemoObjectFragment f = DemoObjectFragment.newInstance(personArrayList);
ViewPager mViewPager = (ViewPager) findViewById(R.id.pager);
imageView = (ImageView) findViewById(R.id.funnyimage);
Bundle bundle = getIntent().getExtras();
Log.d("s","singleview");
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
/*
DemoCollectionPagerAdapter mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter( getSupportFragmentManager());
ViewPager mViewPager = (ViewPager) findViewById(R.id.pager);
imageView = (ImageView) findViewById(R.id.funnyimage);
Bundle bundle = getIntent().getExtras();
Log.d("s","singleview");
mViewPager.setAdapter(mDemoCollectionPagerAdapter);*/
/* if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
MyFragment myrag = new MyFragment();
myrag.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(android.R.id.content, myrag).commit();
}
*/
}
// Since this is an object collection, use a FragmentStatePagerAdapter,
// and NOT a FragmentPagerAdapter.
public class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
public static final String ARG_OBJECT = "Person_List";
public DemoCollectionPagerAdapter(FragmentManager fm, ArrayList<Listitem> personArrayList)
{
super(fm);
Log.d("s","adapterview");
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new DemoObjectFragment();
Bundle args = new Bundle();
// Our object is just an integer :-P
args.putInt(DemoObjectFragment.ARG_PERSON_LIST, i + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return 100;
}
#Override
public CharSequence getPageTitle(int position) {
return "OBJECT " + (position + 1);
}
}
// Instances of this class are fragments representing a single
// object in our collection.
public class DemoObjectFragment extends Fragment {
public static final String ARG_PERSON_LIST = "Person_List";
private ArrayList<Listitem> items;
public DemoObjectFragment newInstance(ArrayList<Listitem> items) {
DemoObjectFragment f = new DemoObjectFragment();
Bundle args = new Bundle();
args.putParcelableArrayList(ARG_PERSON_LIST, items);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args.containsKey(ARG_PERSON_LIST)) {
// UNTESTED: probably will need to cast this
this.items = args.getParcelableArrayList(ARG_PERSON_LIST);
} else { // avoid the NullPointerException later by initializing the list
this.items = new ArrayList<Listitem>();
}
// use this.items as you wish, but it will be empty if you didn't set the Bundle argument correctly
}
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// The last two arguments ensure LayoutParams are inflated
// properly.
View rootView = inflater.inflate(
R.layout.fragment_collection_object, container, false);
// Bundle args = getArguments();
// ((TextView) rootView.findViewById(R.id.text1)).setText(Integer.toString(args.getInt(ARG_OBJECT)));
Bundle args= new Bundle();
ArrayList<Listitem> personArrayList = args.getParcelableArrayList("Person_List");
System.out.print(personArrayList);
System.out.print("here1");
if (personArrayList != null && !personArrayList.isEmpty()) {
for (Listitem person : personArrayList) {
Picasso.
with(getActivity()).
load(person.url)
.placeholder(R.drawable.logo)
.fit()
.noFade()
.into(imageView);
Log.i("PersonsActivity",String.valueOf(person.url));
}
}
return rootView;
}
}
}
I have 2 errors now :
for newInstance as I mentioned before I cannot refer to not static .
and I am getting error now for picasso
edit 3
This is a good start for what you are looking for and assumes you have correctly implemented Parcelable for the ListItem class.
Somewhere in your Activity
ArrayList<ListItem> personArrayList = new ArrayList<ListItem>();
// add some ListItem's...
DemoObjectFragment f = DemoObjectFragment.newInstance(personArrayList);
From the top of your Fragment class (note: it is not a static class)
public class DemoObjectFragment extends Fragment {
public static final String ARG_PERSON_LIST = "Person_List";
private ArrayList<ListItem> items;
public static DemoObjectFragment newInstance(ArrayList<ListItem> items) {
DemoObjectFragment f = new DemoObjectFragment();
Bundle args = new Bundle();
args.putParcelableArrayList(ARG_PERSON_LIST, items);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args.containsKey(ARG_PERSON_LIST)) {
// UNTESTED: probably will need to cast this
this.items = args.getParcelableArrayList(ARG_PERSON_LIST);
} else { // avoid the NullPointerException later by initializing the list
this.items = new ArrayList<ListItem>();
}
/*
* use this.items as you wish, but
* it will be empty if you didn't set the
* Bundle argument correctly
*/
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment_collection_object, container, false);
ImageView imageView = (ImageView) rootView.findViewById(R.id.imageView);
Log.i("DemoObjectFragment", "Inside onCreateView");
if (this.items.isEmpty()) {
Log.i("DemoObjectFragment", "Warning: There are no items!");
}
if (this.items != null) {
for (Listitem person : items) {
Picasso.with(getActivity())
.load(person.url)
.placeholder(R.drawable.logo)
.fit()
.noFade()
.into(imageView);
Log.i("DemoObjectFragment", "Person URL: " + String.valueOf(person.url));
}
} else {
Log.i("DemoObjectFragment", "Oh no! items is null!");
}
return rootView;
}
}
From what I see the fragment has no way of knowing what personArrayList you are referring to. Usually you pass the list as an extra argument in the newInstance method (step 1), save it in the bundle (step 2) and then retrieve it from the bundle in onCreate (step 3).
To fix you code you would have to either initialize the list with a new ArrayList(), but it would be empty in that case, or do as I said above (you're just missing step 1, so you're almost done).