I can not pass a string to fragment - android

call fragment from fragment. I need to pass a string to the fragment. how to do it?
if (position==1){
FragmentTransaction ft;
VideoList lf = new VideoList();
ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragmentsPanel, lf);
ft.addToBackStack(null);
ft.commit();
}
I want to pass String str = "absd"; and the second fragment to take String str1 = row of the first fragment

Use arguments!
public static VideoList videoListWithString(String string) {
VideoList videoList = new VideoList();
Bundle arguments = new Bundle();
arguments.putString("testString","test");
videoList.setArguments(arguments);
return videoList;
}
and in your fragments onCreate...
Bundle arguments = getArguments();
String testString = arguments.getString("testString");

You can use setArguments() and getArguments() methods in Fragments
like
if (position==1){
FragmentTransaction ft;
VideoList lf = new VideoList();
Bundle bundle = new Bundle();
bundle.putString("str", "absd");
ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragmentsPanel, lf);
ft.addToBackStack(null);
ft.commit();
}
and in the fragment you get this string like this
public class VideoList extends ListFragment {
public View onCreateView(LayoutInflater inflater,
ViewGroup containerObject,
Bundle savedInstanceState){
//here is your arguments
Bundle bundle=getArguments();
//here is your list array
String str=bundle.getString("str");
}
}

Bundle params = new Bundle();
params.putString("str1", "absd");
getFragmentManager().beginTransaction()
.replace(R.id.fragment_place, YourFragment.instantiate(getActivity(), YourFragment.class.getName(), params), "YourFragmentTag").commit();

If your requirement is to pass value from one fragment to another then try using bundle.
For example:
TalkDetail fragment = new TalkDetail();
Bundle bundle = new Bundle();
bundle.putString("title", title);
bundle.putString("largeimg", largeimg);
bundle.putString("excert", excert);
bundle.putString("description",description);
bundle.putString("cat", cat);
bundle.putString("header_title", "Talk");
//bundle.putInt("postid", postid);
fragment.setArguments(bundle);
((BaseContainerFragment)getParentFragment()).replaceFragment(fragment, true);
Here's your BaseContainerFragment class that will help to get better back track and other good stuff
public class BaseContainerFragment extends Fragment {
public void replaceFragment(Fragment fragment, boolean addToBackStack) {
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
if (addToBackStack) {
transaction.addToBackStack(null);
}
transaction.replace(R.id.container_framelayout, fragment);
transaction.commit();
getChildFragmentManager().executePendingTransactions();
}
public boolean popFragment() {
Log.e("test", "pop fragment: " + getChildFragmentManager().getBackStackEntryCount());
boolean isPop = false;
if (getChildFragmentManager().getBackStackEntryCount() > 0) {
isPop = true;
getChildFragmentManager().popBackStack();
}
return isPop;
}
}

Related

getArguments() always returns null in Fragment

