Communication between two fragments with interface - android

My app have one activity A and two fragments F1 and F2.
One clicking button in F1, the F1 is replaced by F2.
I want to transfer data in F1 to F2. For that I implemented the interface in F1 and override its method in A.
But when sending the data from A to F2, my reference(sFragment in code A) to the F2 remains null,due to which data is not sent to F2. I am getting reference to the F2 using TAG provided while replacing F1 by F2.
Does it have something to do with the lifecycle like when I am trying to get reference to the F2 it hasn't yet created?
F1
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.form_fragment1,container,false);
nextB = (Button) v.findViewById(R.id.f1Next);
nextB.setOnClickListener(this);
return v;
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.f1Next:
SFragment fragment = new SFragment();
FragmentManager mManager = getFragmentManager();
FragmentTransaction mTransaction = mManager.beginTransaction();
mTransaction.replace(R.id.fragment_container,fragment,"SecondF"); // SecondF
mTransaction.addToBackStack(null); // this is required to move to the previous fragment
mTransaction.commit();
commListener.PlaceName(data1,data2); //passing value to activity
break;
}
}
interface CommBridge{
void PlaceName(String data1,String data2);
}
#Override
public void onAttach(Context context){
super.onAttach(context);
if (context instanceof CommBridge){
commListener= (CommBridge) context;
}
}
}
A
#Override
public void PlaceName(String data1, String data2) {
SFragment sFragment=(SFragment) getFragmentManager().findFragmentByTag("SecondF");
if (sFragment != null && sFragment.isInLayout()){
Log.d("STATE","1");
sFragment.setPlace(data1,data2);
}else{
Log.d("STATE","2"); // this is always the case
}
F2
public class SFragment extends Fragment {
String Place2,Place1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.form_fragment2,container,false);
return v;
}
void setPlace(String data1, String data2){
place1 = data1;
place2 = data2;
}
}

Let the activity be responsible for handling the onClick event of the Fragment. See the example below.
Activity:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
public class MainActivity extends AppCompatActivity implements Fragment1.CommBridge {
private Fragment1 fragment1 = new Fragment1();
private Fragment2 fragment2 = new Fragment2();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content, fragment1)
.commit();
}
#Override
public void onButtonClicked(String data1, String data2) {
fragment2.setData(data1, data2);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content, fragment2)
.commit();
}
}
Fragment1:
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class Fragment1 extends Fragment {
interface CommBridge {
void onButtonClicked(String data1, String data2);
}
private CommBridge handler;
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof CommBridge) {
handler = (CommBridge) context;
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment1, container, false);
Button button = (Button) view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handler.onButtonClicked("Data1", "Data2");
}
});
return view;
}
}
Fragment2
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Fragment2 extends Fragment {
private String data1;
private String data2;
public void setData(String data1, String data2) {
this.data1 = data1;
this.data2 = data2;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment2, container, false);
TextView textView = (TextView) view.findViewById(R.id.textView);
textView.setText(data1 + "\n" + data2);
return view;
}
}

I would recommend putting the code for replacing the fragment in your Activity and put the values which should be passed to SFragment() in its arguments directly:
SFragment newFragment = new SFragment();
Bundle args = new Bundle();
args.putString("place1", data1);
args.putString("place2", data1);
newFragment.setArguments(args);
You could get them in SFragment#onCreateView()
String place1 = getArguments().getString("place1");
Also have a look here: https://developer.android.com/training/basics/fragments/communicating.html

Related

can't add item to my recycler view from another fragment

