Pass data from activity to another fragment - java

From the activity, I open the fragment "DevicesFragment" as below. How do I transfer data from activity to fragment before starting it? Thanks for help !
getSupportFragmentManager().beginTransaction().add(R.id.fragment, new DevicesFragment(), "devices").commit();

From Activity you send data with intent as:
Bundle bundle = new Bundle();
bundle.putString("text", "From Activity");
// set Fragmentclass Arguments
DevicesFragment devices = new DevicesFragment();
devices.setArguments(bundle);
getSupportFragmentManager().beginTransaction().add(R.id.fragment, devices, "devices").commit();
and in DevicesFragment onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle bundle = getArguments();
if(bundle != null) {
String value = bundle.getString("text");
}
return inflater.inflate(R.layout.fragment, container, false);
}

You can send data from one activity to another fragment using Bundles as below:
Bundle bundle = new Bundle();
bundle.putString("key", "your data");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
and fragment onCreate method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("key");
return inflater.inflate(R.layout.fragment, container, false);
}

Related

can I send data from adapter by bundle( when click on view button from custom layout in adapter) to another fragment?

I use tablayout and push item tab by java class to connect it with fragment but I need to sent data from Adapter use another fragment ,to fragment I use bundle and it take data from adapter but when reach to fragment bundle is null.
I have the following code in BindViewHolder in Adapter:
holder.btn_tobuy.setOnClickListener(new View.OnClickListener() {
FragmentShoping fragmentShoping = new FragmentShoping();
#Override
public void onClick(View v) {
String name_meal=holder.Name_Meal.getText().toString();
Bundle bundle = new Bundle();
bundle.putString("name",name_meal);
Log.i("BUNDLE", bundle.toString());
fragmentShoping.setArguments(bundle);
}
});
then this code in fragment :
Bundle bundle = this.getArguments();
if(bundle!=null) {
String i = bundle.getString("name", "un_name");
shopingMeals.setName_Meal(i);
shopingMeals.setPrice(10);
shopingMeals.setCount(5);
shopingMeals.setImg_meal(R.drawable.burger_1);
list.add(shopingMeals);
}
**I try to put this code in createdview or oncreate in fragment but the same problem I need to send data from adapter to fragment by bundle or another way.
edit code , fragment transaction I try a lot of way :
public FragmentShoping() {
// Required empty public constructor
}
RecyclerView recycler;
View view;
ConstraintLayout rootlayout;
AdapterShoping adapterShoping;
ArrayList<ShopingMeals> list = new ArrayList<>();
ShopingMeals shopingMeals ;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view= inflater.inflate(R.layout.fragment_shoping, container, false);
recycler=view.findViewById(R.id.main_recycler_shoping);
rootlayout = view.findViewById(R.id.shoping_rootlayout);
recycler.setLayoutManager(new LinearLayoutManager(getActivity()));
getMyitem();
adapterShoping=new AdapterShoping(getActivity().getApplicationContext(),list);
recycler.setRotationY(180);
recycler.setAdapter(adapterShoping);
// meals.add(new Meals("mamoun","fff",50,R.drawable.ic_meal));
// meals.add(new Meals("mamoun","fff",50,R.drawable.ic_meal));
// meals.add(new Meals("mamoun","fff",50,R.drawable.ic_meal));
// meals.add(new Meals("mamoun","fff",50,R.drawable.ic_meal));
// recycler.setHasFixedSize(true);
return view;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Bundle bundle = this.getArguments();
// if (bundle != null) {
// String i = bundle.getString("name", "un_name");
// Log.i("BUNDLE2", i);
// }
}
Bundle bundle;
String i;
public ArrayList<ShopingMeals> getMyitem() {
bundle =this.getArguments();
if(bundle!=null) {
i = bundle.getString("name", "un_name");
}
shopingMeals = new ShopingMeals();
shopingMeals.setName_Meal(i);
shopingMeals.setPrice(10);
shopingMeals.setCount(5);
shopingMeals.setImg_meal(R.drawable.burger_1);
list.add(shopingMeals);
// String a = Objects.requireNonNull(this.getActivity()).getSharedPreferences("MySharedPref", MODE_PRIVATE).getString("name", "def");
// SharedPreferences sh = getActivity().getSharedPreferences("MySharedPref", Context.MODE_PRIVATE);
// String s =sh.getString("name","def");
// shopingMeals.setName_Meal(a);
return list;
}
thanks,**
Greate answer provided here
Try to retrieve values instead of bundle
So:
if(getArguments() != null)
shippingMeals.setName_Meal(getArguments().getString("name"));

In my code getArgument is returning null every time

I have tried each and every type of solution but the fragment get argument method is returning null always.
This is my fragment code.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_main_activity, container, false);
**String data1 = getArguments().getString("data");
Toast.makeText(getActivity(), getArgument1, Toast.LENGTH_SHORT).show();**
}
In the above code data1 always return null.
This is my main activity code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
chipNavigationBar = findViewById(R.id.bottomNavBar);
chipNavigationBar.setItemSelected(R.id.home, true);
getSupportFragmentManager().beginTransaction().replace(R.id.container1, new mainActivityFragment()).commit();
chipNavigationBar.setOnItemSelectedListener(new ChipNavigationBar.OnItemSelectedListener() {
#Override
public void onItemSelected(int i) {
Fragment fragment = null;
switch (i) {
case R.id.home:
**fragment = new mainActivityFragment();
Bundle bundle = new Bundle();
bundle.putString("data","anything");
fragment.setArguments(bundle);**
break;
case R.id.menu:
fragment = new menuFragment();
break;
case R.id.corona:
fragment = new CoronaFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.container1, fragment).commit();
}
});
}
I am concerned that there are 2 places you load the mainActivityFragment() - the first is by default, when there are no bundle args, and the second time when the chipNavigationBar. setOnItemSelectedListener is called. Maybe try something like this:
static mainActivityFragment createMainActivityFragment() {
mainActivityFragment fragment = new mainActivityFragment();
Bundle bundle = new Bundle();
bundle.putString("data","anything");
fragment.setArguments(bundle);
return fragment;
}
//IN ONCREATE:
getSupportFragmentManager().beginTransaction().replace(R.id.container1, mainActivityFragment.createMainActivityFragment()).commit();
//IN THE SWITCH
case R.id.home:
fragment = mainActivityFragment.createMainActivityFragment()
break;
Then both instances should have the bundle

