Android Tabs with same Fragment - java

I'm trying to implement Tabs. The Tabs will contain the exact same layout and the same fragment with only one difference - the API URL! (e.g. Trending/Newest).
My Code:
TabFragment
public class TabFragments extends Fragment implements OnPageChangeListener,
OnTabChangeListener {
private TabHost tabHost;
private int currentTab = 0;
private ViewPager viewPager;
private TabFragmentPageAdapter pageAdapter;
private List<Fragment> fragments;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tabhost, null);
tabHost = (TabHost) rootView.findViewById(android.R.id.tabhost);
viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
viewPager.setOnPageChangeListener(this);
//Create correct fragment
fragments=new ArrayList<>();
fragments.add(new ItemStreamFragment());
fragments.add(new ItemStreamFragment());
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
pageAdapter = new TabFragmentPageAdapter(getChildFragmentManager(),
fragments);
pageAdapter.notifyDataSetChanged();
viewPager.setAdapter(pageAdapter);
setupTabs();
}
private void setupTabs() {
tabHost.setup();
tabHost.addTab(newTab(R.string.tab_1_item));
tabHost.addTab(newTab(R.string.tab_2_item));
for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
tabHost.getTabWidget().getChildAt(i)
.setBackgroundColor(Color.parseColor("#304c58"));
// tabHost.setBackgroundResource(R.drawable.tab_selector);
final View view = tabHost.getTabWidget().getChildTabViewAt(i);
final View textView = view.findViewById(android.R.id.title);
((TextView) textView).setTextColor(Color.parseColor("#e2ebf0"));
((TextView) textView).setSingleLine(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
tabHost.getTabWidget().getChildAt(i)
.findViewById(android.R.id.icon);
tabHost.getTabWidget().getChildAt(i).getLayoutParams().height = 75;
} else {
if (view != null) {
// reduce height of the tab
view.getLayoutParams().height *= 0.77;
if (textView instanceof TextView) {
((TextView) textView).setGravity(Gravity.CENTER);
textView.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT;
textView.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT;
}
}
}
}
tabHost.setOnTabChangedListener(TabFragments.this);
tabHost.setCurrentTab(currentTab);
}
private TabSpec newTab(int titleId) {
TabSpec tabSpec = tabHost.newTabSpec(getString(titleId));
tabSpec.setIndicator(getString(titleId));
tabSpec.setContent(new TabFactory(getActivity()));
return tabSpec;
}
#Override
public void onPageScrollStateChanged(int position) {
}
#Override
public void onPageScrolled(int position, float arg1, int arg2) {
}
#Override
public void onPageSelected(int position) {
tabHost.setCurrentTab(position);
}
#Override
public void onTabChanged(String tabId) {
currentTab = tabHost.getCurrentTab();
viewPager.setCurrentItem(currentTab);
}
#SuppressWarnings("unused")
private void updateTab() {
switch (currentTab) {
case 0:
ItemStreamFragment login = (ItemStreamFragment) fragments.get(currentTab);
break;
case 1:
ItemStreamFragment register = (ItemStreamFragment) fragments
.get(currentTab);
break;
}
}
class TabFactory implements TabContentFactory {
private final Context context;
public TabFactory(Context context) {
this.context = context;
}
#Override
public View createTabContent(String tag) {
View v = new View(context);
v.setMinimumHeight(0);
v.setMinimumWidth(0);
return v;
}
}
}
TabFragmentPageAdapter
public class TabFragmentPageAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public TabFragmentPageAdapter(FragmentManager fm, List<Fragment> fragments
) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = fragments.get(position);
Bundle args = new Bundle();
args.putInt("position", position);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
And finally ItemStreamFragment
public class ItemStreamFragment extends Fragment {
private String mApiUrl = "http://api.eese.com:8080/ICDS_API/v1/reco.getNewest/?page=0&limit=13&timestamp=2015-07-02+10%3A34%3A07&lang_key=en";
private final String mImages = "http://d30q95ofpjr96w.cloudfront.net/";
private ItemStream[] mObjectItem;
private int mPosition = 0;
public ItemStreamAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
if (bundle != null) {
mPosition = bundle.getInt("position", 0);
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_itemstream, container, false);
view.setId(mPosition);
getStream(mPosition);
return view;
}
private void getStream(int position) {
switchUrl(position);
new GetRequestTask(new OnTaskCompleted() {
#Override
public void onTaskCompleted(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonResults = jsonObject.getJSONArray("results");
final int resultLength = jsonResults.length();
mObjectItem = new ItemStream[resultLength];
for (int i = 0; i < resultLength; i++) {
JSONObject item = jsonResults.getJSONObject(i);
mObjectItem[i] = new ItemStream(item.getInt("id"), item.getString("title"), mImages + "" + item.getString("thumbnail") + ".374x210." + item.getString("thumbnail_type"));
}
if (getActivity() != null) {
mAdapter = new ItemStreamAdapter(getActivity(), R.layout.list_itemstream, mObjectItem);
ListView scrollView = (ListView) getActivity().findViewById(R.id.itemstream_trend);
scrollView.setAdapter(mAdapter);
}
} catch (Exception ex) {
}
}
}).execute(mApiUrl);
}
//Needs to be tuned
private void switchUrl(int position) {
switch (position) {
case 0:
mApiUrl = "http://api.eese.com:8080/ICDS_API/v1/reco.getTrending/?page=0&limit=13&timestamp=2015-07-02+10%3A34%3A07&lang_key=en";
break;
case 1:
mApiUrl = "http://api.eese.com:8080/ICDS_API/v1/reco.getNewest/?page=0&limit=13&timestamp=2015-07-02+10%3A34%3A07&lang_key=en";
break;
}
}
}
And here you see what happens:
(Sry for the overlay :) )
The thing is that the first Tab is loaded with data but the second tab stays empty (it shouldn't be empty though). Not sure what is wrong here. Would be cool if you can point me in the right direction :)

For using Tabs in material design you should use TabLayout from design support library. Here is the tutorial from where you can learn this new approach.
As far as loading fragment is concern, you second fragment will be loaded with first this is complete different discussion with viewpager, so you need to have different url for each fragment and don't create fragment using new Operator. Instead create static getInstance() in Fragment class and pass the url from there and using Fragment#setArgument(Bundle) get new Fragment instance. When fragment view is created i.e in onViewCreated(...) get arguments from bundle in your case String url and call webservice which will return the respective response.

Fixed the problem:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_itemstream, container, false);
view.setId(mPosition);
getStream(mPosition,view);
return view;
}
private void getStream(int position, final View view) {
switchUrl(position);
new GetRequestTask(new OnTaskCompleted() {
#Override
public void onTaskCompleted(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonResults = jsonObject.getJSONArray("results");
final int resultLength = jsonResults.length();
mObjectItem = new ItemStream[resultLength];
for (int i = 0; i < resultLength; i++) {
JSONObject item = jsonResults.getJSONObject(i);
mObjectItem[i] = new ItemStream(item.getInt("id"), item.getString("title"), mImages + "" + item.getString("thumbnail") + ".374x210." + item.getString("thumbnail_type"));
}
if (getActivity() != null) {
mAdapter = new ItemStreamAdapter(getActivity(), R.layout.list_itemstream, mObjectItem);
ListView scrollView = (ListView) view.findViewById(R.id.itemstream_trend);
scrollView.setAdapter(mAdapter);
}
} catch (Exception ex) {
}
}
}).execute(mApiUrl);
}
Just added view to the method getStream. Now it is working! What do you think about this solution?