I have an activity that has five fragments, One fragments is the notification fragment that has a recycler view where notification should be populating upon receiving them. now i have a function that add the items to the recycler view but when i try add it from another fragment it throws and null reference error.
Here is the fragment where there is the recycler and function to add the items on the recyclerview
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View v = inflater.inflate (R.layout.fragment_notificationcict, container, false);
notimodels = new ArrayList<> ();
RecyclerView mRecyclerView = v.findViewById (R.id.notificationsRecycler);
mRecyclerView.setHasFixedSize (true);
mLayoutManager = new LinearLayoutManager (getContext ());
mAdapter = new NotificationAdapter (notimodels);
mRecyclerView.setLayoutManager (mLayoutManager);
mRecyclerView.setAdapter (mAdapter);
}
public void addItem(NotificationModel n)
{
notimodels = new ArrayList<> ();
notimodels.add (n);
mAdapter.notifyItemInserted (notimodels.size () -1);
}
On the second fragment that adds items to the notification fragment
NotificationFragmentCict fragment = new NotificationFragmentCict ();
NotificationModel model = (new NotificationModel (R.drawable.logo, "OCApp", "Where are yiu.", "min"));
fragment.addItem (model);
Here is the Error
rocess: com.univibezstudios.ocappservice.ocapp, PID: 27625
java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView$Adapter.notifyItemInserted(int)' on a null object reference
at com.univibezstudios.ocappservice.ocapp.Fragments.NotificationFragmentCict.addItem(NotificationFragmentCict.java:99)
at com.univibezstudios.ocappservice.ocapp.Fragments.AccountFragmentCict$4$1$1.onDataChange(AccountFragmentCict.java:374)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##19.2.1:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##19.2.1:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database##19.2.1:55)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6803)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:497)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
See This is Fragment A
package com.codinginflow.fragmentcommunicationexample;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class FragmentA extends Fragment {
private FragmentAListener listener;
private EditText editText;
private Button buttonOk;
public interface FragmentAListener {
void addItemsToFragmentB();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_a, container, false);
editText = v.findViewById(R.id.edit_text);
buttonOk = v.findViewById(R.id.button_ok);
buttonOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addItemsToFragmentB();
});
return v;
}
public void updateEditText(CharSequence newText) {
editText.setText(newText);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof FragmentAListener) {
listener = (FragmentAListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement FragmentAListener");
}
}
#Override
public void onDetach() {
super.onDetach();
listener = null;
}
}
This is Fragment B
package com.codinginflow.fragmentcommunicationexample;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class FragmentB extends Fragment {
private FragmentBListener listener;
private EditText editText;
private Button buttonOk;
public interface FragmentBListener {
addItemsToFragmentA();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_b, container, false);
editText = v.findViewById(R.id.edit_text);
buttonOk = v.findViewById(R.id.button_ok);
buttonOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addItemsToFragmentA();
}
});
return v;
}
public void updateEditText(CharSequence newText) {
editText.setText(newText);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof FragmentBListener) {
listener = (FragmentBListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement FragmentBListener");
}
}
#Override
public void onDetach() {
super.onDetach();
listener = null;
}
}
This is an Activity in which u r going to add items to your recycler view
package com.codinginflow.fragmentcommunicationexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity implements FragmentA.FragmentAListener, FragmentB.FragmentBListener {
private FragmentA fragmentA;
private FragmentB fragmentB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentA = new FragmentA();
fragmentB = new FragmentB();
getSupportFragmentManager().beginTransaction()
.replace(R.id.container_a, fragmentA)
.replace(R.id.container_b, fragmentB)
.commit();
}
#Override
public void addItemsToFragmentA() {
fragmentB.updateEditText(input);
}
#Override
public void addItemsToFragmentB() {
fragmentA.updateEditText(input);
}
}

Android Fragment: Overlapping - still visible after replace

