How to Access String In Another Fragment in Android - android

I am trying to access a String from an EditText on my login page to use in my other fragments. I found some information on using Bundle to achieve this, but I am having some difficulty implementing this function. I have a temporary TextView I am assigning the String to so I can tell when it is working, so ignore this object(tvGetTest).
Login Class:
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_login, container, false);
etAccountNumber = (EditText) rootView.findViewById(R.id.etAccountNumber);
rbGroup = (RadioGroup) rootView.findViewById(R.id.rbGroup);
rbUsa = (RadioButton) rootView.findViewById(R.id.rbUsa);
rbCanada = (RadioButton) rootView.findViewById(R.id.rbCanada);
btnLogin = (Button) rootView.findViewById(R.id.btnLogin);
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putString(accountNumber, accountNumber);
bundle.putString(countryCode, countryCode);
fragment.setArguments(bundle);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doLogin();
}
});
return rootView;
}
public void doLogin() {
accountNumber = etAccountNumber.getText().toString();
if (rbUsa.isChecked()) {
countryCode = "USA";
}
else if (rbCanada.isChecked()) {
countryCode = "CAN";
}
}
onCreate of Other Fragment Class:
tvGetTest = (TextView) rootView.findViewById(R.id.tvGetTest);
Bundle bundle = this.getArguments();
if (bundle != null) {
String aNo = bundle.getString("accountNumber");
tvGetTest.setText(aNo);
}
Edit:
public void doBundle() {
Fragment fragment = new AvailabilityFragment();
Bundle bundle = new Bundle();
bundle.putString(accountNumber, accountNumber);
bundle.putString(countryCode, countryCode);
fragment.getFragmentManager().putFragment(bundle, accountNumber, fragment);
fragment.getFragmentManager().putFragment(bundle, countryCode, fragment);
}

It's preferable to manage all your fragments from their host activity, avoid nesting fragments.
In your use case, you should define a method in your HostActivity called launchOtherFragment:
public void launchOtherFragment(String accountNumber, String countryCode)
{
Bundle bundle = new Bundle();
bundle.putString("accountNumber", accountNumber);
bundel.putString("countryCode", countryCode);
OtherFragment fragment = new OtherFragment();
fragment.setArguments(bundle);
getFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment).commit();
}
Now you can access this method in your first fragment, so in doLogin:
private void doLogin() {
accountNumber = etAccountNumber.getText().toString();
if (rbUsa.isChecked()) {
countryCode = "USA";
}
else if (rbCanada.isChecked()) {
countryCode = "CAN";
}
((HostActivity)getActivity()).launchOtherFragment(accountNumber, countryCode);
}

Related

Android : How to send data from Activity to Fragment (Error: Bundle is empty) [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Null pointer exception when using Bundle to pass data
(7 answers)
Closed 2 years ago.
I am very new to Android and a high school student.
So I think it'd be nice if you could give me the code, too.
I implemented login using firebase and LoginActivity.FragmentIndivative in java.I want to send my name, e-mail address, and phone number to java.
So I used a Bundle object, and NullpointerException occurred.
Please help me. I don't have time. I'll wait for you guys.
I'll attach the code below.
Please take good care of me.
private void signUp(){
final String email = ((EditText)findViewById(R.id.idText)).getText().toString();
final String password = ((EditText)findViewById(R.id.pwText)).getText().toString();
if(email.length() > 0 && password.length() > 0){
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Intent intent1;
if (task.isSuccessful()) {
FirebaseUser user = mAuth.getCurrentUser();
startToast("로그인에 성공하였습니다");
fragmentIndividual = new FragmentIndividual();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction fmt = fm.beginTransaction();
intent1 = new Intent(getApplicationContext(), MainActivity.class);
intent1.putExtra("name", "nnnaa");
Bundle bundle = new Bundle();
bundle.putString("name", mAuth.getCurrentUser().getDisplayName());
bundle.putString("email", mAuth.getCurrentUser().getEmail());
bundle.putString("phone", mAuth.getCurrentUser().getPhoneNumber());
System.out.println(email);
System.out.println(mAuth.getCurrentUser().getEmail());
startActivity(intent1);
} else {
if(task.getException() != null){
startToast(task.getException().toString());
}
}
}
});
}else{
startToast("빈 칸을 채워주세요");
}
}
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_individual, container, false);
Bundle bundle = this.getArguments();
if(bundle != null){
bundle = getArguments();
String name = bundle.getString("name");
String email = bundle.getString("email");
String phone = bundle.getString("phone");
View v = inflater.inflate(R.layout.fragment_individual, container, false);
nameTv = (TextView)v.findViewById(R.id.nameTv);
emailTv = (TextView)v.findViewById(R.id.emailTv);
phoneTv = (TextView)v.findViewById(R.id.phoneTv);
nameTv.setText(name);
emailTv.setText(email);
phoneTv.setText(phone);
}
return view;
}
Inside your onComplete method, Try to replace inside your if statement with this code.
if (task.isSuccessful()) {
FirebaseUser user = mAuth.getCurrentUser();
startToast("로그인에 성공하였습니다");
Bundle bundle = new Bundle();
bundle.putString("name", mAuth.getCurrentUser().getDisplayName());
bundle.putString("email", mAuth.getCurrentUser().getEmail());
bundle.putString("phone", mAuth.getCurrentUser().getPhoneNumber());
System.out.println(email);
System.out.println(mAuth.getCurrentUser().getEmail());
Fragment fragment = IndividualFragment.newInstance(bundle);
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.frame_layout, fragment, "fragment").commit();
} else {
...
where R.id.your_activity_layout is your Activity layout or you can either add a FrameLayout inside your activity layout .xml.
And in your IndividualFragment
public class IndividualFragment extends Fragment {
public IndividualFragment() {
}
private TextView nameTv;
private TextView emailTv;
private TextView phoneTv;
public static IndividualFragment newInstance(Bundle bundle) {
IndividualFragment fragment = new IndividualFragment();
fragment.setArguments(bundle);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_individual, container, false);
Bundle bundle = getArguments();
if(bundle != null){
bundle = getArguments();
String name = bundle.getString("name");
String email = bundle.getString("email");
String phone = bundle.getString("phone");
nameTv = (TextView)view.findViewById(R.id.nameTv);
emailTv = (TextView)view.findViewById(R.id.emailTv);
phoneTv = (TextView)view.findViewById(R.id.phoneTv);
nameTv.setText(name);
emailTv.setText(email);
phoneTv.setText(phone);
}
return view;
}
}
You can also check this link.
https://stackoverflow.com/a/36100397/11445765