Related

My ViewPager Fragment data of recyclerview and layout disappear after coming back from a fragment

I'm getting the object from modelView as you guys see.
Every thing is perfectly working apart from my viewpager fragment when I first come to my pager fragment it shows data when I go through forward and then come backward it disappears my data and my layout structure.
My viewModel have data always have a data but my recyclerview is not showing it.
BrandFragment is a base fragment having viewpager in it.
BrandFragment :
public class BrandFragment extends Fragment {
#BindView(R.id.brandtablayout)
TabLayout brandtablayout;
#BindView(R.id.brandpager)
ViewPager brandpager;
#BindView(R.id.backgroundImage)
ImageView backgroundImage;
#BindView(R.id.brandIcon)
CircleImageView brandIcon;
#BindView(R.id.brandName)
TextView brandName;
#BindView(R.id.brandTagLine)
TextView brandTagLine;
#BindView(R.id.brandRatingBar)
RatingBar brandRatingBar;
#BindView(R.id.noInternet)
ImageView noInternet;
private Brand brand;
int chipId;
private KProgressHUD mProgressBar;
private ShareViewModel shareViewModel;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_brand, container, false);
brandpager = view.findViewById(R.id.brandpager);
brandtablayout = view.findViewById(R.id.brandtablayout);
backgroundImage = view.findViewById(R.id.backgroundImage);
brandIcon = view.findViewById(R.id.brandIcon);
brandName = view.findViewById(R.id.brandName);
brandTagLine= view.findViewById(R.id.brandTagLine);
brandRatingBar = view.findViewById(R.id.brandRatingBar);
noInternet = view.findViewById(R.id.noInternet);
brandtablayout.addTab(brandtablayout.newTab().setText("Product"));
brandtablayout.addTab(brandtablayout.newTab().setText("Profile"));
brandtablayout.setTabGravity(TabLayout.GRAVITY_FILL);
BrandProfileViewPagerAdapter brandProfileAdapter = new BrandProfileViewPagerAdapter(getFragmentManager(), brandtablayout.getTabCount());
brandpager.setAdapter(brandProfileAdapter);
brandtablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
brandpager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
progressbar("Getting Brand Detail","Please wait...");
return view;
}
private void getBrandDetails() {
WebServiceFactory.getInstance().getBrandDetails(chipId).enqueue(new Callback<Brand>() {
#Override
public void onResponse(Call<Brand> call, Response<Brand> response) {
if (response.body().getFlag() == 1) {
brand = response.body();
shareViewModel.setBrandProductsMutableLiveData(brand.getBrandProducts());
shareViewModel.setBrandSpecificationsMutableLiveData(brand.getBrandSpecifications());
brandProfileDetails();
mProgressBar.dismiss();
}else {
mProgressBar.dismiss();
}
}
#Override
public void onFailure(Call<Brand> call, Throwable t) {
mProgressBar.dismiss();
}
});
}
private void brandProfileDetails(){
if (brand.getBrandSpecifications() != null){
brandRatingBar.setRating(brand.getBrandSpecifications().getBrandRates());
brandName.setText(brand.getBrandSpecifications().getBrandName());
Picasso.get().load(AppConstants.imagePath(brand.getBrandSpecifications().getBrandBg())).into(backgroundImage);
brandTagLine.setText(brand.getBrandSpecifications().getBrandSlogan());
Picasso.get().load(AppConstants.imagePath(brand.getBrandSpecifications().getBrandIcon())).into(brandIcon);
}
mProgressBar.dismiss();
}
#Override
public void onViewCreated (#NonNull View view, #Nullable Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
shareViewModel = ViewModelProviders.of((FragmentActivity) requireActivity()).get(ShareViewModel.class);
shareViewModel.getChipId().observe(getViewLifecycleOwner(), new Observer<Integer>() {
#Override
public void onChanged(Integer id) {
chipId =id;
if (InternetConnection.checkConnection(getContext())) {
// Internet Available...
noInternet.setVisibility(View.GONE);
getBrandDetails();
} else {
noInternet.setVisibility(View.VISIBLE);
mProgressBar.dismiss();
Toast.makeText(getContext(), "Check your internet Connection", Toast.LENGTH_SHORT).show();
// Internet Not Available...
}
}
});
}
private void progressbar(String title, String detail){
mProgressBar = KProgressHUD.create(getContext())
.setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
.setLabel(title)
.setDetailsLabel(detail)
.setCancellable(false)
.setAnimationSpeed(2)
.setDimAmount(0.5f)
.show();
}
}
BrandProductFragment :
public class BrandProductFragment extends Fragment implements RecyclerviewOnClickInterface, CategoryRecyclerviewInterface, ChipsInterface, MyButtonClickListener {
int tabCount;
#BindView(R.id.brandPopularProduct)
TextView brandPopularProduct;
#BindView(R.id.brandNewProduct)
TextView brnadNewProduct;
#BindView(R.id.brandHighestProduct)
TextView brandHighestProduct;
#BindView(R.id.brandLowestProduct)
TextView brandLowestProduct;
#BindView(R.id.brandProductRecyclerview)
RecyclerView brandProductRecyclerview;
BrandProfilePopularAdapter brandProfilePopularAdapter;
BrandNewReleaseAdapter brandNewReleaseAdapter;
BrandProductHighestAdapter brandProductHighestAdapter;
BrandLowestAdapter brandLowestAdapter;
BrandProducts brandProductData;
ShareViewModel shareViewModel;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_brand_product, container, false);
tabCount = 0;
brandPopularProduct = view.findViewById(R.id.brandPopularProduct);
brnadNewProduct = view.findViewById(R.id.brandNewProduct);
brandHighestProduct = view.findViewById(R.id.brandHighestProduct);
brandLowestProduct = view.findViewById(R.id.brandLowestProduct);
brandProductRecyclerview = view.findViewById(R.id.brandProductRecyclerview);
buttonOnClick();
return view;
}
private void buttonOnClick() {
brandPopularProduct.setOnClickListener(v -> {
tabCount = 1;
tabSelector();
if (brandProductData != null) {
getBrandProductPopular(brandProductData);
}
});
brnadNewProduct.setOnClickListener(v -> {
tabCount = 2;
tabSelector();
if (brandProductData != null) {
getBrandProductNewRelease();
}
});
brandHighestProduct.setOnClickListener(v -> {
tabCount = 3;
tabSelector();
if (brandProductData != null) {
getBrandProductHighest();
}
});
brandLowestProduct.setOnClickListener(v -> {
tabCount = 4;
tabSelector();
if (brandProductData != null) {
getBrandProductLowest();
}
});
}
private void tabSelector() {
if (tabCount == 1) {
brandPopularProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor));
brandPopularProduct.setTextSize(20);
brnadNewProduct.setTextSize(18);
brandLowestProduct.setTextSize(18);
brandHighestProduct.setTextSize(18);
brnadNewProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
brandHighestProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
brandLowestProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
} else if (tabCount == 2) {
brnadNewProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor));
brandPopularProduct.setTextSize(18);
brnadNewProduct.setTextSize(20);
brandLowestProduct.setTextSize(18);
brandHighestProduct.setTextSize(18);
brandPopularProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
brandHighestProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
brandLowestProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
} else if (tabCount == 3) {
brandHighestProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor));
brandPopularProduct.setTextSize(18);
brnadNewProduct.setTextSize(18);
brandLowestProduct.setTextSize(18);
brandHighestProduct.setTextSize(20);
brnadNewProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
brandPopularProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
brandLowestProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
} else if (tabCount == 4) {
brandLowestProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor));
brandPopularProduct.setTextSize(18);
brnadNewProduct.setTextSize(18);
brandLowestProduct.setTextSize(20);
brandHighestProduct.setTextSize(18);
brnadNewProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
brandHighestProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
brandPopularProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
}
}
private void getBrandProductPopular(BrandProducts brandProductData) {
if (brandProductData.getPOPULARPRODUCTS() != null){
brandProfilePopularAdapter = new BrandProfilePopularAdapter(getContext(), brandProductData.getPOPULARPRODUCTS(), this);
GridLayoutManager mLayoutManager = new GridLayoutManager(getContext(), 2);
brandProductRecyclerview.setLayoutManager(mLayoutManager);
brandProductRecyclerview.setAdapter(brandProfilePopularAdapter);
recyclerviewAnimation(brandProductRecyclerview);
}
}
private void getBrandProductNewRelease() {
if ( brandProductData.getNEWRELEASEPRODUCTS() != null){
brandNewReleaseAdapter = new BrandNewReleaseAdapter(getContext(), brandProductData.getNEWRELEASEPRODUCTS(), this);
GridLayoutManager mLayoutManager = new GridLayoutManager(getContext(), 2);
brandProductRecyclerview.setLayoutManager(mLayoutManager);
brandProductRecyclerview.setAdapter(brandNewReleaseAdapter);
recyclerviewAnimation(brandProductRecyclerview);
}
}
private void getBrandProductHighest() {
if (brandProductData.getHIGHESTPRODUCTS() != null){
brandProductHighestAdapter = new BrandProductHighestAdapter(getContext(), brandProductData.getHIGHESTPRODUCTS(), this);
GridLayoutManager mLayoutManager = new GridLayoutManager(getContext(), 2);
brandProductRecyclerview.setLayoutManager(mLayoutManager);
brandProductRecyclerview.setAdapter(brandProductHighestAdapter);
recyclerviewAnimation(brandProductRecyclerview);
}
}
private void getBrandProductLowest() {
if ( brandProductData.getLOWESTPRODUCTS() != null){
brandLowestAdapter = new BrandLowestAdapter(getContext(), brandProductData.getLOWESTPRODUCTS(), this);
GridLayoutManager mLayoutManager = new GridLayoutManager(getContext(), 2);
brandProductRecyclerview.setLayoutManager(mLayoutManager);
brandProductRecyclerview.setAdapter(brandLowestAdapter);
recyclerviewAnimation(brandProductRecyclerview);
}
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
shareViewModel = ViewModelProviders.of((FragmentActivity) getContext()).get(ShareViewModel.class);
shareViewModel.getBrandProduct().observe(getViewLifecycleOwner(), new Observer<BrandProducts>() {
#Override
public void onChanged(BrandProducts brandProducts) {
Log.e("getBrands", brandProducts.toString());
brandProductData = brandProducts;
getBrandProductPopular(brandProductData);
}
});
}
private void recyclerviewAnimation(RecyclerView recyclerView) {
Context context = recyclerView.getContext();
LayoutAnimationController layoutAnimationController = AnimationUtils.loadLayoutAnimation(context, R.anim.layout_animation_fall_down);
recyclerView.setLayoutAnimation(layoutAnimationController);
recyclerView.getAdapter().notifyDataSetChanged();
recyclerView.scheduleLayoutAnimation();
}
int productId;
#Override
public void onItemClick(int position) {
shareViewModel.setProductIdMutable(brandProductData.getPOPULARPRODUCTS().get(position).getProductId());
fragmentTransaction();
}
#Override
public void onItemClickCategory(int position) {
shareViewModel.setProductIdMutable(brandProductData.getNEWRELEASEPRODUCTS().get(position).getProductId());
fragmentTransaction();
}
#Override
public void onChipItemClick(int position) {
shareViewModel.setProductIdMutable(brandProductData.getHIGHESTPRODUCTS().get(position).getProductId());
fragmentTransaction();
}
#Override
public void onclick(int position) {
shareViewModel.setProductIdMutable(brandProductData.getLOWESTPRODUCTS().get(position).getProductId());
fragmentTransaction();
}
private void fragmentTransaction() {
Bundle bundle = new Bundle();
bundle.putString("BrandProduct", "brand");
PreviewProductFragment previewProductFragment = new PreviewProductFragment();
previewProductFragment.setArguments(bundle);
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction().addToBackStack("");
fragmentTransaction.setCustomAnimations(R.anim.enter_right_to_left, R.anim.exit_right_to_left);
fragmentTransaction.replace(R.id.tabbed_framelayout, previewProductFragment);
fragmentTransaction.commit();
}
}
BrandProfileViewPagerAdapter this is my viewPager Adapter :
public class BrandProfileViewPagerAdapter extends FragmentStatePagerAdapter {
private int tabCount;
public BrandProfileViewPagerAdapter(#NonNull FragmentManager fm, int tabs) {
super(fm, tabs);
this.tabCount=tabs;
}
#NonNull
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
BrandProductFragment brandProductFragment = new BrandProductFragment();
return brandProductFragment;
case 1:
BrandProfileFragment brandProfileFragment= new BrandProfileFragment();
return brandProfileFragment;
default:
return null;
}
}
#Override
public int getCount() {
return tabCount;
}
}
Before :
After :