I have a Fragment (PokedexFragment.java) which contains a GridView (via Custom Recyclerview) with a few items. When I click on an item the current Fragment will be replaced by another fragment (SinglePokemonFragment.java) with the details from the selected item.
The user would like to go to the last or next item in the gridview directly (pressing Forward- / Backbutton). When he presses the Hardware "Backbutton" the old Fragment (SinglePokemonFragment.java) is still visible!
I do not like to use addBackStack, because there should not be any backstacks.
What part of the code is wrong or has to be updated and why?
I thought replace means replace...
SinglePokemonFragment.java (Buttons)
cLayBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Create new fragment and transaction
Fragment newFragment = new SinglePokemonFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
Bundle bundle = new Bundle();
bundle.putInt("POKEMON_ID", Integer.parseInt(db.getPokemonID(intPokeDexID-1)));
bundle.putInt("ARRAY_ID", intPokeArrayID-1);
bundle.putInt("POKEMON_ID_MAX", getIntPokemonIDMax);
bundle.putInt("POKEDEX_ID", intPokeDexID-1);
newFragment.setArguments(bundle);
transaction.replace(R.id.frame_container, newFragment);
// Commit the transaction
transaction.commit();
}
});
cLayForward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Create new fragment and transaction
Fragment newFragment = new SinglePokemonFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
Bundle bundle = new Bundle();
bundle.putInt("POKEMON_ID", Integer.parseInt(db.getPokemonID(intPokeDexID+1)));
bundle.putInt("ARRAY_ID", intPokeArrayID+1);
bundle.putInt("POKEMON_ID_MAX", getIntPokemonIDMax);
bundle.putInt("POKEDEX_ID", intPokeDexID+1);
newFragment.setArguments(bundle);
transaction.replace(R.id.frame_container, newFragment);
// Commit the transaction
transaction.commit();
}
});
MainFragment.java (with ViewPager)
public class MainFragment extends Fragment {
private TextView titleTxtView;
private static final String ARG_PARAM1 = "param1";
private String mParam1;
TabLayout tabLayout;
ViewPager viewPager;
private FragmentActivity myContext;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
tabLayout = (TabLayout) view.findViewById(R.id.tab_layout);
viewPager = (ViewPager) view.findViewById(R.id.pager);
if (viewPager != null) {
Log.v("ViewPager", "IS NOT NULL");
setupViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.ic_pokedex);
tabLayout.getTabAt(1).setIcon(R.drawable.pokedex_kanto);
tabLayout.getTabAt(2).setIcon(R.drawable.pokedex_johto);
tabLayout.getTabAt(3).setIcon(R.drawable.pokedex_hoenn);
}else{
Log.v("ViewPager", "ISNULL");
}
return view;
}
#Override
public void onAttach(Activity activity) {
myContext=(FragmentActivity) activity;
super.onAttach(activity);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
}
}
private void setupViewPager(ViewPager viewPager) {
PagerAdapter adapter = new PagerAdapter(getChildFragmentManager(), getActivity());
adapter.addFragment(new PokedexFragment().newInstance(0, 9999), "Alle");
adapter.addFragment(new PokedexFragment().newInstance(1, 151), "Kanto");
adapter.addFragment(new PokedexFragment().newInstance(152, 251), "Johto");
adapter.addFragment(new PokedexFragment().newInstance(252, 386), "Hoenn");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
}
}
PokedexFragment.java
package com.spicysoftware.goexpert;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toolbar;
import java.util.ArrayList;
import java.util.List;
import static android.content.ContentValues.TAG;
public class PokedexFragment extends Fragment{
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
MySQLiteHelper db;
// TODO: Rename and change types of parameters
private int param1, param2;
public PokedexFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
param1 = getArguments().getInt(ARG_PARAM1);
param2 = getArguments().getInt(ARG_PARAM2);
}
}
public static PokedexFragment newInstance(int intDexFrom, int intDexTo) {
PokedexFragment fragment = new PokedexFragment();
Bundle args = new Bundle();
args.putInt(ARG_PARAM1, intDexFrom);
args.putInt(ARG_PARAM2, intDexTo);
fragment.setArguments(args);
Log.d(TAG, "newInstance: 2F");
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View myView = inflater.inflate(R.layout.fragment_pokedexall, container, false);
db = new MySQLiteHelper(getActivity());
RecyclerView recyclerView = (RecyclerView)myView.findViewById(R.id.rvPokedex);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getActivity(),4);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemViewCacheSize(20);
recyclerView.setDrawingCacheEnabled(true);
recyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
CustomRecyclerAdapterPokedexGrid adapter = new CustomRecyclerAdapterPokedexGrid(getActivity(), db.getPokemon(param1,param2));
recyclerView.setAdapter(adapter);
return myView;
}
}
CustomRecyclerAdapterPokedexGrid.java (ItemClickListener)
viewHolder.setClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
if (isLongClick) {
} else {
String test = strPokemonInfo.get(i);
String[] separated = test.split("/");
intPokemonID = Integer.parseInt(separated[0]);
pokeDexID = Integer.parseInt(separated[1]);
Fragment myFragment = new SinglePokemonFragment();
Bundle bundle = new Bundle();
bundle.putInt("POKEMON_ID", intPokemonID);
bundle.putInt("ARRAY_ID", i);
bundle.putInt("POKEMON_ID_MAX", strPokemonInfo.size());
bundle.putInt("POKEDEX_ID", pokeDexID);
myFragment.setArguments(bundle);
AppCompatActivity activity = (AppCompatActivity) view.getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, myFragment).addToBackStack(null).commit();
}
}
});

Android ViewPager displays white screen

