retrieve data from fragment - java

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

Related

Pass data from activity to another fragment

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

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

Fragment Bundle

Please Help me!
What I'm doing wrong?
in Fragment1
#Override
public static Fragment1 newInstance(String param) {
Fragment1 fragment = new Fragment1();
Bundle args = new Bundle();
args.putString("key","value");
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString("key");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment1, container, false);
textview.setText(mParam1)
return v
in Activity onCreate
Fragment1.newInstance("text");
and in the end i have null in mParam1
Why?
I don't believe your mParam1 is null. I think your textview is null because you haven't referenced it. You need to give it a reference to the textview in the layout.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment1, container, false);
TextView textview = v.findViewById(R.id.textview);
textview.setText(mParam1);
return v;
}
Also, you need to change args.putString("key", "value") to args.putString("key", param) if you expect to get the string you passed to the new instance and not get "value" set to all your textviews.
Also, make sure you import android.support.v4.app.Fragment; and add this to your MainActivity's onCreate:
Fragment fragment = Fragment1.newInstance("Text");
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragmentContainer, fragment, null)
.commit();
Where R.id.fragmentContainer is the id of your FrameLayout in your activity_main.xml.
<FrameLayout
android:id="#+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
If you don't have this, your onCreate in your fragment will never get called and will never inflate. I can't think of anything else it can be because your fragment code is fine. So the problem is in your main Activity.
You have to put the args to the Fragment from the parent Activity.
For instance if you use a ViewPager, in the adapter do the following when instantiating :
public class ParentActivity extends FragmentActivity {
private class MyAdapter extends FragmentStatePagerAdapter {
MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
fragment.setArguments(args);
switch (position) {
case 0:
Fragment1 fragment = new Fragment1();
Bundle args = new Bundle();
args.putString("key", "MyString");
fragment.setArguments(args);
return fragment;
}
}
#Override
public int getCount() {
return 1;
}
}
}

Passing data from listview in fragment to fragment

when i click on the listview the bundle can get the value, but cant pass the value to second fragment.
First Fragment
categorylist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final String category = ((TextView) view.findViewById(R.id.mainproductitem)).getText().toString();
details_fragment ldf = new details_fragment ();
Bundle args = new Bundle();
args.putString("category", category);
ldf.setArguments(args);
}
});
return view;
}
Second Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
view=inflater.inflate(R.layout.my_fragment2, container, false);
test = (TextView)view.findViewById(R.id.textView);
Bundle args = getArguments();
if (args != null && args.containsKey("category")){
String userId = args.getString("category");
test.setText(userId);
}
return view;
}
You may be forget to start your second fragment
categorylist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final String category = ((TextView) view.findViewById(R.id.mainproductitem)).getText().toString();
details_fragment ldf = new details_fragment ();
Bundle args = new Bundle();
args.putString("category", category);
ldf.setArguments(args);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.yourContainer, ldf);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
}
and in you second activity
Bundle agrs = getArguments();
if (args != null) {
String category = agrs.getString("category");
test.setText(category);
}
In First Fragment
categorylist.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final String category = ((TextView) view.findViewById(R.id.mainproductitem)).getText().toString();
MainActivity main=new MainActivity();
main.openSecondFrag();
}
});
return view;
}
In your MainActivity,put openSecondFrag() method
public void openSecondFrag(){
details_fragment ldf = new details_fragment ();
Bundle args = new Bundle();
args.putString("category", category);
ldf.setArguments(args);
}
In Second Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
view=inflater.inflate(R.layout.my_fragment2, container, false);
test = (TextView)view.findViewById(R.id.textView);
Bundle args = getArguments();
if (args != null && args.containsKey("category")){
String userId = args.getString("category");
test.setText(userId);
}
return view;
}
I am sure it will work.
HomeActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.activity.HomeActivity"
tools:showIn="#layout/app_bar_home">
//View that will hold all the fragments
<FrameLayout
android:id="#+id/container_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
FirstFragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment1, container, false);
view.setBackgroundColor(Color.WHITE);
listViewAdapter.SetOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
SecondFragment secondFrag = new SecondFragment();
Bundle args = new Bundle();
args.putString("Key","some value");
secondFrag .setArguments(args);
getFragmentManager()
.beginTransaction()
.replace(R.id.container_view, fragment)
.addToBackStack(null)
.commit();
}
});
return view;
}
SecondFragment
public class SecondFragment extends Fragment {
public SecondFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.second_fragment, container, false);
TextView textView = (TextView)view.findViewById(R.id.textView);
view.setBackgroundColor(Color.WHITE);
String key = getArguments().getString("Key");
//Set the value to your text view
textView.setText(key);
return view;
}
I tried this out and it works perfectly.
Try this: on your receiving Fragment:
Bundle agrs = this.getArguments();
if (args != null) {
String myStr = args.getString(key, defaultValue);
}
`Use this code in your categorylist.setOnItemClickListener`
// Create fragment and give it an argument specifying the article it should show
details_fragment newFragment = new details_fragment ();
Bundle args = new Bundle();
args.putString("category", category)
//Note: if your are in fragment than replace getSupportFragmentManager to getFragmentManager.
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
Use a Bundle. Here's an example:
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putString(key, value);
fragment.setArguments(bundle);
getFragmentManager().beginTransaction().replace(R.id.container_view, bundle).commit();
Bundle has put methods for lots of data types. See this
Then in your Fragment, retrieve the data (e.g. in onCreate() method) with:
Bundle bundle = this.getArguments();
if (bundle != null) {
int myInt = bundle.getString(key, defaultValue);
}

Categories

Resources