empty recycler view in Fragment

I have an activity that contains 2 fragments
in TriFragment.java the user entres an input and click the button Sortto sort the numbers , the input entred will be sent to the second fragment StepsFragmentto display mystepsList in a Recyclerview.
i have cheked and found that mystepsListis empty even before the user enters the data (on creating the activity) so the recyclerview is not showing anything
mainactivity
public class Sorting_activity extends AppCompatActivity implements StepsFragment.OnFragmentInteractionListener,TriFragment.TriFragmentListner{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sorting_activity);
TriFragment tri = new TriFragment();
FragmentManager manager=getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.triLayout,tri ,tri.getTag())
.commit();
StepsFragment steps= new StepsFragment();
manager.beginTransaction()
.replace(R.id.stepsLayout,steps ,steps.getTag())
.commit();
}
#Override
public void onFragmentInteraction(Uri uri) { }
#Override
public void onInputsent(String input) {
StepsFragment.setTextView(input);
}
}
StepsFragment
public class StepsFragment extends Fragment {
private OnFragmentInteractionListener mListener;
private static TextView inputEntred ;
private RecyclerView RV ;
private Handler mhandler = new Handler();
public StepsFragment() {
// Required empty public constructor
}
public static void setTextView(String textentered){
inputEntred.setText(textentered);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.fragment_steps, container, false);
inputEntred =view.findViewById(R.id.inputEntred);
String[] numberList = inputEntred.getText().toString().split(",");
final Integer[] numbers = new Integer[numberList.length];
if(numberList.length !=0){
// converting the strig array to an array of integers
for (int i = 0; i < numberList.length; i++) {
try {
numbers[i] = Integer.parseInt(numberList[i]);
}
catch (NumberFormatException e){
System.out.println("error is"+e);
}
}
SelectionSort m1 = new SelectionSort();
ArrayList<String> mystepsList = m1.steps(numbers);// returns the steps numbers
if(mystepsList.isEmpty()){
System.out.println("empty list");
}else {
for (int i = 0; i < mystepsList.size(); i++)
{
System.out.println(mystepsList.get(i));
}
}
RV =view.findViewById(R.id.RV);
final StepListAdapter adapter = new StepListAdapter() ;
RV.setAdapter(adapter);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
RV.setLayoutManager(llm);
adapter.setList(mystepsList);
}
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
// mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
adapter
public class StepListAdapter extends RecyclerView.Adapter<StepListAdapter.StepListHolder> {
private ArrayList<String> etapes_list = new ArrayList<String>();
#NonNull
#Override
public StepListHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new StepListHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.log_item,parent,false));
}
#Override
public void onBindViewHolder(#NonNull StepListHolder holder, int position) {
holder.etapes.setText(etapes_list.get(holder.getAdapterPosition()));
}
#Override
public int getItemCount() {
return etapes_list.size();
}
public void setList(ArrayList<String> etapes_list ){
this.etapes_list= etapes_list;
notifyDataSetChanged();
}
#Override
public long getItemId(int position) {
return (null != etapes_list ? etapes_list.size() : 0);
}
public class StepListHolder extends RecyclerView.ViewHolder {
TextView etapes ;
public StepListHolder(#NonNull View itemView) {
super(itemView);
etapes =itemView.findViewById(R.id.txt_log);
}
}
}
Because you see you are setting a recyclerView in onCreateView method of Stepsfragment, this means your computation is done when fragment is created and not when you actully press the sort button.
modify your fragment this way and your recyclerView will works fine.
package com.example;
public class StepsFragment extends Fragment {
private OnFragmentInteractionListener mListener;
private static TextView inputEntred ;
private RecyclerView RV ;
private Handler mhandler = new Handler();
public StepsFragment() {
// Required empty public constructor
}
public static void setTextView(String textentered){
inputEntred.setText(textentered);
//Set Your recyclerView Here.
String[] numberList = inputEntred.getText().toString().split(",");
final Integer[] numbers = new Integer[numberList.length];
if(numberList.length !=0){
// converting the strig array to an array of integers
for (int i = 0; i < numberList.length; i++) {
try {
numbers[i] = Integer.parseInt(numberList[i]);
}
catch (NumberFormatException e){
System.out.println("error is"+e);
}
}
SelectionSort m1 = new SelectionSort();
ArrayList<String> mystepsList = m1.steps(numbers);// returns the steps numbers
if(mystepsList.isEmpty()){
System.out.println("empty list");
}else {
for (int i = 0; i < mystepsList.size(); i++)
{
System.out.println(mystepsList.get(i));
}
}
final StepListAdapter adapter = new StepListAdapter() ;
RV.setAdapter(adapter);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
RV.setLayoutManager(llm);
adapter.setList(mystepsList);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.fragment_steps, container, false);
inputEntred =view.findViewById(R.id.inputEntred);
RV =view.findViewById(R.id.RV);
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
// mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
and yes try to avoid making method static for setting data in Fragment.

FragmentStateAdapter onRefreshListener

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);
}
}
}

