i have written code for image slider but i use drawable images..
Actually i want to know, How to use online images in slideshow instead of
drawables...please help me with complete code as i am new to android..
public class DealsFragment extends Fragment {
private PagerAdapter mPagerAdapter;
public static DealsFragment newInstance() {
DealsFragment fragment = new DealsFragment();
return fragment;
}
public DealsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_deals, container, false);
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(getActivity(), ImageOneDeals.class.getName()));
fragments.add(Fragment.instantiate(getActivity(), ImageTwoDeals.class.getName()));
fragments.add(Fragment.instantiate(getActivity(), ImageThreeDeals.class.getName()));
mPagerAdapter = new ImagePagerAdapter(getChildFragmentManager(), fragments);
pager.setAdapter(mPagerAdapter);
return view;
}
}
ImageOneDeals.java
public class ImageOneDeals extends Fragment {
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){
if(container==null){
return null;
}
return (LinearLayout) inflater.inflate(R.layout.image1_deals,container,false);
}
}
ImagePagerAdapter.java
public class ImagePagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public ImagePagerAdapter(FragmentManager fragmentManager, List<Fragment> fragments){
super(fragmentManager);
this.fragments=fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
}
Your Deal Fragment:-
public class DealFragment extends Fragment {
private View rootView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (rootView == null) {
rootView = inflater.inflate(R.layout.slide_view_pager, container, false);
new GetUserImage().execute(); //run your webservices here
}
return rootView;
}
public class GetUserImage extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(getActivity());
pd.setCancelable(true);
pd.setMessage("Loading...");
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.show();
}
#Override
protected String doInBackground(String... params) {
postUserImageData();
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//save your data in a list
// set Adapter after you get data from webservices
mPager = (ViewPager) rootView.findViewById(R.id.slidePager);
ImagePagerAdapter viewImagePagerAdapter = new ImagePagerAdapter(getChildFragmentManager(), TotalCount, imagearr);
mPager.setAdapter(viewImagePagerAdapter);
mPager.getCurrentItem();
}
public void postUserImageData() {
}
}
}
your Adapter:-
public class ImagePagerAdapter extends FragmentPagerAdapter {
private int numOfItemSize;
List<UserImage> arr1;
public ImagePagerAdapter (FragmentManager childFragmentManager, int num_pages, List<UserImage> customMessageListView) {
super(childFragmentManager);
this.numOfItemSize = num_pages;
this.arr1 = customMessageListView;
}
#Override
public Fragment getItem(int position) {
ImageOneDeals userImageDetailFragment = new ImageOneDeals ();
UserImage sc = arr1.get(position);
Bundle bundle = new Bundle();
bundle.putString("ProfilePic", sc.ProfilePic);
bundle.putString("Work", sc.Work);
bundle.putString("BirthTime", sc.BirthTime);
bundle.putString("Message", sc.Message);
userImageDetailFragment.setArguments(bundle);
return userImageDetailFragment;
}
#Override
public int getCount() {
return numOfItemSize;
}
}
your ImageOneDeals :-
public class ImageOneDeals extends Fragment {
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
Title = getArguments().getString("ProfilePic");
BirthTime = getArguments().getString("BirthTime");
Work = getArguments().getString("Work");
Message = getArguments().getString("Message");
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
final View view = (View) inflater.inflate(R.layout.slide_user_image, container, false);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initialiseViews();
}
public void initialiseViews() {
ImageView imgDetails = (ImageView) getView().findViewById(R.id.UserimageView);
TextView usrname = (TextView) getView().findViewById(R.id.userName);
TextView usrwork = (TextView) getView().findViewById(R.id.userWork);
// imgLoader.DisplayImage(Title,imgDetails);
Picasso.with(getActivity())
.load(Title)
.placeholder( R.mipmap.add_photo)
.error( R.mipmap.add_photo)
.into(imgDetails);
usrname.setText(Message);
usrwork.setText(Work);
}
}
Related
Im trying to use Material Container Transform in Recyclerview Adapter as described by this post MaterialContainerTransform transition is not Working on Return , but after implementing this in my project im getting null pointer exception error.
As everyone know Material Container Transform animation tutorials are in kotlin and im doing it in java.
So if anyone know how to properly use material container transform animation in recyclerview and point out my mistakes i will be very much thankful to him.
RecyclerView Adapter Class(source)
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> implements Filterable {
private Context context;
private List<Astadhyayi> wordList;
private List<Astadhyayi> filwordList;
private DictionaryDB dictionaryDB;
private OnclickListenerInterface listener;
public RecyclerViewAdapter(Context context, List<Astadhyayi> itemList, DictionaryDB dictionaryDB) {
this.context = context;
this.wordList = itemList;
this.dictionaryDB = dictionaryDB;
filwordList = new ArrayList<Astadhyayi>(itemList);
}
public void setClickListener(OnclickListenerInterface onclickListener) {
this.listener = onclickListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.wordslist_two_rv, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
Astadhyayi word = wordList.get(position);
holder.rsutras.setText(word.mSutras);
// Animation******
holder.rsutras.setTransitionName(word.getMSutras());
if (word.mStatus != null && word.mStatus.equals(DictionaryDB.BOOKMARKED)) {
holder.bookmark.setImageResource(R.drawable.cards_heart);
} else {
holder.bookmark.setImageDrawable(null);
}
}
#Override
public Filter getFilter() {
return Searched_Filter;
}
private Filter Searched_Filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<Astadhyayi> filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0) {
filteredList.addAll(filwordList);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for (Astadhyayi item : filwordList) {
if (item.getMSutras().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
wordList.clear();
wordList.addAll((ArrayList<Astadhyayi>)results.values);
notifyDataSetChanged();
}
};
#Override
public int getItemCount() {
return wordList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView rsutras;
private ImageView bookmark;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
rsutras = itemView.findViewById(R.id.tvSansTerm);
bookmark = itemView.findViewById(R.id.bookmarkBtn);
}
/*
#Override
public void onClick(View view) {
if(listener!=null) listener.onItemClicked(getAbsoluteAdapterPosition(), rsutras);
}
*/
#Override
public void onClick(View view) {
int position = this.getAbsoluteAdapterPosition();
Astadhyayi word = wordList.get(position);
//*************** Bundle **************\\
Bundle bundle = new Bundle();
bundle.putParcelable("allData", word);
bundle.putString("transition_name", word.getMSutras());
Fragment detailsFragment = new TermThreeDetailsFragment();
detailsFragment.setSharedElementEnterTransition(new MaterialContainerTransform());
detailsFragment.setArguments(bundle);
FragmentTransaction fT =((AppCompatActivity)context).getSupportFragmentManager().beginTransaction();
fT.setReorderingAllowed(true);
fT.addSharedElement(rsutras, rsutras.getTransitionName()); // Shared element!
fT.replace(R.id.fragment_container, detailsFragment);
fT.addToBackStack(null);
fT.commit();
}
}
}
RecyclerView Fragment Class(source)
public class ShowtermsTwoFragment extends Fragment {
private RecyclerView rv;
private EditText tV;
private Toolbar toolbar;
private LinearLayoutManager layoutManager;
private static DictionaryDB db;
private RecyclerViewAdapter rvAdapter;
private SearchView searchView = null;
private SearchView.OnQueryTextListener queryTextListener;
private List<Astadhyayi> wordsList = new ArrayList<>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setExitTransition(new MaterialElevationScale(false));
setReenterTransition(new MaterialElevationScale(true));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_terms_recyclerview, container, false);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
toolbar = ((Toolbar) view.findViewById(R.id.toolbar_rv));
rv = view.findViewById(R.id.rvTerms);
tV = view.findViewById(R.id.tVinput);
//*********** TOOLBAR
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);
setHasOptionsMenu(true);
// new Get_DbData().execute();
databaseCheck();
recyclerCheck1();
postponeEnterTransition();
((ViewGroup) view.getParent()).getViewTreeObserver()
.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
startPostponedEnterTransition();
return true;
}
});
}
private void databaseCheck() {
String sanskritWord = getActivity().getIntent().getStringExtra("sanskritWord");
//*********** ### DATABASE OPENING ### ***********\\
db = DictionaryDB.getInstance(this.getActivity());
wordsList = db.getWords((sanskritWord));
}
private void recyclerCheck1() {
layoutManager = new LinearLayoutManager(getContext());
rv.setLayoutManager(layoutManager);
rv.setHasFixedSize(true);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(rv.getContext(), layoutManager.getOrientation());
rv.addItemDecoration(dividerItemDecoration);
rvAdapter = new RecyclerViewAdapter(getContext(), wordsList, db);
rv.setAdapter(rvAdapter);
/////********** rvAdapter.setClickListener(this);
rvAdapter.notifyDataSetChanged();
}
}
Details Fragment Class(destination)
public class TermThreeDetailsFragment extends Fragment {
private TextView sutraTV,vrittiTV,padaTv,adhyayTV,sutraIdTV ;
private CoordinatorLayout coordinatorLayout;
private FloatingActionButton fabBtn;
private static DictionaryDB db;
private Astadhyayi word;
private BottomAppBar bottomAppBar;
private TextToSpeech pronunciation;
private AudioManager audio;
private String ttsID , trans;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MaterialContainerTransform transform = new MaterialContainerTransform();
transform.setScrimColor(Color.TRANSPARENT);
setSharedElementEnterTransition(transform);
setSharedElementReturnTransition(transform);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.show_three_details, container, false);
view.findViewById(R.id.tvSutra).setTransitionName(word.getMSutras());
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
sutraTV = view.findViewById(R.id.tvSutra);
adhyayTV = view.findViewById(R.id.tVAdhyay);
padaTv = view.findViewById(R.id.tVPada);
sutraIdTV = view.findViewById(R.id.tVSutraId);
vrittiTV = view.findViewById(R.id.tvVritti);
fabBtn = view.findViewById(R.id.favFAB);
coordinatorLayout = view.findViewById(R.id.parentCordlayout);
bottomAppBar = view.findViewById(R.id.bottom_app_bar);
bundleCheckWithDb();
WordCheck();
}
private void bundleCheckWithDb() {
//*********** Geting Parcelable Data
word = new Astadhyayi(Parcel.obtain());
Bundle bundle = this.getArguments();
if (bundle != null) {
word = bundle.getParcelable("allData");
trans = bundle.getString("transition_name");
adhyayTV.setText(word.getMAdhyay());
padaTv.setText(word.getMPada());
sutraIdTV.setText(word.getMSutra_id());
sutraTV.setText(word.getMSutras());
vrittiTV.setText(word.getMVritti());
}
//*********** DATABASE OPENING
db = DictionaryDB.getInstance(this.getActivity());
}
private void WordCheck() {
if (word.mStatus != null && word.mStatus.equals(DictionaryDB.BOOKMARKED)) {
fabBtn.setImageResource(R.drawable.cards_heart);
} else {
fabBtn.setImageResource(R.drawable.cards_heart_white);
}
fabBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
bookMarkWord(word, fabBtn);
}
});
}
}
Error im getting
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.sanskrit.mysearcher.models.Astadhyayi.getMSutras()' on a null object reference
at com.sanskrit.mysearcher.fragments.TermThreeDetailsFragment.onCreateView(TermThreeDetailsFragment.java:69)
From the current given information, I think you should do something like this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
word = new Astadhyayi(Parcel.obtain());
Bundle bundle = this.getArguments();
if (bundle != null) {
word = bundle.getParcelable("allData");
}
View view = inflater.inflate(R.layout.show_three_details, container, false);
view.findViewById(R.id.tvSutra).setTransitionName(word.getMSutras());
return view;
}
Again, I am not sure what getMSutras() actually returns and if it's right to use that here.
I’ve been having difficulties sending data from one fragment to another when utilizing a TabLayout. I’ve read copious amounts of online posts pertaining to how to do this and have had no success when implementing them myself.
I have four fragments set up in my application. I'm trying to send data gathered from an EditText element in the fourth fragment to the TextView element of the second fragment.
I don't get any errors, but the text does not show up in the second fragment. I don't know how to proceed from here. Thanks!
Fourth Fragment (sending Fragment)
public class settings extends Fragment {
SendMessage SM;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.setl, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Button btnPassData = (Button) view.findViewById(R.id.btnPassData);
final EditText inData = (EditText) view.findViewById(R.id.inMessage);
btnPassData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SM.sendData(inData.getText().toString().trim());
}
});
}
public interface SendMessage {
void sendData(String message);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
SM = (SendMessage) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException("Error in retrieving data. Please try again");
}
}
}
Second Fragment (receiving fragment)
public class tt extends Fragment {
TextView txtData;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.ttl, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
txtData = (TextView)view.findViewById(R.id.txtData);
}
public void displayReceivedData(String message) {
txtData.setText("Data received: "+ message);
}
}
Main Activity
public class MainActivity extends AppCompatActivity implements settings.SendMessage {
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_test);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
}
#Override
public void sendData(String message) {
String tag = "android:switcher:" + R.id.view_pager + ":" + 1;
tt f = (tt) getSupportFragmentManager().findFragmentByTag(tag);
f.displayReceivedData(message);
}
}
Something might be breaking in other part of your app.
Below is code of your working example.
class MainActivity
public class MainActivity extends AppCompatActivity implements Setting.SendMessage {
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(),this );
ViewPager viewPager = findViewById(R.id.viewpager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.sliding_tabs);
tabs.setupWithViewPager(viewPager);
}
#Override
public void sendData(String message) {
String tag = "android:switcher:" + R.id.viewpager + ":" + 1;
tt f = (tt) getSupportFragmentManager().findFragmentByTag(tag);
f.displayReceivedData(message);
}
}
class Setting
public class Setting extends Fragment {
SendMessage SM;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.setl, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Button btnPassData = (Button) view.findViewById(R.id.btnPassData);
final EditText inData = (EditText) view.findViewById(R.id.inMessage);
btnPassData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SM.sendData(inData.getText().toString().trim());
}
});
}
public interface SendMessage {
void sendData(String message);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
SM = (SendMessage) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException("Error in retrieving data. Please try again");
}
}
}
class tt
public class tt extends Fragment {
TextView txtData;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.tt, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
txtData = (TextView)view.findViewById(R.id.txtData);
}
public void displayReceivedData(String message) {
txtData.setText("Data received: "+ message);
}
}
class SectionsPagerAdapter
public class SectionsPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 2;
private String tabTitles[] = new String[] { "Tab1", "Tab2"};
private Context context;
public SectionsPagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
if(position==0){
return new Setting();
}
else
return new tt();
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
}
how can i implement a onRefreshListener in fragments if i am using ViewPager (ViewPager 2) with FragmentStateAdapter.
I found only examples with FragmentPageAdapter.
the other code works so far, i mean swiping between fragments an displaying a list of strings.
Just the refresh (pull from top to bottom) don't work.
I just see the refresh symbol short and then it dissapears.
In the debugger the onRefresh functions will not be called, after a refresh action.
This is my Code:
main activity
viewPager = findViewById(R.id.view_pager);
tabLayout = findViewById(R.id.tabs);
viewPager.setAdapter(new ViewPagerAdapter(this, dataManager));
new TabLayoutMediator(tabLayout, viewPager,
new TabLayoutMediator.TabConfigurationStrategy() {
#Override public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
tab.setText("Tab " + (position + 1));
}
}).attach();
viewpager
public class ViewPagerAdapter extends FragmentStateAdapter {
private static final int CARD_ITEM_SIZE = 3;
private DataManager dataManager;
public ViewPagerAdapter(#NonNull FragmentActivity fragmentActivity, DataManager dataManager) {
super(fragmentActivity);
this.dataManager = dataManager;
}
#NonNull #Override public Fragment createFragment(int position) {
Fragment fragment = null;
if (position == 0)
{
fragment = new FragmentA();
Bundle bundle = new Bundle(2);
bundle.putString("TOKEN", dataManager.getToken());
bundle.putString("SERVER_URL", dataManager.getServerURL());
fragment.setArguments(bundle);
}
else if (position == 1)
{
fragment = new FragmentB();
}
else if (position == 2)
{
fragment = new FragmentC();
}
return fragment;
}
#Override public int getItemCount() {
return CARD_ITEM_SIZE;
}
fragment
public class FragmentA extends Fragment implements SwipeRefreshLayout.OnRefreshListener{
private RecyclerView recyclerView;
private SwipeRefreshLayout swipeLayout;
private Bundle bundle;
private ListView mainListView;
private LibrariesAdapter listAdapter;
private LibraryDataManager libraryDataManager;
private RecyclerViewAdapter adapter;
private GetLibrariesTask getLibrariesTask;
private String token;
private String serverUrl;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bundle = getArguments();
if (bundle != null) {
token = bundle.getString("TOKEN");
serverUrl = bundle.getString("SERVER_URL");
libraryDataManager = new LibraryDataManager(token, serverUrl);
} else {
// ToDo show error or something else
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment, container, false);
swipeLayout = rootView.findViewById(R.id.swiperefresh);
getLibrariesTask = new GetLibrariesTask();
getLibrariesTask.execute();
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mainListView = view.findViewById(android.R.id.list);
ArrayList<Library> librariesList = new ArrayList<>();
listAdapter = new LibrariesAdapter(getActivity(), librariesList);
mainListView.setAdapter(listAdapter);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getLibrariesTask = new GetLibrariesTask();
getLibrariesTask.execute();
}
});
}
private class GetLibrariesTask extends AsyncTask<Void, Void, List<Library>> {
#Override
protected List<Library> doInBackground(Void... args) {
List<Library> libraries = libraryDataManager.getLibraries();
return libraries;
}
#Override
protected void onPostExecute(List<Library> libraries) {
listAdapter.clear();
listAdapter.addAll(libraries);
listAdapter.notifyDataSetChanged();
Logger.debug("on refresh2");
// swipeLayout.setRefreshing(false);
}
}
}
Im trying to pass string data together with images.
Why when running this code I get only image 'nature4' shown but there is no 'nature2' image and strings 'Fragment1' etc..
public class MainActivity extends AppCompatActivity {
private ViewPager viewPager;
private ArrayList<String> strs;
private FragmentPagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("x","onCreateActivity");
strs = new ArrayList<String>();
strs.add("Fragment 1");
strs.add("Fragment 2");
strs.add("Fragment 3");
strs.add("Fragment 4");
strs.add("Fragment 5");
viewPager = (ViewPager) findViewById(R.id.pager);
adapter = new FragmentPagerAdapter(getSupportFragmentManager(), strs);
viewPager.setAdapter(adapter);
}
public class FragmentPagerAdapter extends FragmentStatePagerAdapter {
private ArrayList<String> itemData;
public FragmentPagerAdapter(FragmentManager fm, ArrayList<String> itemData) {
super(fm);
this.itemData = itemData;
}
#Override
public int getCount()
{
return itemData.size();
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
Log.i("x","destroyItem");
}
#Override
public Fragment getItem(int position){
Log.i("x","getItem");
// pass data to fragment
Fragment1 f = Fragment1.newInstance(itemData.get(position));
return f;
}
}
}
And Fragment.class
public class Fragment1 extends Fragment {
public Fragment1(){}
String stringValue;
private int [] images = {R.drawable.nature2,R.drawable.nature4};
public static Fragment1 newInstance(String str)
{
Fragment1 slider=new Fragment1();
Bundle b=new Bundle();
b.putString("stringValue", str);
slider.setArguments(b);
return slider;
}
TextView textView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.i("x","onCreateViewFragment");
View view = inflater.inflate(R.layout.fragment1, container, false);
textView = (TextView) view.findViewById(R.id.textView);
ImageView photo = (ImageView) view.findViewById(image);
photo.setImageResource(images[1]);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
Log.i("x","onActivityCreatedFragment");
super.onActivityCreated(savedInstanceState);
stringValue = getArguments().getString("stringValue");
textView.setText(stringValue);
}
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i("x","onCreateFragment");
super.onCreate(savedInstanceState);
}
}
I think you need to make your question clear. If you want to pass String stringValue and in imageResId from Activity to Fragment, try the following codes.
public static Fragment1 newInstance(String str, int imageResId) {
Fragment1 slider = new Fragment1();
Bundle b=new Bundle();
b.putString("stringValue", str);
b.putInt("image_resid", imageResId);
slider.setArguments(b);
return slider;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
stringValue = getArguments().getString("stringValue");
imageResId = getArguments().getIn("image_resid");
}
FragmentPagerAdapter:
public class FragmentPagerAdapter extends FragmentStatePagerAdapter {
...
#Override
public Fragment getItem(int position){
Fragment fragment;
String str = itemData.get(position);
int resId;
if (position == 0) {
resId = R.drawable.nature2;
} else if (position == 1) {
resId = R.drawable.nature4;
}
fragment = Fragment1.newInstance(str, resId);
...
return fragment;
}
}
Currently I have a tab host activity that contains SherlockFragment. In one of these tabs (Fragments), I want to implement a ViewPager that will show images (ImageView). I created a FragmentPagerAdapter and Fragment to add it in the ViewPager. But when I run the application, my ViewPager appears empty with no image in it.
Here are my classes:
BonusFragment.Java
public class BonusFragment extends SherlockFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getImages(); //Here I get the images for the viewpager
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
return null;
}
View view = inflater.inflate(R.layout.bonus_frag, container, false);
viewPager = (ViewPager) view.findViewById(R.id.pagr);
Q.ADAPTER = new BonusPagerAdapter(getActivity()
.getSupportFragmentManager(), myImagesList);
viewPager.setAdapter(Q.ADAPTER);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
BonusPagerAdapter.Java
private ArrayList<Bitmap> items;
public BonusPagerAdapter(FragmentManager fm, ArrayList<Bitmap> items) {
super(fm);
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Fragment getItem(int position) {
Bitmap bitmap = items.get(position);
BonusImageFragment fragment = BonusImageFragment.newInstance("Glass 1");
fragment.setBitmap(bitmap);
return fragment;
}
#Override
public int getItemPosition(Object object) {
return PagerAdapter.POSITION_NONE;
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
}
BonusImageFragment.Java
public class BonusImageFragment extends SherlockFragment {
private Bitmap bitmap;
public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
private static String frag = "";
public BonusImageFragment() {
}
public static final BonusImageFragment newInstance(String message)
{
frag = message;
BonusImageFragment f = new BonusImageFragment();
Bundle bdl = new Bundle(1);
bdl.putString(EXTRA_MESSAGE, message);
f.setArguments(bdl);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.glass_item, container, false);
ImageView image = (ImageView) v.findViewById(R.id.glass_view);
image.setImageBitmap(bitmap);
return v;
}
public Bitmap getBitmap() {
return bitmap;
}
public void setBitmap(Bitmap bitmap) {
this.bitmap = bitmap;
}
}
Now why does my ViewPager always appears empty?
Fixed it... I had to change "getActivity().getSupportFragmentManager()" in "BonusFragment.Java" with "getChildFragmentManager()"