From the main activity I cause a fragment

<fragment class="com.example.viktor.buyersguide.Section" 

In this fragment, a list is compiled and the selected value is then transmitted by the user.

  public void onListItemClick(ListView l, View v, int position, long id) { if (listenerSection != null) listenerSection.itemClicked(id); } 

And in the main activity, the public void itemClicked(long id) method (since I implement the implements Section.ListSection ) creates an intent

  Intent intent = new Intent(this, Main2Activity.class); intent.putExtra(Main2Activity.SUB_SECTION_ID, (int)id); startActivity(intent); 

And passes the selected id . In the markup of the opened activity Main2Activity , a new fragment with a list is also called

  <fragment class="com.example.viktor.buyersguide.SubSection" 

And I need to transfer the id from this activity ( Main2Activity ) into the SubSection fragment. I try it through the Bundle :

 int cardsId = (int) getIntent().getExtras().get(SUB_SECTION_ID); Bundle subSectionId = new Bundle(); subSectionId.putInt("idSub", cardsId); SubSection subSection = new SubSection(); subSection.setArguments(subSectionId); 

And in SubSection take out

 Bundle subSectionId = this.getArguments(); if (subSectionId != null) { this.id = subSectionId.getInt("idSub"); } 

by creating an int id; in advance int id; . However, it is always "0". What could be the problem or how else can the value be conveyed?

  • Most likely the code where you get the id is executed faster than the transfer from the activation to the id fragment. Where do you execute this code? - pavel163
  • Well, this is where the first fragment is loaded (from the first activity) and there the id is transferred to the main activity from the fragment. Then from this activity through the intensity of the second activity and from the second activity into the second fragment, where id is already 0 - Victor
  • problem in the intent, I mean in the second activity when I take the value from the intent, it is already NullPointer - Victor
  • The question is why .. - Victor

1 answer 1

You have a fragment added to the active through the markup. This is not the best solution. It is better to add fragments programmatically.

Also you incorrectly pass arguments to the fragment. It is necessary not to transfer to a new copy thereof, but to the one that you are displaying on the screen.

However, you cannot pass arguments correctly to the fragment added to the markup. So you need to add it programmatically and pass arguments to it when creating a fragment instance. Then everything will work.