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) {
}
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);
}
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;
}
Hello everyone i need help in passing data from activity to fragment.
im using the this way but getting error of null pointer .
In main Activity
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.leftfeedback:
handleChanges();
break;
}
}
private void handleChanges() {
FeedBackFragment feedBackFragment =new FeedBackFragment();
if (feedBackFragment != null) {
feedBackFragment.fragmentCommunication(ExtraData);
} else {
Log.i(TAG, "Fragment 2 is not initialized");
}
}
in fragment side
all given data is coming i checked with log before to set on
public class FeedBackFragment extends Fragment{
private static final String TAG ="FeedBackFragment" ;
View view;
TextView feedbackEditText;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.feedback_fragemnt, container, false);
feedbackEditText = (TextView) view.findViewById(R.id.feedbackEditText);
return view;
}
public void fragmentCommunication(String feedBackData) {
log.i(TAG,feedBackData);
try {
JSONObject jsonObject = new JSONObject(feedBackData);
String message = jsonObject.getString("message");
if(message.trim()!=null){
feedbackEditText.setText(message);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This could happen if you haven't created the fragment in the right way.
If you dynamically add the fragment with:
getSupportFragmentManager().beginTransaction().
replace(R.id.container, new FeedBackFragment(), YOUR_FRAGMENT_TAG).
commit();
You can use the following code to communicate with the fragment.
private void handleChanges() {
FeedBackFragment feedBackFragment =new FeedBackFragment();
// you need to use id if you add the fragment via layout.
//FeedBackFragment feedBackFragment = (FeedBackFragment)
getSupportFragmentManager().findFragmentById(R.id.your_feed_back_fragment_id);
// If you dynamically add the fragment, use tag to find the fragment.
FeedBackFragment feedBackFragment = (FeedBackFragment)
getSupportFragmentManager().findFragmentByTag(YOUR_FRAGMENT_TAG);
if (feedBackFragment != null) {
feedBackFragment.fragmentCommunication(ExtraData);
} else {
Log.i(TAG, "Fragment 2 is not initialized");
}
}
Read more at Creating and Using Fragments.
Because of feedBackFragment not create, so Edittext is null
you should attach your feedBackFragment to MainActivity.
FeedBackFragment feedBackFragment;
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.leftfeedback:
handleChanges();
break;
}
}
private void handleChanges() {
if (null == feedBackFragment) {
feedBackFragment = new FeedBackFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(contentId, feedBackFragment);
transaction.commit();
}
feedBackFragment.fragmentCommunication(ExtraData);
}
http://www.androhub.com/android-pass-data-from-activity-to-fragment/
check this link here you find exact what you want with better clearification
I have changed some of your code try this. It works for you.
private void handleChanges() {
FeedBackFragment feedBackFragment =new FeedBackFragment();
if (feedBackFragment != null) {
Bundle bundle = new Bundle();
bundle.putString("edttext", "ExtraData");
// set Fragmentclass Arguments
feedBackFragment.setArguments(bundle);
} else {
Log.i(TAG, "Fragment 2 is not initialized");
}
}
And in Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
String strtext = getArguments().getString("edttext");
view = inflater.inflate(R.layout.feedback_fragemnt, container, false);
feedbackEditText = (TextView) view.findViewById(R.id.feedbackEditText);
feedbackEditText.setText(strtext);
return view;
}
try this :
private void handleChanges() {
Bundle bundle = new Bundle();
bundle.putString("KEY", "string");
FeedBackFragment fragment = new FeedBackFragment();
fragment.setArguments(bundle);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
on your fragment : to get the data :
Bundle bundle = getArguments();
if (bundle != null) {
String data = bundle.getString("KEY");
}
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);
}