i'm back here with a new Question. So at the moment i created an app , that can switch from a fragment to another fragment when you click on a button. And inside those 2 fragments there is 2 viewPagers, whose create a custom number of buttons. But the problem is that when i switch from a fragment to the other one, and then i switch back , the content of the first one is no longer here. I tried a lot of things and nothing really help me. And i hope you can help me. Thanks in advance.
The Main Activity :
public class MainActivity extends AppCompatActivity {
String identifiant=null;
BottomBar bottombar;
ProgressBar progressBar;
ImageButton imageButton;
TextView nomson;
RelativeLayout aaaa;
FragmentWhizz fragmentWhizz;
FragmentPlaylist fragmentPlaylist;
FragmentManager fm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
autorisation();
fragmentWhizz = new FragmentWhizz();
fragmentPlaylist=new FragmentPlaylist();
Fragment fragment = new FragmentConnexion();
FragmentManager fm = getFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.contentFragment, fragment);
transaction.commit();
bottombar = (BottomBar) findViewById(bottomBar);
aaaa = (RelativeLayout) findViewById(R.id.aaaa);
bottombar.setVisibility(View.INVISIBLE);
bottombar.setOnTabSelectListener(new OnTabSelectListener() {
#Override
public void onTabSelected(#IdRes int tabId) {
if (tabId == R.id.tab_whiz) {
if(identifiant !=null){
changementFragment(fragmentWhizz);
}
}
if (tabId == R.id.tab_playlist) {
if(identifiant !=null){
changementFragment(fragmentPlaylist);
}
}
if (tabId == R.id.tab_reveil) {
if(identifiant !=null){
changementFragment(new FragmentReveil());
}
}
if (tabId == R.id.tab_param) {
if(identifiant !=null){
changementFragment(new FragmentParam());
}
}
}
});
}
public void changementFragment(final Fragment fragment){
runOnUiThread(new Runnable() {
public void run() {
fm = getFragmentManager();
FragmentTransaction ft =fm.beginTransaction();
ft.setCustomAnimations(android.R.animator.fade_in,android.R.animator.fade_out);
ft.replace(R.id.contentFragment, fragment).commit();
}
});
}
}
One of the 2 fragments that have the ViewPager:
public class FragmentPlaylist extends Fragment {
SlideToutesPlaylist fragmentAllPlaylist = new SlideToutesPlaylist();
SlideUserPlaylist fragmentUserPlaylist = new SlideUserPlaylist();
ViewPager mViewPager;
FloatingActionButton floatbutton;
private FragmentActivity myContext;
#Override
public void onAttach(Activity activity) {
myContext=(FragmentActivity) activity;
super.onAttach(activity);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.playlist, container, false);
DeplacerBoutton deplacer = new DeplacerBoutton(getActivity(),2);
floatbutton = (FloatingActionButton) myView.findViewById(R.id.floatingActionButton);
floatbutton.setOnTouchListener(deplacer);
mViewPager = (ViewPager) myView.findViewById(R.id.slide);
mViewPager.setAdapter(new SamplePagerAdapter(myContext.getSupportFragmentManager()));
Log.i("test","test");
return myView;
}
public class SamplePagerAdapter extends FragmentStatePagerAdapter {
SamplePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
/** Show a Fragment based on the position of the current screen */
if (position == 0) {
return fragmentAllPlaylist;
} else
return fragmentUserPlaylist;
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
}
}
And finally one fragment displayed on the viewPager:
public class SlideToutesPlaylist extends Fragment {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.playlistall, container, false);
AffichePlaylist(myView);
return myView;
}
public void AffichePlaylist(View myView){
ExecHttpGetRequest requete = new ExecHttpGetRequest();
requete.execute("an IP");
LinearLayout aaa = (LinearLayout) myView.findViewById(R.id.aaa);
try {
if (requete.get() != null) {
JSONObject jsonObj = new JSONObject(requete.get());
JSONArray jSon = jsonObj.getJSONArray("valeurs");
for (int i = 0; i < jSon.length(); i++) {
JSONObject c = jSon.getJSONObject(i);
final String nom_playlist = c.getString("nom_playlist");
final String id_playlist = c.getString("id_playlist");
final String id_createur = c.getString("id_createur");
final String nb_vote = c.getString("nb_vote");
Button bouton = new Button(getContext());
bouton.setText(nom_playlist);
aaa.addView(bouton);
}
}
} catch (InterruptedException | ExecutionException | JSONException e) {
e.printStackTrace();
}
}
}
EDIT Ok finally i solved my problem with your solution but now i have this problem :
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
at android.support.v4.app.FragmentManagerImpl.getFragment(FragmentManager.java:873)
at android.support.v4.app.FragmentStatePagerAdapter.restoreState(FragmentStatePagerAdapter.java:215)
at android.support.v4.view.ViewPager.onRestoreInstanceState(ViewPager.java:1481)
at android.view.View.dispatchRestoreInstanceState(View.java:14762)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:3123)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:3129)
at android.view.View.restoreHierarchyState(View.java:14740)
at android.support.v4.app.Fragment.restoreViewState(Fragment.java:475)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1329)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:757)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2355)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2146)
at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2098)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2008)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
To inflate fragments inside another fragment you need tu use getChildFragmentManager() instead of
myContext.getSupportFragmentManager().
EDIT:
Use FragmentStatePagerAdapter as follows:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import java.util.ArrayList;
import java.util.List;
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> mFragmentList = new ArrayList<>();
private List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
//Check if the list is empty before return the size
#Override
public int getCount() {
return mFragmentList != null ? mFragmentList.size() : 0;
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public void addFragment(Fragment fragment) {
mFragmentList.add(fragment);
}
#Override
public CharSequence getPageTitle(int position) {
if (!mFragmentTitleList.isEmpty()) {
return mFragmentTitleList.get(position);
}
return "";
}
}
Then in your fragment just add the fragments you want to show in the viewPager:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
...
viewPager = (ViewPager) view.findViewById(R.id.viewpager);
adapter = new ViewPagerAdapter(getChildFragmentManager());
adapter.addFragment(SlideToutesPlaylist.newInstance(), getString(R.string.title));
adapter.addFragment(SlideToutesPlaylist.newInstance(), getString(R.string.title));
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(2);
Related
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);
how to switch between Fragment A and Fragment B in android TabLayout.
how to switch to next Fragment when Fargment Button Onclick is called.
Please help me
package com.digi.global.globalhub.fragment.offer;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.digi.global.globalhub.R;
import com.digi.global.globalhub.Utility.M;
import com.digi.global.globalhub.listener.FilterListener;
import com.digi.global.globalhub.listener.FragmentMove;
import com.digi.global.globalhub.listener.OfferFilter;
public class OfferFragmentActivity extends Fragment implements View.OnClickListener{
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
PagerAdapter adapter;
ViewPager viewPager;
TabLayout tabLayout;
Context context;
Toolbar toolbar;
ImageView bizMenu;
PopupMenu popup;
public static OfferFragmentActivity mInstance = null;
public OfferFragmentActivity() {
// Required empty public constructor
}
public static OfferFragmentActivity newInstance(String param1, String param2) {
OfferFragmentActivity fragment = new OfferFragmentActivity();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
context = this.getContext();
mInstance = this;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view =inflater.inflate(R.layout.fragment_offer, container, false);
viewPager = (ViewPager) view.findViewById(R.id.viewpager);
adapter = new PagerAdapter(getChildFragmentManager(), getContext());
tabLayout = (TabLayout) view.findViewById(R.id.tablayout);
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
toolbar = (Toolbar) view.findViewById(R.id.toolbar);
bizMenu = (ImageView) view.findViewById(R.id.bizMenu);
bizMenu.setVisibility(View.VISIBLE);
bizMenu.setOnClickListener(this);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
//toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.biz_ic, android.R.style.Theme_DeviceDefault));
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final Drawable upArrow = getResources().getDrawable(R.mipmap.ic_menu_white_36dp);
upArrow.setColorFilter(Color.parseColor("#B68426"), PorterDuff.Mode.SRC_ATOP);
((AppCompatActivity)getActivity()).getSupportActionBar().setHomeAsUpIndicator(upArrow);
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(getString(R.string.Offers));
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(final TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return view;
}
#Override
public void onClick(View v) {
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Fragment fragment = (Fragment) adapter.instantiateItem(viewPager, viewPager.getCurrentItem());
if(fragment instanceof OfferFilter){
switch (item.getItemId()) {
case R.id.bizTravel:
((OfferFilter) fragment).onFilterBizTravel("bizTravel");
return true;
case R.id.bizAssistance:
((OfferFilter) fragment).onFilterAssistance("bizAssistance");
return true;
case R.id.bizSolution:
((OfferFilter) fragment).onFilterSolution("bizSolution");
return true;
case R.id.partners:
((OfferFilter) fragment).onFilterPartner("partners");
return true;
case R.id.favoutites:
((OfferFilter) fragment).onFilterFavouritesBiz("favoutites");
return true;
}
return false;
}
return super.onOptionsItemSelected(item);
}
class PagerAdapter extends FragmentStatePagerAdapter {
String tabTitles[] = getResources().getStringArray(R.array.offerTab);
Context context;
public PagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return tabTitles.length;
}
#Override
public Fragment getItem(int position) {
/* FragmentMove fragmentChanges = (FragmentMove) adapter.instantiateItem(viewPager, 2);
if(fragmentChanges instanceof FragmentMove) {
((FragmentMove) fragmentChanges).fragmentChanges();
}*/
switch (position) {
case 0:
return new FragmentOne();
case 1:
return new FragmentTWO();
case 2:
return new FragmentThree();
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
/* public View getTabView(int position) {
View tab = LayoutInflater.from(getContext()).inflate(R.layout.tab_text_layout, null);
TextView tv = (TextView) tab.findViewById(R.id.tabText);
tv.setText(tabTitles[position]);
return tab;
}*/
}
}
You can have a FragmentPagerAdapter to manager fragments and set this adapter into viewPager to slide fragments when you click on tabs or swipe to change tabs.
FragmentPagerAdapter:
public class TabLayoutViewPagerAdapter extends FragmentPagerAdapter {
private final int PAGE_COUNT = 3;
private final String[] mTabsTitle = {"Fragment A", "Fragment B, "Fragment C"};
private Context context;
private int[] mTabsIcons = {
R.drawable.a,
R.drawable.b,
R.drawable.c};
public TabLayoutViewPagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
public View getTabView(int position) {
View view = LayoutInflater.from(context).inflate(R.layout.custom_tab, null);
TextView title = (TextView) view.findViewById(R.id.title);
title.setText(mTabsTitle[position]);
title.setSingleLine(true);
ImageView icon = (ImageView) view.findViewById(R.id.icon);
icon.setImageResource(mTabsIcons[position]);
return view;
}
#Override
public Fragment getItem(int pos) {
switch (pos) {
case 0:
return new FragmentA();
case 1:
return new FragmentB();
case 2:
return new FragmentC();
}
return null;
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public CharSequence getPageTitle(int position) {
return mTabsTitle[position];
}}
How you use it:
ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
TabLayoutViewPagerAdapter pagerAdapter = new TabLayoutViewPagerAdapter(getSupportFragmentManager(), this);
if (viewPager != null) {
viewPager.setAdapter(pagerAdapter);
}
You need a TabLayout:
mTabLayout = (TabLayout) findViewById(R.id.tabLayout);
if (mTabLayout != null) {
mTabLayout.setupWithViewPager(viewPager);
//populate your tabs
for (int i = 0; i < mTabLayout.getTabCount(); i++) {
TabLayout.Tab tab = mTabLayout.getTabAt(i);
if (tab != null)
tab.setCustomView(pagerAdapter.getTabView(i));
}
TabLayout.Tab tab = mTabLayout.getTabAt(0);
if (tab != null && tab.getCustomView() != null) {
tab.getCustomView().setSelected(true);
}
}
How to select a page:
private void selectPage(int pageIndex) {
mTabLayout.setScrollPosition(pageIndex, 0f, true);
viewPager.setCurrentItem(pageIndex);
}
Do not forget to create your customTab.xml.
Best regards.
In Fragment A's onClick() method, try this :
TabActivity tabs = (TabActivity) getParent();
tabs.getTabHost().setCurrentTab(2);
I have an activity which uses view pager to switch between fragments. I have three fragments. While switching between these fragments i have to pass a string value to the fragment class to identify which fragment is selected.Because here I am using same fragment class for all the three fragments.
Here is my main activity.
public class mainActivity extends AppCompatActivity {
public String kind, value;
private TabLayout tabLayout;
private ViewPager viewPager;
public FloatingActionButton upload, send;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
upload = (FloatingActionButton) findViewById(R.id.upload_fab);
send = (FloatingActionButton) findViewById(R.id.send_message);
uploadFab.hide();
Intent mIntent = getIntent();
kind = mIntent.getStringExtra("KIND");
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Student student =new Student();
switch (position) {
case 0:
upload.hide();
value = "r";
break;
case 1:
upload.hide();
value = "e";
break;
case 2:
upload.show();
value = "u";
break;
default:
upload.hide();
val = "r";
break;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new RemainderFragment(), "REMAINDER");
adapter.addFragment(new RemainderFragment(), "EMAIL");
adapter.addFragment(new RemainderFragment(), "UPLOAD");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
here is my fragment class
public class RemainderFragment extends Fragment {
public RemainderEmailFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.raminder_fragment, container, false);
EditText subject = (EditText) rootView.findViewById(R.id.subject);
EditText des = (EditText) rootView.findViewById(R.id.description);
// String value = mainActivity.value
//button to send data
button = activity.send;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//getting details
SendData();
}
});
return rootView;
}
public void SendData() {
//functon
}
I have tried intents and shared preferences to send data. but nothing worked. I have to get the String value in my fragment class. please help.
Please check the below code for sample required changes, I have modified your file and added some code to support your requirement.
Your Activity file
package com.adobe.reader.test;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import com.adobe.reader.R;
public class mainActivity extends AppCompatActivity
{
public String kind, value;
private TabLayout tabLayout;
private ViewPager viewPager;
public FloatingActionButton upload, send;
// Adding adapter
private ViewPagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
upload = (FloatingActionButton) findViewById(R.id.upload_fab);
send = (FloatingActionButton) findViewById(R.id.send_message);
uploadFab.hide();
Intent mIntent = getIntent();
kind = mIntent.getStringExtra("KIND");
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
// Let's say we need to call some method from fragment in the activity
Fragment fragment = getCurrentFragment();
if (Fragment instanceof RemainderFragment)
{
RemainderFragment remainderFragment = (RemainderFragment) fragment;
remainderFragment.setString("Testing string");
}
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Fragment fragment = getCurrentFragment();
if (Fragment instanceof RemainderFragment)
{
RemainderFragment remainderFragment = (RemainderFragment) fragment;
}
Student student =new Student();
switch (position) {
case 0:
upload.hide();
value = "r";
break;
case 1:
upload.hide();
value = "e";
break;
case 2:
upload.show();
value = "u";
break;
default:
upload.hide();
val = "r";
break;
}
remainderFragment.setString(value);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
/**
* This method will give you current fragment used in the viewpager.
* #return
*/
public Fragment getCurrentFragment()
{
Fragment fragment = null;
if (viewPager != null)
{
int currentFragmentIndex = viewPager.getCurrentItem();
if (adapter != null)
{
fragment = adapter.getItem(currentFragmentIndex);
}
}
return fragment;
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new RemainderFragment(), "REMAINDER");
adapter.addFragment(new RemainderFragment(), "EMAIL");
adapter.addFragment(new RemainderFragment(), "UPLOAD");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
Your Fragment file
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import com.adobe.reader.R;
public class RemainderFragment extends Fragment
{
public String testingString;
public RemainderEmailFragment() {
// Required empty public constructor
}
// Sample method to be called from activity
public void setString(String testStr)
{
testingString = testStr;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.raminder_fragment, container, false);
EditText subject = (EditText) rootView.findViewById(R.id.subject);
EditText des = (EditText) rootView.findViewById(R.id.description);
// String value = mainActivity.value
//button to send data
button = activity.send;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//getting details
SendData();
}
});
return rootView;
}
public void SendData() {
//functon
}
Hi I am new to Android and get a problem with Recycler View and fragment.
There are 3 fragments that can swipe, and there is a recycler view with an adapter that is in the fragment. I got a sample code from http://developer.android.com/training/implementing-navigation/lateral.html but I get null pointer exception in List object. Thanks in advance. My code is showed below:
public class TripHistoryActivity extends FragmentActivity implements ActionBar.TabListener{
private static final String TAG = "TripHistoryActivity";
private CommonDBHelper commonDBHelper;
private List<Trip> allTrips;
private ArrayList<Trip> currentTrips;
private ArrayList<Trip> pastTrips;
private ArrayList<Trip> futureTrips;
AppSectionsPagerAdapter mAppSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trip_history);
commonDBHelper = new CommonDBHelper(this);
TripDBHelper tripDBHelper = new TripDBHelper(commonDBHelper.getWritableDatabase());
allTrips = tripDBHelper.getAllTrips();
currentTrips = new ArrayList<>();
pastTrips = new ArrayList<>();
futureTrips = new ArrayList<>();
Calendar calendar = Calendar.getInstance();
int currentDay = calendar.get(calendar.DAY_OF_MONTH);
int currentMonth = calendar.get(calendar.MONTH);
int currentYear = calendar.get(calendar.YEAR);
for (Trip trip : allTrips) {
String date = trip.getTime().substring(0, trip.getTime().indexOf(" "));
String[] dates = date.split("/");
if (currentYear < Integer.valueOf(dates[2])) {
futureTrips.add(trip);
}
else if (currentYear > Integer.valueOf(dates[2])
|| currentMonth > Integer.valueOf(dates[0])
|| currentDay > Integer.valueOf(dates[1])) {
pastTrips.add(trip);
}
else {
currentTrips.add(trip);
}
}
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
final ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// When swiping between different app sections, select the corresponding tab.
// We can also use ActionBar.Tab#select() to do this if we have a reference to the
// Tab.
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by the adapter.
// Also specify this Activity object, which implements the TabListener interface, as the
// listener for when this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mAppSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to one of the primary
* sections of the app.
*/
public class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public android.support.v4.app.Fragment getItem(int i) {
switch (i) {
case 0:
android.support.v4.app.Fragment currentTripsFragment = new CurrentTripsFragment();
Bundle currentTripsBundle = new Bundle();
currentTripsBundle.putParcelableArrayList("currentTrips", currentTrips);
currentTripsFragment.setArguments(currentTripsBundle);
return currentTripsFragment;
case 1:
android.support.v4.app.Fragment pastTripsFragment = new PastTripsFragment();
Bundle pastTripsBundle = new Bundle();
pastTripsBundle.putParcelableArrayList("pastTrips", pastTrips);
pastTripsFragment.setArguments(pastTripsBundle);
return pastTripsFragment;
default:
android.support.v4.app.Fragment futureTripsFragment = new FutureTripsFragment();
Bundle futureTripsBundle = new Bundle();
futureTripsBundle.putParcelableArrayList("futureTrips", futureTrips);
futureTripsFragment.setArguments(futureTripsBundle);
return futureTripsFragment;
}
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Current Trips";
case 1:
return "Past Trips";
case 2:
return "Future Trips";
default:
return "Fault";
}
}
}
/**
* A fragment that launches other parts of the demo application.
*/
public static class CurrentTripsFragment extends android.support.v4.app.Fragment {
private RecyclerView mRecyclerView;
private Context context;
List<Trip> currentTrips;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_current_trips, container, false);
context = rootView.getContext();
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
currentTrips = getArguments().getParcelableArrayList("currentTrips");
Log.d(TripHistoryActivity.TAG, String.valueOf(currentTrips == null));
RecyclerView.LayoutManager manager = new LinearLayoutManager(context);
mRecyclerView.setLayoutManager(manager);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
CardViewAdapter cardViewAdapter = new CardViewAdapter(currentTrips);
mRecyclerView.setAdapter(cardViewAdapter);
cardViewAdapter.setOnItemClick(new CardViewAdapter.OnItemClick() {
#Override
public void onItemClick(int position) {
handleItemClick(position);
}
});
return rootView;
}
public void handleItemClick (int position) {
Toast.makeText(context, "Clicked " + position, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, ViewTripActivity.class);
intent.putExtra("trip", currentTrips.get(position));
startActivity(intent);
}
}
There are 2 other fragments that are same as this one so I omit them.
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.nyu.cs9033.eta.R;
import com.nyu.cs9033.eta.models.Trip;
import java.util.List;
/**
* Created by Ray on 2016/4/2.
*/
public class CardViewAdapter extends RecyclerView.Adapter<CardViewAdapter.CardViewHolder> {
private final List<Trip> trips;
public CardViewAdapter (List<Trip> trips) {
this.trips = trips;
}
public interface OnItemClick {
public void onItemClick(int position);
}
private OnItemClick onItemClick;
public void setOnItemClick (OnItemClick onItemClick) {
this.onItemClick = onItemClick;
}
#Override
public CardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.history_list_item, parent, false);
return new CardViewHolder(view);
}
#Override
public void onBindViewHolder(final CardViewHolder holder, final int position) {
holder.name.setText(trips.get(position).getName());
holder.location.setText(trips.get(position).getLocation());
holder.time.setText(trips.get(position).getTime());
if (onItemClick != null) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onItemClick.onItemClick(position);
}
});
}
}
#Override
public int getItemCount() {
return trips.size();
}
class CardViewHolder extends RecyclerView.ViewHolder {
private TextView name;
private TextView location;
private TextView time;
public CardViewHolder (View view) {
super(view);
name = (TextView) view.findViewById(R.id.card_trip_name);
location = (TextView) view.findViewById(R.id.card_trip_location);
time = (TextView) view.findViewById(R.id.card_trip_time);
}
}
}
This is what logcat says:
FATAL EXCEPTION: mainProcess: com.nyu.cs9033.eta, PID: 14018
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()'
on a null object reference
at com.nyu.cs9033.eta.adapters.CardViewAdapter.getItemCount(CardViewAdapter.java: 57)
at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java: 2357)
at android.view.View.measure(View.java: 18796)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java: 715)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java: 461)
at android.view.View.measure(View.java: 18796)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java: 5951)
at android.widget.FrameLayout.onMeasure(FrameLayout.java: 194)
at android.view.View.measure(View.java: 18796)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java: 1488)
at android.view.View.measure(View.java: 18796)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java: 5951)
at android.widget.FrameLayout.onMeasure(FrameLayout.java: 194)
at android.view.View.measure(View.java: 18796)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java: 5951)
at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java: 446)
at android.view.View.measure(View.java: 18796)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java: 5951)
at android.widget.FrameLayout.onMeasure(FrameLayout.java: 194)
at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java: 2643)
at android.view.View.measure(View.java: 18796)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java: 2108)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java: 1224)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java: 1460)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java: 1115)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java: 6023)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java: 858)
at android.view.Choreographer.doCallbacks(Choreographer.java: 670)
at android.view.Choreographer.doFrame(Choreographer.java: 606)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java: 844)
at android.os.Handler.handleCallback(Handler.java: 739)
at android.os.Handler.dispatchMessage(Handler.java: 95)
at android.os.Looper.loop(Looper.java: 148)
at android.app.ActivityThread.main(ActivityThread.java: 5422)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java: 726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java: 616)
You should get bundle from onCreate() instead of onCreateView(). Try the below change in your Fragment class:
public static class CurrentTripsFragment extends android.support.v4.app.Fragment {
private RecyclerView mRecyclerView;
private Context context;
List<Trip> currentTrips;
#Override
public void onCreate(Bundle savedInstanceState){
super().onCreate(savedInstanceState);
if(getArguments()!= null){
currentTrips = getArguments().getParcelableArrayList("currentTrips");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_current_trips, container, false);
context = rootView.getContext();
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
Log.d(TripHistoryActivity.TAG, String.valueOf(currentTrips == null));
RecyclerView.LayoutManager manager = new LinearLayoutManager(context);
mRecyclerView.setLayoutManager(manager);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
CardViewAdapter cardViewAdapter = new CardViewAdapter(currentTrips);
mRecyclerView.setAdapter(cardViewAdapter);
cardViewAdapter.setOnItemClick(new CardViewAdapter.OnItemClick() {
#Override
public void onItemClick(int position) {
handleItemClick(position);
}
});
return rootView;
}
public void handleItemClick (int position) {
Toast.makeText(context, "Clicked " + position, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, ViewTripActivity.class);
intent.putExtra("trip", currentTrips.get(position));
startActivity(intent);
}
}
You are getting a null pointer exception on your list which you are using to show list items in recycler view...please check whether you are getting your data in the list or not...problem seems to be here:
CardViewAdapter cardViewAdapter = new CardViewAdapter(currentTrips);
and here:
currentTrips = getArguments().getParcelableArrayList("currentTrips");
MainActivity.java
public class MainActivity extends ActionBarActivity {
Toolbar toolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
private ArrayList<String> mLanguagesArray = null;
int Numboftabs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if (extras != null) {
mLanguagesArray = new ArrayList<String>();
mLanguagesArray.addAll(extras.getStringArrayList("languages"));
Numboftabs = mLanguagesArray.size();
}
}
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setIcon(R.drawable.ic_launcher);
adapter = new ViewPagerAdapter(getSupportFragmentManager(),
mLanguagesArray, Numboftabs, MainActivity.this);
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setViewPager(pager);
tabs.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int arg0) {
refreshListInFragment(arg0);
}
});
}
protected void refreshListInFragment(int position) {
String currentLanguage = mLanguagesArray.get(position);
FragmentManager fm = getSupportFragmentManager();
ListviewFragment fragment = (ListviewFragment) fm
.findFragmentById(R.id.pager);
fragment.loadListview(currentLanguage);
}
}
ViewPagerAdapter.java
import java.util.ArrayList;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
ArrayList<String> Titles;
int NumbOfTabs;
Context mContext;
public ViewPagerAdapter(FragmentManager fm,
ArrayList<String> mLanguagesArray, int mNumbOfTabsumb,
Context context) {
super(fm);
Titles = new ArrayList<String>();
this.Titles = mLanguagesArray;
this.NumbOfTabs = mNumbOfTabsumb;
this.mContext = context;
}
#Override
public Fragment getItem(int position) {
ListviewFragment listfragment = new ListviewFragment(mContext);
return listfragment;
}
#Override
public CharSequence getPageTitle(int position) {
return Titles.get(position);
}
#Override
public int getCount() {
return NumbOfTabs;
}
}
ListviewFragment.java
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.ListView;
import android.widget.ProgressBar;
public class ListviewFragment extends Fragment {
ProgressBar progressbar;
ListView list;
ArrayList<RStore> mRstoreList = null;
RadioListAdapter adapter;
Context mContext;
Button tryagain;
String mCurrentLanguage = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.listviewfragment, container, false);
progressbar = (ProgressBar) v.findViewById(R.id.progressbar);
list = (ListView) v.findViewById(R.id.listview);
if (ListviewFragment.this.isMenuVisible()) {
if (mRstoreList == null) {
loadListview("English");
}
}
return v;
}
public void loadListview(final String currentlanguage) {
this.mCurrentLanguage = currentlanguage;
mRstoreList = new ArrayList<RStore>();
new AsyncTask<Void, Void, String>() {
private String jsonStr;
#Override
protected void onPreExecute() {
list.setVisibility(View.GONE);
progressbar.setVisibility(View.VISIBLE);
tryagain.setVisibility(View.GONE);
super.onPreExecute();
}
#Override
protected String doInBackground(Void... arg0) {
try {
String URL = ServiceUrls.MUSIC_PHP;
CustomHttpClient sh = new CustomHttpClient();
JSONObject jsonobjpost = new JSONObject();
jsonobjpost.put("languages", currentlanguage);
jsonStr = sh.makeServiceCall(URL, CustomHttpClient.POST,
jsonobjpost.toString());
System.out.println("MUSIC_PHP_Response " + jsonStr);
} catch (Exception e) {
e.printStackTrace();
}
return jsonStr;
}
#Override
protected void onPostExecute(String result) {
if (result == null || result.trim().equalsIgnoreCase("null")
|| result.trim().equalsIgnoreCase("")) {
progressbar.setVisibility(View.GONE);
super.onPostExecute(result);
return;
}
try {
String DUMMYJASON = result.toString();
JSONObject jsonObject = new JSONObject(DUMMYJASON);
JSONArray jsonArray = jsonObject.getJSONArray("Language");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
String id = obj.getString("id");
String language = obj.getString("language");
String tittle = obj.getString("Tittle");
String link = obj.getString("link");
RStore storecon = new RStore();
storecon.setId(id);
storecon.setLanguage(language);
storecon.setTitle(tittle);
storecon.setLink(link);
mRstoreList.add(storecon);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter = new RadioListAdapter(mContext, mRstoreList);
list.setAdapter(adapter);
list.setVisibility(View.VISIBLE);
progressbar.setVisibility(View.GONE);
super.onPostExecute(result);
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
public ListviewFragment(Context context) {
this.mContext = context;
}
}
I'm creating number of fragments dynamically using one fragment class called ListviewFragment and setting it as view page adapter. ListviewFragment contains listview which is populated dynamically from service. With my code everything is working fine the only problem is, sometimes the datas inside the fragments are not refreshing or updating with new values. In my case the listview is showing the previously loaded data but in background the service is called and the listview Adapter is updated but the updated listview is not showing in the fragment. Please see my code, and correct me if i made any mistake..Thanks in advance
Instead of calling a method with (currentLanguage) as a parameter in fragment from activity using findFragmentById, I've just passed (currentLanguage) as bundle in ViewPagerAdapter getItem() method and in ListviewFragment class onCreateView i got (currentlanguage) value using getArguments and passed it to (loadListview) method. Now everything works fine and clean.
ViewPagerAdapter.java
#Override
public Fragment getItem(int position) {
Bundle args = new Bundle();
args.putString("language", Titles.get(position));
ListviewFragment f = new ListviewFragment(mContext);
f.setArguments(args);
return f;
}
ListviewFragment.java
private void getarugs() {
Bundle args = getArguments();
mCurrentLanguage = args.getString("language");
loadListview(mCurrentLanguage);
}