I'm trying to create VeiwPager inside a Fragment using FragmentStatePagerAdapter.
it displays the first fragment but after scrolling to the second fragment there is just white fragment (even on scrolling back to the first fragment)
I've tried to use PagerAdapter and set pictures without fragment but the result is same.
is there RAM problem ? what can I do to solve it?
Home fragment(contains ViewPager) :
private void initSlideShow(View view){
VPImageSlider = (ViewPager16by9) view.findViewById(R.id.VPImageSlider);
sliderDotsPanel = (LinearLayout) view.findViewById(R.id.SliderDots);
VPImageSliderAdapter vpImageSliderAdapter = new VPImageSliderAdapter(getFragmentManager());
vpImageSliderAdapter.addSlide(R.drawable.dc_slide_1);
vpImageSliderAdapter.addSlide(R.drawable.dc_slide_2);
vpImageSliderAdapter.addSlide(R.drawable.dc_slide_3);
vpImageSliderAdapter.addSlide(R.drawable.dc_slide_4);
vpImageSliderAdapter.addSlide(R.drawable.dc_slide_5);
VPImageSlider.setAdapter(vpImageSliderAdapter);
}
ViewPager Fragment:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import iranelab.samsoft.net.iranelab.Classes.ImageView16by9;
import iranelab.samsoft.net.iranelab.R;
public class ViewPagerFragment extends Fragment {
private static final String ARG_PARAM4 = "imageTest";
private int imageTest;
public ViewPagerFragment() {}
public static ViewPagerFragment newInstance(String imageId, String type, String text,int imageTest) {
ViewPagerFragment fragment = new ViewPagerFragment();
Bundle args = new Bundle();
args.putInt(ARG_PARAM4, imageTest);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
imageTest = getArguments().getInt(ARG_PARAM4);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_view_pager, container, false);
ImageView16by9 image = (ImageView16by9) view.findViewById(R.id.IVSlide);
image.setImageResource(imageTest);
return view;
}
}
ViewPager Adapter :
public class VPImageSliderAdapter extends FragmentStatePagerAdapter {
private int[] slides = {};
public VPImageSliderAdapter(FragmentManager fm){
super(fm);
}
public void addSlide(int drawable){
slides = Arrays.copyOf(slides,slides.length+1);
slides[slides.length-1]=drawable;
}
#Override
public int getCount() {
return slides.length;
}
#Override
public Fragment getItem(int position) {
return ViewPagerFragment.newInstance(slides[position]);
}
}
Change
VPImageSliderAdapter vpImageSliderAdapter = new VPImageSliderAdapter(getFragmentManager());
to
VPImageSliderAdapter vpImageSliderAdapter = new VPImageSliderAdapter(getChildFragmentManager());
it will work
Just needed to add :
ViewPager.setOffscreenPageLimit(5);

Add ViewPager in Fragment in Android

I have two fragments: FirstFragment and SecondFragment. FirstFragment contains ViewPager, which has three pages (three fragments). In the onCreate of activty, I add FirstFragment to main layout, and three pages show normally.
Problem is: when I replace FirstFragment by SecondFragment, and then comeback FirstFragment three pages disappear. Then I scroll ViewPager forward and backward, pages show but only first and third pages show, second page disappear.
Here FirstFragment:
package com.example.bkmsx.afragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FirstFragment extends Fragment {
ViewPager mViewPager;
static MainActivity mainActivity;
public static FirstFragment newInstance(MainActivity activity){
mainActivity = activity;
return new FirstFragment();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.first_fragment, null);
mViewPager = (ViewPager) view.findViewById(R.id.view_pager);
ViewPagerAdapter adapter = new ViewPagerAdapter(mainActivity.getSupportFragmentManager());
mViewPager.setAdapter(adapter);
return view;
}
private class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
String text = "";
switch (position) {
case 0: text = "First Page";
break;
case 1: text = "Second Page";
break;
case 2: text = "Third Page";
break;
}
return TextFragment.newInstance(mainActivity, text);
}
#Override
public int getCount() {
return 3;
}
}
}
SecondFragment:
package com.example.bkmsx.afragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class SecondFragment extends Fragment {
static MainActivity mainActivity;
public static SecondFragment newInstance(MainActivity activity) {
mainActivity = activity;
return new SecondFragment();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
TextView textView = new TextView(mainActivity);
textView.setText("New Fragment");
return textView;
}
}
Any suggestion? Thanks in advance.
In FirstFragment , Use this code and try
public View view; // declare view as global variable
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
if(view == null){
view = inflater.inflate(R.layout.first_fragment, null);
mViewPager = (ViewPager) view.findViewById(R.id.view_pager);
ViewPagerAdapter adapter = new ViewPagerAdapter(mainActivity.getSupportFragmentManager());
mViewPager.setAdapter(adapter);
}
return view;
}
As Divyesh comment has good suggestion there is also need to add
mViewPager.setOffscreenPageLimit(3);
use ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager() ); instead of mainActivity.getSupportFragmentManager()
Try this code Hope it helps
final ViewPager viewPager = (ViewPager) findViewById(R.id.container);
final PagerAdapter adapter = new PaginationAdapter(getSupportFragmentManager(),tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
viewPager.setOffscreenPageLimit(3);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});