I need to pass arguments to my fragments but getArguments() alway returns null
public static PersonFragment newInstance(int columnCount, ArrayList<Person> personenListe) {
PersonFragment personFragment = new PersonFragment();
Bundle args = new Bundle();
args.putSerializable("persList",personenListe);
args.putInt(ARG_COLUMN_COUNT, columnCount);
personFragment.setArguments(args);
return new PersonFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) { //getAguments() == null !!
mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
mPersonenListe = (ArrayList<Person>) getArguments().getSerializable("persList");
}
}
I'm calling it in MainActivity
openFragment(PersonFragment.newInstance(personenListe.size(), personenListe));
With this method
public void openFragment(Fragment fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
Instead of returning the fragment that you set the arguments to, you returned a brand new fragment.
So change the newInstance to:
public static PersonFragment newInstance(int columnCount, ArrayList<Person> personenListe) {
PersonFragment personFragment = new PersonFragment();
Bundle args = new Bundle();
args.putSerializable("persList",personenListe);
args.putInt(ARG_COLUMN_COUNT, columnCount);
personFragment.setArguments(args);
// return new PersonFragment();
return personFragment ; // <<< change here
}

pass string from activity to fragment [duplicate]

This question already has answers here:
how to pass string data from activity to fragment?
(5 answers)
Closed 5 years ago.
My problem is passing string from activity to fragment. I researched for a whole day and my problem isn't solved.
activity :
if(email.matches(users.user1)&&password.matches(users.pass1)){
Intent intent = new Intent(LoginActivity.this,MainActivity.class);
Bundle bundle = new Bundle();
bundle.putString("user", users.name);
ProfileFragment fragobj = new ProfileFragment();
fragobj.setArguments(bundle);
startActivity(intent);
}
fragment :
public class ProfileFragment extends Fragment {
public static ProfileFragment newInstance() {
return new ProfileFragment();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_profile, container, false);
String user = getArguments().getString("user");
TextView textView = v.findViewById(R.id.namef1);
textView.setText(user);
return inflater.inflate(R.layout.fragment_profile, container, false);
}
}
MainActivity
public class MainActivity extends Activity {
private BottomNavigationView mBottomNavigationView;
private Toolbar supportActionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupBottomNavigation();
if (savedInstanceState == null) {
loadHomeFragment();
}
}
private void setupBottomNavigation() {
mBottomNavigationView =findViewById(R.id.bottom_navigation);
mBottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.action_home:
loadHomeFragment();
return true;
case R.id.action_profile:
loadProfileFragment();
return true;
case R.id.action_settings:
loadSettingsFragment();
return true;
}
return false;
}
});
}
private void loadHomeFragment() {
HomeFragment fragment = HomeFragment.newInstance();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_frame, fragment);
ft.commit();
}
private void loadProfileFragment() {
ProfileFragment fragment = ProfileFragment.newInstance();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_frame, fragment);
ft.commit();
}
private void loadSettingsFragment() {
SettingsFragment fragment = SettingsFragment.newInstance();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_frame, fragment);
ft.commit();
}
public void setSupportActionBar(Toolbar supportActionBar) {
this.supportActionBar=supportActionBar;
}
}
as it shown in code user has login and one of his data display in a profile fragment . I wanna display this string as Textview in profilefragment .
anybody have an idea?
Move below part of code to the place where you are adding the ProfileFragment to Activity.
Bundle bundle = new Bundle();
bundle.putString("user", users.name);
ProfileFragment fragobj = new ProfileFragment();
fragobj.setArguments(bundle);

how to replace fragment from activity spinner without backstack