Reload entire fragment on backpress

I have an AppCompatActivity that let the users to draw signature then the activity passes the Path of the signature to a fragment. The fragment is supposed to put the signature on an ImageView. The fragment is receiving the path of the image precisely correct. For test, when i put the path manually the ImageView shows up the image very finely on App Startup. but after having drawn the signature from the activity, the image is not showing up on the fragment.
After digging in a lot and lots of FAQs on stackoverflow i came to know that the fragment components are not refreshing after backpress from the activity. There is a terms and condition checkbox on the fragment. Even that checkbox remains checked after getting back from the activity. Spent hours in this solving this. No luck.
Activity Side coding to pass the Image Path-
Menu1_SecondClass fragment = new Menu1_SecondClass();
fragment.setBoolean(true);
Bundle bundle = new Bundle();
bundle.putString("imagePath", StoredPath); // Passing the Path
fragment.setArguments(bundle);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.linearLayout, fragment);
ft.commit();
finish();
mFileOutStream.flush();
mFileOutStream.close();
Fragment Side Coding
public class Menu1_SecondClass extends Fragment {
Button signatureButton;
ImageView signImage;
CheckBox checkBox;
View view;
public String image_path;
public boolean vboolean = false;
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Homework Details");
}
public void setBoolean(Boolean boo){
this.vboolean = boo;
}
public boolean getBoolean(){
return this.vboolean;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(getBoolean()){
Toast.makeText(getActivity(), "Refreshing.. " , Toast.LENGTH_SHORT).show();
this.setBoolean(false);
refreshFragment();
}
}
public void refreshFragment(){
FragmentTransaction t = getActivity().getSupportFragmentManager().beginTransaction();
t.setReorderingAllowed(false);
t.detach(this).attach(this).commitAllowingStateLoss();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_homework, container, false);
signatureButton = (Button) view.findViewById(R.id.getSign);
signImage = (ImageView) view.findViewById(R.id.imageViewSign);
signatureButton.setOnClickListener(onButtonClick);
checkBox = (CheckBox) view.findViewById(R.id.checkbox);
//disable button if checkbox is not checked else enable button
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
signatureButton.setEnabled(true);
} else {
signatureButton.setEnabled(false);
}
}
});
putSignature();
return view;
}
public void putSignature(){
Bundle bundle = this.getArguments();
if (bundle != null) {
image_path = bundle.getString("imagePath", ""); if(!image_path.isEmpty()) {
Bitmap bitmap = BitmapFactory.decodeFile(image_path);
if (bitmap != null) {
//bitmap = Bitmap.createScaledBitmap(bitmap, 120, 80, false);
signImage.setImageBitmap(bitmap);
Toast.makeText(getActivity(), "Image Created: " + image_path, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "Null Image", Toast.LENGTH_SHORT).show();
}
}
}
}
Button.OnClickListener onButtonClick = new Button.OnClickListener() {
#Override
public void onClick(View v) {
if (checkBox.isChecked()) {
Intent i = new Intent(getActivity(), SignatureActivity.class);
startActivity(i);
} else {
signatureButton.setEnabled(false);
}
}
};
}
When You are passing data from activity to fragment you can use below code
Bundle bundle = new Bundle();
bundle.putString("imagePath", imagePath);
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
and while receiving data in fragment, inside onCreateView method you can write code like this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
String strtext = getArguments().getString("imagePath");
return inflater.inflate(R.layout.fragment, container, false);
}
transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.framelay_loan, firstFrag);
transaction.addToBackStack(fragment.getClass().getName());
Bundle bundle = new Bundle();
bundle.putString("imagePath", imagePath);
fragment.setArguments(bundle);
transaction.commit();`
Inside onCreateView method
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) {
View view = inflater.inflate(R.layout.fragment_micro_form1, container,false);
Bundle bundle = this.getArguments();
if (bundle != null) {
image_path = bundle.getString("imagePath", "");
}
return view;
}

getArguments returning null

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;
}

how to pass data from activity to fragment..?

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");
}

Bundle not working

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);
}

Categories

Resources