Changing an image when button click from another fragment

I want to be able to click a button on my settings fragment, which will change an image on another fragment called home fragment. My app keeps crashing once i click the button and im not sure why.
Settings Fragment :
public class SettingsFragment extends Fragment {
public Button button;
public ImageView Torso;
public ImageView ShopGreenTorso;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
button = (Button) getView().findViewById(R.id.button1);
Torso = (ImageView) getView().findViewById(R.id.Torso);
ShopGreenTorso= (ImageView) getView().findViewById(R.id.ShopGreenTorso);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Purchased", Toast.LENGTH_SHORT).show();
Intent i = new Intent(SettingsFragment.this.getActivity(), AvatarFragment.class);
//i.putExtra("resID", R.drawable.torso2green);
Bundle b= new Bundle();
b.putInt("resID", R.drawable.torso2green);
SettingsFragment.this.setArguments(b);
//setArguments(bundle);
startActivity(i);
}
});
}
Avatar Fragment:
public class AvatarFragment extends Fragment {
public ImageView IV;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_avatar, container, false);
// init image view
IV = (ImageView) rootView.findViewById( R.id.Torso );
// getting extras
//Bundle bundle = getActivity().getIntent().getExtras();
// Bundle bundle=getArguments();
Bundle b=getArguments();
if(b!= null)
{
int resid = b.getInt("resID");
IV.setBackgroundResource(resid);
}
return rootView;
}
}
I believe the error is coming from IV.setImageResource(resid) but im not entirely sure, any help would be much appreciated.
It's hard to tell without seeing the exception, but it might be because Bundle mappings are case-sensitive.
Your SettingsFragment uses "ResId", but your HomeFragment is expecting "resID". If no mapping is found in the Bundle, you'll be given the default value of 0 for resID. It's possible that you're crashing when calling IV.setImageResource(0);.
Your image implementation in code is wrong, you need to init your image view like this :
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_avatar, container, false);
// init image view
IV = (ImageView) rootView.findViewById( R.id.Torso );
// getting extras
Bundle bundle = getActivity().getIntent().getExtras();
if(bundle!= null)
{
int resid = bundle.getInt("resId");
IV.setImageResource(resid);
}
return rootView;
}
Don't pass value from Fragment to Fragment directly.
You should use setArguments from SettingsFragment and getArguments in HomeFragment

Fragment Bundle receiving null value

I have two fragment which i want to pass data from one fragment to another,the bundle has value from first fragment when sending but not receiving in another fragment.Here is the code:
First Fragment :
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.customer_one,container,false);
edemail = v.findViewById(R.id.ed_email);
edpass = v.findViewById(R.id.ed_pass);
btn = v.findViewById(R.id.btn_next);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
email = edemail.getText().toString().trim();
password = edpass.getText().toString().trim();
Customer_Frag2 cf2 = new Customer_Frag2();
Bundle bundle = new Bundle();
bundle.putString("Email",email);
bundle.putString("Password",password);
cf2.setArguments(bundle);
Log.d("Test2",bundle.toString());
}
});
return v;
}
Second Fragment:
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable
ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.customer_two,container,false);
Bundle bundle = getArguments();
if(bundle!=null){
email = bundle.getString("Email");
pass = bundle.getString("Password");
}
Log.d("Test",email+pass);
return v;
}

retrieve data from fragment

I want to retrieve String data from my fragment that sent from activity and I'm using this code to send :
Bundle bundle = new Bundle();
bundle.putString("name",texts.get(position));
CatSelected catSelected = new CatSelected();
catSelected.setArguments(bundle);
getFragmentManager().beginTransaction().replace(R.id.container, catSelected, "CatSelected").commit();
And this code to receive :
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.search_frag, container, false);
txt = (TextView) view.findViewById(R.id.textView);
txt.setText(getArguments().getString("name"));
return view;
}
But textview is showing the default text and does not change. What's the problem?
A common practice seen while using fragments is, not to directly instantiate the fragment. Instead, you a get a fragment object by doing something like below.
MyFragment = MyFragment.newInstance(int arg1, String args2); // pass your args here
getSupportFragmentManager().beginTransaction().replace(R.id.flContent, fragment).commit();
Now, the MyFragment is composed of
public static MyFragment newInstance(int arg1, String arg2) {
MyFragment fragment = new MyFragment();
Bundle args = new Bundle();
args.putInt("arg1Key", arg1);
args.putInt("arg1Key", arg2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
myArg1 = getArguments().getInt("arg1Key");
myArg2 = getArguments().getInt("arg2Key");
}
}
In your second fragment or in your fragment that you want to retrive the passed value first must create a bundle.Try this.
Bundle bundle = getArguments();
txt.setText = bundle.getString("name");

Categories

Resources