i have one activity which contains spinner control in appbar. in homeActivity i'm using fragment which have default fragment as parentoptionfragment, from that fragment there are 3 option to change the fragments, if i have choosen one fragment from parentoption fragment and i want to change spinner value then the fragment should be updated without adding to backstack means if i press back button then it should call parent optionfragment, but when i'm trying to do so i'm getting error.
public void GetChildData(String token) {
ParentOptionsFragment fragment =new ParentOptionsFragment();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
tv_childClassname.setText(classNameArr[position]);
tv_childSchoolName.setText(schoolNameArr[position]);
Fragment f = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
if (f instanceof ChildMapFragment){
Toast.makeText(HomeActivity.this, "refreshing childmapfragment", Toast.LENGTH_SHORT).show();
ChildMapFragment fragment = new ChildMapFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.popBackStackImmediate (fragment.getClass().getName(), 0);
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}else if(f instanceof ParentOptionsFragment){
Toast.makeText(HomeActivity.this, "spinner changed from ParentOptionsFragment", Toast.LENGTH_SHORT).show();
}
}
parentoptionfragment.java
public class ParentOptionsFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_parent_options, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final ImageView img1=(ImageView)view.findViewById(R.id.imageView);
ImageView img2=(ImageView)view.findViewById(R.id.imageView2);
ImageView img3=(ImageView)view.findViewById(R.id.img_transport);
img3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ChildMapFragment fragment = new ChildMapFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
/*final ViewTreeObserver vto = img1.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
int x;
img1.getViewTreeObserver().removeOnPreDrawListener(this);
x = img1.getMeasuredWidth();
img1.setLayoutParams(new LinearLayout.LayoutParams(x,x));
return true;
}
});*/
}
}
childfragment.java
public class ChildFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_child_map, container, false);
}
}
homeActivity ---> defaultfragment-- parentoptionfragment
parentoptiofragment---> childfragment
using spinner update childfragment without backstack
onbackpress of childfragment --> parentoptionfragment
replace
Toast.makeText(HomeActivity.this, "refreshing childmapfragment", Toast.LENGTH_SHORT).show();
ChildMapFragment fragment = new ChildMapFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.popBackStackImmediate (fragment.getClass().getName(), 0);
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
with :
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.popBackStack()
update :
on your child fragment add a method : update() and call it :
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragment = fragmentManager.findFragmentById(R.id.fragment_container)
if(fragment isInstanceOf ChildMapFragment ){
((ChildMapFragment )fragment).update() //call your update method here
}
FragmentManager fragmentManager = getSupportFragmentManager();
// String f_name=fragment.getClass().getName();
if (!fragmentManager.popBackStackImmediate(tag, 0)) {
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.content_frame, fragment, tag);
ft.addToBackStack(tag);
ft.commit();
}
to Refresh fragment implement back stack in activity like this
#Override
public void onBackStackChanged() {
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fr = fragmentManager.findFragmentById(R.id.content_frame);
if (fr != null) {
fr.onResume();
}
}
here pass different tag base on different fragment

Bundle not working (getArguments() always null) [Android]