Move from a fragment with listview adapter to new activity base on each item selected

I have done some series of research about how to make each item of the listview in fragment activity to move to another activity having getView() from swipeListadapter. The codes below contain the tab fragment containing the swipe listadapter for the list view and the setonitemclicklistener.
public class SwipeListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieList;
private String[] bgColors;
public SwipeListAdapter(Activity tab1, List<Movie> movieList) {
this.activity = tab1;
this.movieList = movieList;
bgColors = activity.getApplicationContext().getResources().getStringArray(R.array.movie_serial_bg);
}
#Override
public int getCount() {
return movieList.size();
}
#Override
public Object getItem(int location) {
return movieList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_rows, null);
TextView serial = (TextView) convertView.findViewById(R.id.serial);
TextView title = (TextView) convertView.findViewById(R.id.title);
serial.setText(String.valueOf(movieList.get(position).id));
title.setText(movieList.get(position).title);
String color = bgColors[position % bgColors.length];
serial.setBackgroundColor(Color.parseColor(color));
return convertView;
}
}
The code below is my fragment tab class
public class Tab1 extends Fragment implements ViewSwitcher.ViewFactory, SwipeRefreshLayout.OnRefreshListener {
private int index;
private int[] images = new int[] { R.drawable.gallery1, R.drawable.gallery2, R.drawable.gallery3, R.drawable.gallery4, R.drawable.gallery5, R.drawable.gallery6, R.drawable.gallery7, R.drawable.gallery8 };
ImageSwitcher switcher;
android.os.Handler Handler = new Handler();
private SwipeRefreshLayout swipeRefreshLayout;
private SwipeListAdapter adapter;
private List<Movie> movieList;
private ListView listView;
// private static final String url = "http://api.androidhive.info/json/movies.json";
private String URL_TOP_250 = "http://192.177.53.152/locator/test/refractor.php?offset=";
// initially offset will be 0, later will be updated while parsing the json
private int offSet = 0;
private static final String TAG = Tab1.class.getSimpleName();
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View vi = inflater.inflate(R.layout.tab_1,container,false);
listView = (ListView) vi.findViewById(R.id.list);
listView.setBackgroundColor(Color.WHITE);
swipeRefreshLayout = (SwipeRefreshLayout) vi.findViewById(R.id.swipe_refresh_layout);
movieList = new ArrayList<>();
adapter = new SwipeListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
//getView().setOnClickListener();
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
fetchMovies();
}
}
);
return vi;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
switch(position) {
case 1:
intent = new Intent(getActivity().getApplicationContext(), New1.class);
startActivity(intent);
break;
case 2:
intent = new Intent(getActivity().getApplicationContext(), New2.class);
startActivity(intent);
break;
default:
intent = new Intent(getActivity().getApplicationContext(), New3.class);
startActivity(intent);
}
}
});
switcher = (ImageSwitcher) getActivity().findViewById(R.id.imageSwitcher1);
switcher.setFactory(this);
switcher.setImageResource(images[index]);
switcher.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
index++;
if (index >= images.length) {
index = 0;
}
switcher.setImageResource(images[index]);
}
});
switcher.setInAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_in));
switcher.setOutAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_out));
//auto change image
Handler.post(UpdateImage);
}
#Override
public void onRefresh() {
fetchMovies();
}
private void fetchMovies() {
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(true);
// appending offset to url
String url = URL_TOP_250 + offSet;
// Volley's json array request object
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// looping through json and adding to movies list
for (int i = 0; i < response.length(); i++) {
try {
JSONObject movieObj = response.getJSONObject(i);
int rank = movieObj.getInt("rank");
String title = movieObj.getString("postTitle");
Movie m = new Movie(rank, title);
movieList.add(0, m);
// updating offset value to highest value
if (rank >= offSet)
offSet = rank;
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
adapter.notifyDataSetChanged();
}
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error: " + error.getMessage());
Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
Runnable UpdateImage = new Runnable() {
public void run() {
// Increment index
index++;
if (index > (images.length - 1)) {
index = 0;
}
switcher.setImageResource(images[index]);
// Set the execution after 5 seconds
Handler.postDelayed(this, (3 * 1000));
}
};
#Override
public View makeView() {
ImageView myView = new ImageView(getActivity());
myView.setScaleType(ImageView.ScaleType.FIT_CENTER);
myView.setLayoutParams(new ImageSwitcher.LayoutParams(Gallery.LayoutParams.
FILL_PARENT, Gallery.LayoutParams.FILL_PARENT));
return myView;
}
}
In a nutshell, whenever I click any of the item listview, the app crashes and system logcat is not giving any clue to that. I want to be able to click an item on the listview in d fragment and to be directed to a new activity. Any help will be appreciated. Thanks.

Get a Global Variable passed in main Class to a static Class - Android

I got a code that has a Global Variable and a PageAdapter Static Class. I had look everywhere and didnt find the answer.
I want to get the userG variable, that is in the internal storage to load the tabs. Here is the code:
public class FormActivity extends AppCompatActivity {
ActivityFormPageAdapter mActivityFormPageAdapter;
ViewPager mViewPager;
static String userG;
public void onCreate(Bundle savedInstaceState) {
super.onCreate(savedInstaceState);
setContentView(R.layout.form_access);
mActivityFormPageAdapter = new ActivityFormPageAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pages);
mViewPager.setAdapter(mActivityFormPageAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabsform);
tabLayout.setupWithViewPager(mViewPager);
int i = Color.GRAY;
tabLayout.setSelectedTabIndicatorColor(i);
tabLayout.setSelectedTabIndicatorHeight(6);
}
public String getData(View view) throws IOException {
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
String MODEPROFILE = "mode_profile";
FileInputStream fis = openFileInput(MODEPROFILE);
int c;
String userD = "";
while ((c = fis.read()) != -1) {
userD = userD + Character.toString((char) c);
}
Toast.makeText(getBaseContext(), userG, Toast.LENGTH_LONG).show();
fis.close();
userG = userD;
return userG;
}
public static class ActivityFormPageAdapter extends FragmentStatePagerAdapter {
public ActivityFormPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new FormObjectFragment();
Bundle args = new Bundle();
args.putInt(FormObjectFragment.ARG_OBJECT, i + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "PERSONAL" + userG;
case 1:
return "SERVICES";
case 2:
return "APP ACCESS";
}
return null;
}
public static class FormObjectFragment extends Fragment {
public static final String ARG_OBJECT = "object";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_form, container, false);
Bundle args = getArguments();
String i = Integer.toString(args.getInt(ARG_OBJECT));
if (i == Integer.toString(1)) {
//Toast.makeText(getContext(), , Toast.LENGTH_LONG).show();
rootView.findViewById(R.id.personal).setVisibility(View.VISIBLE);
}
if (i == Integer.toString(2)) {
rootView.findViewById(R.id.services).setVisibility(View.VISIBLE);
}
if (i == Integer.toString(3)) {
rootView.findViewById(R.id.appaccess).setVisibility(View.VISIBLE);
}
/*((TextView) rootView.findViewById(R.id.textform)).setText(Integer.toString(args.getInt(ARG_OBJECT)));*/
return rootView;
}
}
}
}
I'm using (View view) just for testing the internal storage, but always when I call getData() it cames Null. Thats the reason I put in Charsequence the variable, to see if it's coming. But nothing comes. Always Null.
Anyone can help me?

Categories