Can't add fragments - android

I'm trying to build a simple application that displays two fragments. The first fragment is displayed by default. It contains a list of names which you can choose and when you click on one of the items, it supposes to display a second fragment with a text view, displaying the name you have chosen.
The problem is everytime I click one of the names on the list, it throws me a NullPointerException. I really don't know what could be the problem.
Here are the codes( The app contains three class - two fragments and one activity. The FriendsF fragment is the list fragment and it performs well. The second fragment is FeedFragment and onitemclick it should display the name that was clicked)
FriendsF fragment:
package com.example.fragmentsexcersize;
import android.app.Activity;
import android.app.ListFragment;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class FriendsF extends ListFragment {
private static final String[] FRIENDS = { "ladygaga", "msrebeccablack",
"taylorswift13" };
public interface SelectionListener {
public void onItemSelected(int position);
}
private SelectionListener mCallback;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ? android.R.layout.simple_list_item_activated_1
: android.R.layout.simple_list_item_1;
setListAdapter(new ArrayAdapter<String>(getActivity().getBaseContext(), layout, FRIENDS));
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (SelectionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement SelectionListener");
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (isInTwoPaneMode()) {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
}
#Override
public void onListItemClick(ListView l, View view, int position, long id) {
mCallback.onItemSelected(position);
}
private boolean isInTwoPaneMode() {
return getFragmentManager().findFragmentById(R.id.tweets) != null;
}
}
FeedFragment:
package com.example.fragmentsexcersize;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class FeedFragment extends Fragment{
private TextView mTextView;
private static final String[] data = { "ladygaga", "msrebeccablack",
"taylorswift13" };
public FeedFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tweet_view, container, false);
mTextView = (TextView) rootView.findViewById(R.id.tweet_view);
return rootView;
}
public void updateFeedDisplay(int position) {
mTextView.setText(data[position]);
}
}
MainActivity:
package com.example.fragmentsexcersize;
import android.app.Activity;
import android.app.FragmentManager;
import android.os.Bundle;
import android.app.FragmentTransaction;
public class MainActivity extends Activity implements FriendsF.SelectionListener{
private FriendsF mFriendsFragment;
private FeedFragment mFeedFragment;
private FragmentManager fragMana;
private FragmentTransaction transaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFriendsFragment = new FriendsF();
fragMana = getFragmentManager();
transaction = fragMana.beginTransaction();
transaction.add(R.id.friends, mFriendsFragment);
transaction.commit();
}
private boolean isInTwoPaneMode() {
return findViewById(R.id.tweets) == null;
}
public void onItemSelected(int position) {
if (mFeedFragment == null)
mFeedFragment = new FeedFragment();
if (!isInTwoPaneMode()) {
transaction = fragMana.beginTransaction();
transaction.add(R.id.tweets, mFeedFragment);
transaction.commit();
}
mFeedFragment.updateFeedDisplay(position);
}
}
Make the following changes to your source:
MainActivity
public void onItemSelected(int position) {
Bundle bundle = new Bundle();
if (mFeedFragment == null)
mFeedFragment = new FeedFragment();
if (!isInTwoPaneMode()) {
bundle.putInt("POSITION", position);
mFeedFragment.setArguments(bundle);
transaction = fragMana.beginTransaction();
transaction.replace(R.id.tweets, mFeedFragment);
transaction.commit();
}
}
FeedFragment
private TextView mTextView;
private static final String[] data = { "ladygaga", "msrebeccablack",
"taylorswift13" };
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
View rootView = inflater.inflate(R.layout.tweet_view, container, false);
mTextView = (TextView) rootView.findViewById(R.id.tweet_view);
int mPosition = getArguments().getInt("POSITION", 0);
mTextView.setText(data[mPosition]);
return rootView;
}

Categories

Resources