My code was working few hours ago but not anymore, I can't see what is the reason.
Here is my listener where I change fragment after a click :
CustomMarkRow.java
public void onClick(DialogInterface dialogInterface, int i){
Bundle bundle = new Bundle();
bundle.putInt("id", CustomMarkRow.this.mark.getId());
FragmentManager fragmentManager = CustomMarkRow.this.fragmentManager;
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); activity.getActionBar().setSelectedNavigationItem(CustomMarkRow.this.positionTab);
EditMarkFragment fragment = new EditMarkFragment();
fragment.setArguments(bundle);
fragmentTransaction.replace(R.id.fragmentContainer, fragment,"2");
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
At this moment, fragment.getArguments() contains what I put inside :
{android.os.Bundle#3644} "Bundle[{id=1}]"
In my second file :
EditMarkFragment.java
public class EditMarkFragment extends Fragment {
public View view;
public EditMarkFragment(){
super();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
this.view = inflater.inflate(getResources().getIdentifier("edit_mark", "layout",container.getContext().getPackageName()), container, false);
if(this.getArguments()==null){ // always null
...
}
return this.view
}
getArguments() always return null here, What is bad in this sample ?
* edit *
Here is my launcher class :
public class Launcher extends Activity implements ActionBar.TabListener {
private HomeFragment frag1 = new HomeFragment();
private EditMarkFragment frag2 = new EditMarkFragment();
private MarkListFragment frag3 = new MarkListFragment();
private EditCategoryFragment frag4 = new EditCategoryFragment();
private CategoryListFragment frag5 = new CategoryListFragment();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.launcher);
//Configuration de la barre d'onglet
getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab tab1 = getActionBar().newTab().setTabListener(this).setTag("1").setText("Home"); //.setIcon(R.drawable.homew);
getActionBar().addTab(tab1);
ActionBar.Tab tab2 = getActionBar().newTab().setTabListener(this).setTag("2").setText("New Mark"); //.setIcon(R.drawable.addw);
getActionBar().addTab(tab2);
ActionBar.Tab tab3 = getActionBar().newTab().setTabListener(this).setTag("3").setText("My Marks"); //.setIcon(R.drawable.listw);
getActionBar().addTab(tab3);
ActionBar.Tab tab4 = getActionBar().newTab().setTabListener(this).setTag("4").setText("New Category"); //.setIcon(R.drawable.categoryw);
getActionBar().addTab(tab4);
ActionBar.Tab tab5 = getActionBar().newTab().setTabListener(this).setTag("5").setText("Categories"); //.setIcon(R.drawable.categoryw);
getActionBar().addTab(tab5);
}
#Override
public void onTabSelected(ActionBar.Tab tab, android.app.FragmentTransaction ft) {
if(tab.getTag().equals("1")){
ft.replace(R.id.fragmentContainer, frag1);
}
else if(tab.getTag().equals("2")){
ft.replace(R.id.fragmentContainer, frag2);
}
else if(tab.getTag().equals("3")){
ft.replace(R.id.fragmentContainer, frag3);
}
else if(tab.getTag().equals("4")){
ft.replace(R.id.fragmentContainer, frag4);
}
else if(tab.getTag().equals("5")){
ft.replace(R.id.fragmentContainer, frag5);
}
}
#Override
public void onTabUnselected(ActionBar.Tab tab, android.app.FragmentTransaction ft) {
if(tab.getTag().equals("1")){
ft.remove(frag1);
}
else if(tab.getTag().equals("2")){
ft.remove(frag2);
}
else if(tab.getTag().equals("3")){
ft.remove(frag3);
} else if(tab.getTag().equals("4")){
ft.remove(frag4);
}
else if(tab.getTag().equals("5")){
ft.remove(frag5);
}
}
#Override
public void onTabReselected(ActionBar.Tab tab, android.app.FragmentTransaction ft) {
}
}
While your onClick() code is creating an arguments Bundle, your onCreate() is not. If that edition of your fragment calls getArguments(), the method will return null.
1-Update your EditMark fragment with as follows:-
public class EditMarkFragment extends Fragment {
public static View view;
public static EditMarkFragment newInstance(int id) {
EditMarkFragment fragment = new EditMarkFragment();
Bundle bundle = new Bundle();
bundle.putInt("id", id);
fragment.setArguments(bundle);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
this.view = inflater.inflate(getResources().getIdentifier("edit_mark", "layout",container.getContext().getPackageName()), container, false);
int id=getArguments.getInt("id");
return this.view}
2- Inside CustomMarkRow update your code as :-
public void onClick(DialogInterface dialogInterface, int i){
FragmentManager fragmentManager = CustomMarkRow.this.fragmentManager;
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); activity.getActionBar().setSelectedNavigationItem(CustomMarkRow.this.positionTab);
EditMarkFragment fragment = EditMarkFragment.newInstance(CustomMarkRow.this.mark.getId()) ;
fragmentTransaction.replace(R.id.fragmentContainer, fragment,"2");
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
Try this,hope this will hep you.

NullPointerException at getArguments().getInten("index", index)

I'm presented with this unpleasant message on this code
public static HelpDetailsFragment newInstance(int index)
{
HelpDetailsFragment detailFragment = new HelpDetailsFragment();
Bundle bundleArgs = new Bundle();
bundleArgs.putInt("index", index);
detailFragment.setArguments(bundleArgs);
return detailFragment;
} // newInstance()
public int getCurrentIndex()
{
return getArguments().getInt("index", 0);
}
I'm using this code here:
HelpDetailsFragment detailFragment = (HelpDetailsFragment) getFragmentManager()
.findFragmentById(R.id.helpDetailsFrame);
if((detailFragment == null) || (detailFragment.getCurrentIndex() != index))
{
detailFragment = HelpDetailsFragment.newInstance(index);
Log.i(TAG, "HelpListFragment Create and replace details fragment for item:"+index);
FragmentTransaction fragTrans = getFragmentManager().beginTransaction();
fragTrans.replace(R.id.helpDetailsFrame, detailFragment);
fragTrans.commit();
}
What em I missing here??

Categories

Resources