Bundle value in fragment becomes null - java

I have main activity where I am connecting Api to recycler view. On recycler view item click, I need to open fragment and then use viewpager to slide between pages. My problem is when i click on any item in recview, it always opens the first page. That is because my position that is passed becomes null when fragment is created. Anyone got any solution?
public class ArticleFragment extends Fragment {
private TextView tvTitle, tvDescription;
private ImageView ivSlika;
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private NewsList mNewsList=new NewsList();
private int mPosition;
public ArticleFragment() { }
public static ArticleFragment newInstance(NewsList param1, int param2) {
ArticleFragment fragment = new ArticleFragment();
Bundle args = new Bundle();
args.putSerializable(ARG_PARAM1, param1);
args.putInt(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mNewsList = (NewsList) getArguments().getSerializable(ARG_PARAM1);
mPosition = getArguments().getInt(ARG_PARAM2);
Log.d(TAG, "onCreate: "+ getArguments());
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_article, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
tvTitle=view.findViewById(R.id.tvNaslov);
tvDescription=view.findViewById(R.id.tv_description);
ivSlika=view.findViewById(R.id.iv_article);
//setParameters((NewsList) getArguments().getSerializable(ARG_PARAM1), getArguments().getInt(ARG_PARAM2));
setParameters(mNewsList, mPosition);
}
public void setParameters( NewsList nl, int position){
//nl=new NewsList();
//nl=articleActivity.getMyList();
//List<News> newsList=nl.getNewsList();
/*ArticleActivity articleActivity=(ArticleActivity) getActivity();
position=articleActivity.getPosition();
tvTitle.setText(articleActivity.getMyTitle(position));
tvDescription.setText(articleActivity.getMyDescription(position));
Picasso.get().load(articleActivity.getMyImage(position)).fit().into(ivSlika);*/
tvTitle.setText(nl.getNewsList().get(position).getTitle());
tvDescription.setText(nl.getNewsList().get(position).getDescription());
Picasso.get().load(nl.getNewsList().get(position).getImageUrl()).fit().into(ivSlika);
}
}
public class ArticleActivity extends AppCompatActivity {
private int position;
private NewsList newsList;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_article);
initViews();
newsList= (NewsList)getIntent().getSerializableExtra("List");
position=getIntent().getIntExtra("Position",5);
//getSupportFragmentManager().beginTransaction().add(R.id.viewPager, ArticleFragment.newInstance(newsList, position)).commit();
setUpPager();
}
public String getMyTitle(int position){
return newsList.getNewsList().get(position).getTitle();
}
public String getMyDescription(int position){
return newsList.getNewsList().get(position).getDescription();
}
public String getMyImage(int position){
return newsList.getNewsList().get(position).getImageUrl();
}
private void initViews(){
viewPager= findViewById(R.id.viewPager);
}
private void setUpPager(){
PagerAdapter pagerAdapter=new ScreenSlidePagerAdapter(getSupportFragmentManager(), newsList, position);
viewPager.setAdapter(pagerAdapter);
}
public NewsList getMyList(){
return newsList;
}
public int getPosition() {
return position;
}
}
public class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
private NewsList newsList;
private int mPosition;
private static final int NUM_PAGES =10;
public ScreenSlidePagerAdapter(FragmentManager fragmentManager, NewsList newsList, int position){
super(fragmentManager);
this.newsList=newsList;
this.mPosition=position;
}
public Fragment getItem(int position) {
switch (position){
case 0:
return ArticleFragment.newInstance(newsList, 0);
case 1:
return ArticleFragment.newInstance(newsList, 1);
case 2:
return ArticleFragment.newInstance(newsList, 2);
case 3:
return ArticleFragment.newInstance(newsList, 3);
case 4:
return ArticleFragment.newInstance(newsList, 4);
case 5:
return ArticleFragment.newInstance(newsList, 5);
case 6:
return ArticleFragment.newInstance(newsList, 6);
case 7:
return ArticleFragment.newInstance(newsList, 7);
case 8:
return ArticleFragment.newInstance(newsList, 8);
case 9:
return ArticleFragment.newInstance(newsList, 9);
default:
return ArticleFragment.newInstance(newsList, position);
}
}
#Override
public int getCount() {
return NUM_PAGES;
}
#Override
public int getItemPosition(#NonNull Object object) {
return super.getItemPosition(object);
}
}
public class RecyclerAdapter extends RecyclerView.Adapter<NameViewHolder> {
private List<News> dataList = new ArrayList<>();
private NameClickListener clickListener;
public RecyclerAdapter(NameClickListener clickListener) {
this.clickListener = clickListener;
}
#NonNull
#Override
public NameViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View cellView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row, parent, false);
return new NameViewHolder(cellView, clickListener);
}
#Override
public void onBindViewHolder(#NonNull NameViewHolder holder, int position) {
holder.setName(dataList.get(position));
}
#Override
public int getItemCount() {
return dataList.size();
}
public void addData(List<News> data){
this.dataList.clear();
this.dataList.addAll(data);
notifyDataSetChanged();
}
public void addNewCell(News news, int position){
if(dataList.size() >= position){
dataList.add(position,news);
notifyItemInserted(position);
}
}
}
public class MainActivity extends AppCompatActivity implements NameClickListener{
private Call<Root> apiCall;
private List<News> newsList;
RecyclerAdapter adapter;
RecyclerView recyclerView;
NewsList ListofNews;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpApiCall();
setUpRecycler();
}
private void setUpApiCall(){
apiCall=NetworkUtils.getApiInterface().getNews();
apiCall.enqueue(new Callback<Root>() {
#Override
public void onResponse(Call<Root> call, Response<Root> response) {
if(response.isSuccessful() && response.body()!=null){
/*newsList=new ArrayList<News>();
for(int i=0;i<response.body().articles.size();i++){
newsList.add(response.body().articles.get(i));
}
setData(newsList);
}*/
ListofNews=new NewsList();
ListofNews.setNewsList(response.body().articles);
setData(ListofNews.getNewsList());
}}
#Override
public void onFailure(Call<Root> call, Throwable t) {
AlertDialog alertDialog=new AlertDialog.Builder(MainActivity.this).setTitle("Error").setMessage("Something went wrong").setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
});
}
private void setUpRecycler(){
recyclerView = (RecyclerView) findViewById(R.id.recView);
// Create adapter passing in the sample user data
adapter = new RecyclerAdapter(this);
// Attach the adapter to the recyclerview to populate items
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
private void setData(List<News> newsList){
adapter.addData(newsList);
}
public void onNameClick(int position){
Intent intent=new Intent(MainActivity.this, ArticleActivity.class);
intent.putExtra("List", ListofNews);
intent.putExtra("Position", position);
startActivity(intent);
}}

Related

TabLayout with ViewPager2 is not displaying the corresponding fragments in the ViewPager2 and app freezes

I am trying to display news of different categories under different tabs using TabLayout. The corresponding fragments do not load at all, only the tabs are displayed. The app freezes when I try to scroll or select a tab such that even the tabIndicator barely moves to the corresponding tab and Android displays "Not responding" message.
MainActivity.java
public class MainActivity extends AppCompatActivity{
Toolbar toolbar;
TabLayout tabLayout;
ViewPager2 viewPager2;
NewsPagerAdapter newsPagerAdapter;
TabLayoutMediator tabLayoutMediator;
String[] tabTitles = new String[]{"HOME","BUSINESS","HEALTH","TECHNOLOGY","SPORTS"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.tbCustom);
tabLayout = findViewById(R.id.tlCategories); setSupportActionBar(toolbar);
viewPager2 = findViewById(R.id.vpNews);
newsPagerAdapter = new NewsPagerAdapter(getSupportFragmentManager(),getLifecycle());
viewPager2.setAdapter(newsPagerAdapter);
tabLayoutMediator = new TabLayoutMediator(tabLayout, viewPager2, (tab, position) -> tab.setText(tabTitles[position]));
tabLayoutMediator.attach();
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager2.setCurrentItem(tab.getPosition());
newsPagerAdapter.notifyDataSetChanged();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
tabLayout.selectTab(tabLayout.getTabAt(position));
}
#Override
public void onPageScrollStateChanged(int state) {
super.onPageScrollStateChanged(state);
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
tabLayoutMediator.detach();
viewPager2.setAdapter(null);
}
}
NewsPagerAdapter.java
public class NewsPagerAdapter extends FragmentStateAdapter {
public NewsPagerAdapter(#NonNull FragmentManager fragmentManager, #NonNull Lifecycle lifecycle) {
super(fragmentManager, lifecycle);
}
#NonNull
#Override
public Fragment createFragment(int position) {
switch (position)
{
case 0: return new HomeFragment();
case 1: return new BusinessFragment();
case 2: return new HealthFragment();
case 3: return new TechnologyFragment();
case 4: return new SportsFragment();
default: return null;
}
}
#Override
public int getItemCount() {
return 5;
}
}
Home Fragment.java - Other fragments have the same structure
public class HomeFragment extends Fragment {
#Override
public void onDestroyView() {
super.onDestroyView();
recyclerView.setAdapter(null);
}
#Override
public void onDetach() {
super.onDetach();
}
private List<NewsModelClass> homeNews = new ArrayList<>();
String country = "in";
String category = "general";
int pageSize = 50;
private RecyclerView recyclerView;
NewsAdapter newsAdapter;
final String API_KEY = "ba88d060a3e049ca9fa46f2bea0d52c4";
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.fragment_home, container, false);
recyclerView = v.findViewById(R.id.rvHome);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
return v;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
newsAdapter = new NewsAdapter(getContext(),homeNews);
recyclerView.setAdapter(newsAdapter);
fetchNews();
}
private void fetchNews()
{
Call<NewsArticles> call = RetrofitClient.getInstance().getMyApi().getNews(country,pageSize,category,API_KEY);
call.enqueue(new Callback<NewsArticles>() {
#Override
public void onResponse(#NonNull Call<NewsArticles> call, #NonNull Response<NewsArticles> response) {
if(response.isSuccessful()) {
if (!homeNews.isEmpty()) {
homeNews.clear();
}
homeNews=response.body().getArticles();
newsAdapter.notifyDataSetChanged();
}
}
#Override
public void onFailure(#NonNull Call<NewsArticles> call, Throwable t) {
Toast.makeText(getContext(),"Something is wrong",Toast.LENGTH_SHORT).show();
}
});
}
}
fragment_home.xml - Other fragments have the same layout
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fragments.HomeFragment">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rvHome"
android:fitsSystemWindows="true"
android:padding="8dp"/>
</FrameLayout>
NewsAdapter.java
public class NewsAdapter extends
RecyclerView.Adapter<NewsAdapter.NewsViewHolder> {
Context context;
List<NewsModelClass> allNews;
public NewsAdapter(Context context,List<NewsModelClass>
allNews) {
this.context = context;
this.allNews = allNews;
}
#NonNull
#Override
public NewsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View newsItem = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_news, parent, false);
return new NewsViewHolder(newsItem);
}
#Override
public void onBindViewHolder(#NonNull NewsViewHolder holder, int position) {
NewsModelClass currentNewsItem = allNews.get(position);
holder.title.setText(currentNewsItem.getTitle());
holder.author.setText(currentNewsItem.getAuthor());
if (currentNewsItem.getUrlToImage() != null)
Glide.with(holder.itemView.getContext()).load(Uri.parse(currentNewsItem.getUrlToImage())).into(holder.articleImage);
holder.cardView.setOnClickListener(v -> {
String newsUrl = currentNewsItem.getUrl();
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
int colorInt = Color.parseColor("#F1ECC3");
CustomTabColorSchemeParams defaultColors = new CustomTabColorSchemeParams.Builder()
.setToolbarColor(colorInt)
.build();
builder.setDefaultColorSchemeParams(defaultColors);
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(context, Uri.parse(newsUrl));
});
}
#Override
public int getItemCount() {
return allNews.size();
}
public static class NewsViewHolder extends RecyclerView.ViewHolder {
ImageView articleImage;
TextView title, author;
CardView cardView;
public NewsViewHolder(#NonNull View itemView) {
super(itemView);
articleImage = itemView.findViewById(R.id.ivArticleImage);
title = itemView.findViewById(R.id.tvHeadline);
author = itemView.findViewById(R.id.tvAuthor);
cardView = itemView.findViewById(R.id.cardView);
}
}
}

RecyclerView inside of ViewPager

I'm trying to make a tab layout with each page having a RecyclerView inside of it. I'm using fragments with RecyclerView in them, then i put them inside of ViewPager. The problem is that even though tabs are being shown it's content is always empty.
My Activity class
public class Spells_Act extends AppCompatActivity {
private ViewPager pager;
private Spells_Slide slider;
private TabLayout tabLayout;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spells);
tabLayout = findViewById(R.id.tab);
pager = findViewById(R.id.pager);
slider = new Spells_Slide(getSupportFragmentManager());
slider.AddFragment(new Fragment1(), "one");
slider.AddFragment(new Fragment1(), "two");
slider.AddFragment(new Fragment1(), "three");
pager.setAdapter(slider);
tabLayout.setupWithViewPager(pager);
}
}
My ViewPager adapter
public class Spells_Slide extends FragmentPagerAdapter {
private Context context;
LayoutInflater inflater;
private List<RecyclerView> pages;
private List<String> list = new LinkedList<>();
private final List<Fragment> stFragment = new ArrayList();
public Spells_Slide(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return stFragment.get(position);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return list.get(position);
}
#Override
public int getCount() {
return list.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object
object) {
return false;
}
public void AddFragment(Fragment fragment, String title) {
list.add(title);
stFragment.add(fragment);
}
My Fragment class
public class Fragment1 extends Fragment {
View v;
private RecyclerView recycler;
Adapter_Rec adapter;
private List<Spells> Spells = new LinkedList<>();
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Spells.add(new Spells("Ghost Sound", "Figment sounds", 0));
Spells.add(new Spells("Disrupt Undead", " Deals 1d6 damage to one undead", 0));
Spells.add(new Spells("Resistance", "Subject gains +1 on saving throws", 0));
Spells.add(new Spells("Ray of Frost", "Ray deals 1d3 cold damage", 0));
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.frag1, container, false);
recycler = v.findViewById(R.id.frag_recycler);
recycler.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new Adapter_Rec(Spells, getContext());
recycler.setAdapter(adapter);
return v;
}
}
And finally my RecyclerViewAdapter
public class Adapter_Rec extends
RecyclerView.Adapter<Adapter_Rec.MyViewHolder> {
private List<Spells> list = new LinkedList<>();
Context context;
public Adapter_Rec(List<Spells> list, Context context)
{
this.context=context;
this.list=list;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
v = LayoutInflater.from(context).inflate
(R.layout.spells_recycle,parent,false);
MyViewHolder vholder = new MyViewHolder(v);
return vholder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.check.setOnCheckedChangeListener(null);
holder.name.setText(list.get(position).getName());
holder.benefits.setText(list.get(position).getDescription());
}
#Override
public int getItemCount() {
return list.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder
{
TextView name;
TextView benefits;
CheckBox check ;
public MyViewHolder(View item)
{ super(item);
name = item.findViewById(R.id.namee);
benefits = item.findViewById(R.id.desc);
check =item.findViewById(R.id.check);
}
}
}
delete isViewFromObject method, or return super.isViewFromObject(view, object);
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object
object) {
//return false; // return false will never show this fragment
return super.isViewFromObject(view, object);
}

Two instances of one fragment class works incorrect

I have created tabbed activity, which has viewpager with two instances of one fragment class. This fragment contains listbox, and I have written few functions to
interact with listview items, and one function in activity to do the same thing. The point is when im trying to call fragment methods, it always trying to update the listview of fragment, which was created at first, but when i call function from activity it works absolutely correct. Whats the problem?
Here is the code of activity:
public class CategoriesActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
SparseArray<Fragment> registeredFragments = new SparseArray<>();
Toolbar toolbar;
FloatingActionButton btnAddCategories;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_categories);
assignElements();
prepareToolbar();
prepareEelements();
}
public void assignElements() {
toolbar = findViewById(R.id.action_bar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
btnAddCategories = findViewById(R.id.btnAddCategory);
// Set up the ViewPager with the sections adapter.
mViewPager = findViewById(R.id.container);
}
public void prepareToolbar() {
toolbar.setTitle("Категории");
toolbar.setTitleTextColor(getResources().getColor(R.color.colorTextLight));
toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
public void prepareEelements() {
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
btnAddCategories.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TabCategoriesFragment tabCategoriesFragment = (TabCategoriesFragment) getRegisteredFragment(mViewPager.getCurrentItem());
tabCategoriesFragment.addNewCategory();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch(id) {
case R.id.home:
finish();
break;
case R.id.homeAsUp:
finish();
break;
case android.R.id.home:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = TabCategoriesFragment.newInstance(false);
break;
case 1:
fragment = TabCategoriesFragment.newInstance(true);
break;
}
return fragment;
}
#Override
public int getCount() {
return 2;
}
}
}
And of the fragment:
public class TabCategoriesFragment extends Fragment {
private static final String ARG_INCOMING = "Incoming";
private OnFragmentInteractionListener mListener;
public int Incoming = -1;
ListView listView;
ArrayList<Categories> categories;
CategoriesListViewAdapter categoriesListViewAdapter;
DBHelper dbHelper;
SQLiteDatabase sqLiteDatabase;
public TabCategoriesFragment() {
}
public int selectedPostion;
public static TabCategoriesFragment newInstance(boolean Incoming) {
TabCategoriesFragment fragment = new TabCategoriesFragment();
Bundle args = new Bundle();
args.putBoolean(ARG_INCOMING, Incoming);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
if (getArguments().getBoolean(ARG_INCOMING)) {
Incoming = 1;
} else {
Incoming = 0;
}
}
}
public void assignElements(View view) {
dbHelper = new DBHelper(getContext());
sqLiteDatabase = dbHelper.getWritableDatabase();
categories = new ArrayList<>();
categoriesListViewAdapter = new CategoriesListViewAdapter(getContext(), categories);
}
#SuppressLint("ClickableViewAccessibility")
public void prepareElements() {
filldata();
listView.setAdapter(categoriesListViewAdapter);
categoriesListViewAdapter.notifyDataSetChanged();
registerForContextMenu(listView);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
selectedPostion = position;
getActivity().openContextMenu(listView);
return true;
}
});
}
public void deleteCategory(boolean deletecosts, String name) {
try {
//delete from db
} catch (Exception e) {
Toast.makeText(getContext(), "Произошла ошибка" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
public String getTableName() {
if (Incoming == 1) {
return "incomingcategories";
} else {
return "outcomingcategories";
}
}
public String getSign() {
if (Incoming == 1) {
return ">";
} else {
return "<";
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
Objects.requireNonNull(getActivity()).getMenuInflater().inflate(R.menu.edit_category_menu, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
//final int selectedPostion = ((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).position;
int id = item.getItemId();
final CheckBox checkBox = new CheckBox(getContext());
switch (id) {
case R.id.categoryDelete:
deleteCategory(categories.get(selectedPosition);
filldata();
categoriesListViewAdapter.notifyDataSetChanged();
case R.id.categorySetbydefault:
break;
case R.id.categoriesSetBydefault:
setCategoryBydefault(categories.get(selectedPostion).description);
filldata();
categoriesListViewAdapter.notifyDataSetChanged();
break;
}
return true;
}
public void setCategoryBydefault(String name) {
//set
}
#Override
public void onStart() {
super.onStart();
prepareElements();
CategoriesActivity categoriesActivity = (CategoriesActivity) getActivity();
}
public void filldata() {
categories.clear();
//do some stuff
}
public void addNewCategory() {
//do some stuff
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_tab_categories, container, false);
listView = view.findViewById(R.id.CategoriesListView);
assignElements(view);
return view;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}

How to use getChildFragmentManager with a class that extends Dialog fragment

I am a having a fragment with TabLayout. As soon as I move from TabLayout Fragment to the next Fragment and press the back key. The content on the default TabLayout fragment disappears. I found a possible solution to this in the post. Following is the code for the TabLayout.
public class IndividualCollectionSheetFragment extends MifosBaseFragment {
private TabLayout tabLayout;
private ViewPager viewPager;
private View rootView;
public IndividualCollectionSheetFragment() {
}
public static IndividualCollectionSheetFragment newInstance() {
Bundle args = new Bundle();
IndividualCollectionSheetFragment fragment = new IndividualCollectionSheetFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_individual_recycler, container, false);
ButterKnife.bind(this, rootView);
setToolbarTitle(getStringMessage(R.string.individual_collection_sheet));
viewPager = rootView.findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = rootView.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
return rootView;
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity().getSupportFragmentManager());
adapter.addFragment(new NewIndividualCollectionSheetFragment(), Constants.NEW);
adapter.addFragment(new SavedIndividualCollectionSheetFragment(), Constants.SAVED);
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);
}
}
}
The solution in the post suggested using getChildFramentManager instead of getSupportFragmentManager. As soon as I changed to getChildFragmentManager. I got the error.
java.lang.IllegalStateException: Fragment CollectionSheetDialogFragment{572dd42 #0 Identifier Dialog Fragment} declared target fragment NewIndividualCollectionSheetFragment{45e8153 #0 id=0x7f090361 android:switcher:2131297121:0} that does not belong to this FragmentManager!
which might be because of the class CollectionSheetDialogFragment which extends DialogFragment and there must be inconsistencies with the different Fragment Managers being used.
NewIndividualCollectionSheet.java(first fragment in tablayout)
public class NewIndividualCollectionSheetFragment extends MifosBaseFragment implements
IndividualCollectionSheetMvpView, MFDatePicker.OnDatePickListener,
Spinner.OnItemSelectedListener, View.OnClickListener {
#BindView(R.id.btn_fetch_collection_sheet)
Button btnFetchSheet;
#BindView(R.id.sp_office_list)
Spinner spOffices;
#BindView(R.id.sp_staff_list)
Spinner spStaff;
#BindView(R.id.tv_repayment_date)
TextView tvRepaymentDate;
#Inject
NewIndividualCollectionSheetPresenter presenter;
private IndividualCollectionSheet sheet;
private DialogFragment datePicker;
private RequestCollectionSheetPayload requestPayload;
private View rootView;
private ArrayAdapter<String> officeAdapter;
private ArrayList<String> officeNameList;
private List<Office> officeList;
private ArrayAdapter<String> staffAdapter;
private ArrayList<String> staffNameList;
private List<Staff> staffList;
private int officeId;
private int staffId;
private int requestCode = 1;
private boolean success = true;
private String actualDisbursementDate;
private String transactionDate;
public NewIndividualCollectionSheetFragment() {
}
public static NewIndividualCollectionSheetFragment newInstance() {
Bundle args = new Bundle();
NewIndividualCollectionSheetFragment fragment = new NewIndividualCollectionSheetFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((MifosBaseActivity) getActivity()).getActivityComponent().inject(this);
if (savedInstanceState != null) {
sheet = (IndividualCollectionSheet) savedInstanceState.get(
Constants.EXTRA_COLLECTION_INDIVIDUAL);
}
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_new_collection_sheet, container, false);
ButterKnife.bind(this, rootView);
setToolbarTitle(getStringMessage(R.string.individual_collection_sheet));
presenter.attachView(this);
setUpUi();
return rootView;
}
private void setUpUi() {
setRepaymentDate();
officeNameList = new ArrayList<>();
officeAdapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_spinner_item, officeNameList);
officeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spOffices.setAdapter(officeAdapter);
spOffices.setOnItemSelectedListener(this);
staffNameList = new ArrayList<>();
staffAdapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_spinner_item, staffNameList);
staffAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spStaff.setAdapter(staffAdapter);
tvRepaymentDate.setOnClickListener(this);
btnFetchSheet.setOnClickListener(this);
presenter.fetchOffices();
}
void setRepaymentDate() {
datePicker = MFDatePicker.newInsance(this);
String date = DateHelper.
getDateAsStringUsedForCollectionSheetPayload(MFDatePicker.getDatePickedAsString());
tvRepaymentDate.setText(date.replace('-', ' '));
transactionDate = date.replace('-', ' ');
actualDisbursementDate = transactionDate;
}
private void prepareRequestPayload() {
requestPayload = new RequestCollectionSheetPayload();
requestPayload.setOfficeId(officeId);
requestPayload.setStaffId(staffId);
requestPayload.setTransactionDate(tvRepaymentDate.getText().toString());
}
#Override
public void setOfficeSpinner(List<Office> offices) {
officeList = offices;
officeNameList.clear();
officeNameList.add(getString(R.string.spinner_office));
officeNameList.addAll(presenter.filterOffices(officeList));
officeAdapter.notifyDataSetChanged();
}
#Override
public void onDatePicked(String date) {
String d = DateHelper.getDateAsStringUsedForCollectionSheetPayload(date);
tvRepaymentDate.setText(d.replace('-', ' '));
}
public void retrieveCollectionSheet() {
prepareRequestPayload();
presenter.fetchIndividualCollectionSheet(requestPayload);
}
public void setTvRepaymentDate() {
datePicker.show(getActivity().getSupportFragmentManager(),
FragmentConstants.DFRAG_DATE_PICKER);
}
#Override
public void setStaffSpinner(List<Staff> staffs) {
spStaff.setOnItemSelectedListener(this);
staffList = staffs;
staffNameList.clear();
staffNameList.add(getString(R.string.spinner_staff));
staffNameList.addAll(presenter.filterStaff(staffList));
staffAdapter.notifyDataSetChanged();
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
switch (adapterView.getId()) {
case R.id.sp_office_list:
if (i == officeList.size() || i == 0) {
Toaster.show(rootView, getStringMessage(R.string.error_select_office));
} else {
Toaster.show(rootView, officeNameList.get(i));
officeId = officeList.get(i - 1).getId();
presenter.fetchStaff(officeId);
}
break;
case R.id.sp_staff_list:
if (i == staffList.size() || i == 0) {
Toaster.show(rootView, getStringMessage(R.string.error_select_staff));
} else {
staffId = staffList.get(i - 1).getId();
}
break;
}
}
public void popupDialog() {
CollectionSheetDialogFragment collectionSheetDialogFragment =
CollectionSheetDialogFragment.newInstance(tvRepaymentDate.getText().toString(),
sheet.getClients().size());
collectionSheetDialogFragment.setTargetFragment(this, requestCode);
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager()
.beginTransaction();
fragmentTransaction.addToBackStack(FragmentConstants.FRAG_DOCUMENT_LIST);
collectionSheetDialogFragment.show(fragmentTransaction, "Identifier Dialog Fragment");
}
public void getResponse(String response) {
switch (response) {
case "FillNow":
FragmentManager fm = getActivity()
.getSupportFragmentManager();
fm.popBackStack();
IndividualCollectionSheetDetailsFragment frag = new
IndividualCollectionSheetDetailsFragment().newInstance(sheet,
actualDisbursementDate, transactionDate);
((MifosBaseActivity) getActivity()).replaceFragment(frag,
true, R.id.container);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
#Override
public void showSheet(IndividualCollectionSheet individualCollectionSheet) {
sheet = individualCollectionSheet;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(Constants.EXTRA_COLLECTION_INDIVIDUAL, sheet);
}
#Override
public void showSuccess() {
if (success) {
popupDialog();
}
}
#Override
public void showError(String message) {
Toaster.show(rootView, message);
}
#Override
public void showNoSheetFound() {
success = false;
Toaster.show(rootView, getStringMessage(R.string.no_collectionsheet_found));
}
#Override
public void showProgressbar(boolean b) {
if (b) {
showMifosProgressDialog();
} else {
hideMifosProgressDialog();
}
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.tv_repayment_date:
setTvRepaymentDate();
break;
case R.id.btn_fetch_collection_sheet:
retrieveCollectionSheet();
break;
}
}
}
CollectionSheetDialogFragment.java
public class CollectionSheetDialogFragment extends DialogFragment {
#BindView(R.id.tv_due_date)
TextView tvDueDate;
#BindView(R.id.tv_members)
TextView tvMembers;
#BindView(R.id.btn_fillnow)
Button btnFillnow;
#BindView(R.id.btn_cancel)
Button btnCancel;
private View rootView;
private String date;
private int members;
public CollectionSheetDialogFragment() {
}
public static CollectionSheetDialogFragment newInstance(String date, int members) {
CollectionSheetDialogFragment collectionSheetDialogFragment =
new CollectionSheetDialogFragment();
Bundle args = new Bundle();
args.putString(Constants.REPAYMENT_DATE, date);
args.putInt(Constants.MEMBERS, members);
collectionSheetDialogFragment.setArguments(args);
return collectionSheetDialogFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((MifosBaseActivity) getActivity()).getActivityComponent().inject(this);
date = getArguments().getString(Constants.REPAYMENT_DATE);
members = getArguments().getInt(Constants.MEMBERS);
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable
ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_collection_sheet_dialog, container, false);
ButterKnife.bind(this, rootView);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
tvDueDate.setText(date);
tvMembers.setText(Integer.toString(members));
}
#OnClick(R.id.btn_fillnow)
public void setBtnFillnow() {
((NewIndividualCollectionSheetFragment) getTargetFragment()).getResponse("FillNow");
}
#OnClick(R.id.btn_cancel)
public void setBtnCancel() {
getDialog().dismiss();
}
}
Can someone help me get around this error so I can persist the TabLayout On back press?
Maybe This Work :
Replace getFragmentManager() instead of getChildFragmentManager()
Try this changing seupViewPager() in IndividualCollectionSheetFragment.java like this
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity().getChildFragmentManager());
adapter.addFragment(new NewIndividualCollectionSheetFragment(), Constants.NEW);
adapter.addFragment(new SavedIndividualCollectionSheetFragment(), Constants.SAVED);
viewPager.setAdapter(adapter);
}

Java Passing Data From One Fragment's ListView To Another Fragment

Movie ListView Fragment
Movie Info Fragment
What I have is an app that has a database of movies, in my first tab fragment I have a listview which has all the movies in my database. I want it so when I click a movie in the listview it grabs the movie's database id and moves to the next tab which displays the movie info.
Main Activity (The activity that holds my tabs view pager)
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setOffscreenPageLimit(1);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG).setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu (Menu menu){
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected (MenuItem item){
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new FragmentMain();
case 1:
return new FragmentManuallyAddMovie();
case 2:
return new FragmentAddInternetMovie();
}
return null;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "MOVIES";
case 1:
return "ADD";
case 2:
return "SEARCH";
}
return null;
}
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
FragmentMain (Where the movies database is displayed in a listview)
public class FragmentMain extends Fragment implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener, View.OnClickListener {
private MoviesDBHandler handler;
private SimpleCursorAdapter adapter;
private ListView lvMovies;
public FragmentMain() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_main, container, false);
handler = new MoviesDBHandler(this.getActivity());
v.findViewById(R.id.btn_delete_all_movies).setOnClickListener(this);
lvMovies = (ListView) v.findViewById(R.id.lv_movies);
lvMovies.setEmptyView(v.findViewById(R.id.tv_instructionsa));
lvMovies.setOnItemClickListener(this);
lvMovies.setOnItemLongClickListener(this);
return v;
}
#Override
public void onResume() {
super.onResume();
String[] from = {MoviesDBHelper.MOVIES_TITLE, MoviesDBHelper.MOVIES_GENRE, MoviesDBHelper.MOVIES_YEAR, MoviesDBHelper.MOVIES_PLOT, MoviesDBHelper.MOVIES_RATING, MoviesDBHelper.MOVIES_RUNTIME, MoviesDBHelper.MOVIES_IMAGE_URL};
int[] to = {R.id.tv_title, R.id.tv_genre, R.id.tv_year, R.id.tv_plot, R.id.tv_rating, R.id.tv_runtime, R.id.img_movie_poster};
adapter = new SimpleCursorAdapter(this.getActivity(), R.layout.movie_list_item, handler.getMovies(), from, to, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if(columnIndex == cursor.getColumnIndex(MoviesDBHelper.MOVIES_IMAGE_URL)) {
DatabaseDownloadImage task = new DatabaseDownloadImage((ImageView) view);
task.execute(cursor.getString(columnIndex));
return true;
}
return false;
}
});
lvMovies.setAdapter(adapter);
}
public class DatabaseDownloadImage extends AsyncTask<String, Integer, Bitmap> {
private ImageView imageView;
public DatabaseDownloadImage(ImageView imageView) {
this.imageView = imageView;
}
#Override
protected Bitmap doInBackground(String... params) {
String address = params[0];
HttpURLConnection connection = null;
Bitmap b = null;
try {
URL url = new URL(address);
connection = (HttpURLConnection) url.openConnection();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return null;
}
else {
b = BitmapFactory.decodeStream(connection.getInputStream());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return b;
}
protected void onPostExecute(Bitmap bitmap) {
if (bitmap == null) {
return;
}
imageView.setImageBitmap(Bitmap.createScaledBitmap(bitmap, 120, 180, false));
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
//Delete all movies from database
case R.id.btn_delete_all_movies:
AlertDialog deleteMovieDialog = new AlertDialog.Builder(this.getActivity()).create();
deleteMovieDialog.setTitle("Delete All Movies?");
deleteMovieDialog.setIcon(R.drawable.ic_delete);
deleteMovieDialog.setButton(DialogInterface.BUTTON_POSITIVE, "No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
deleteMovieDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
handler.deleteAllMovies();
adapter.changeCursor(handler.getMovies());
}
});
deleteMovieDialog.show();
break;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, final long id) {
AlertDialog deleteMovieDialog = new AlertDialog.Builder(this.getActivity()).create();
deleteMovieDialog.setTitle("Delete Movie?");
deleteMovieDialog.setIcon(R.drawable.ic_delete);
deleteMovieDialog.setButton(DialogInterface.BUTTON_POSITIVE, "No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
deleteMovieDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
handler.deleteMovie(id);
adapter.changeCursor(handler.getMovies());
}
});
deleteMovieDialog.show();
return true;
}
}
All Fragment-to-Fragment communication is done through the associated
Activity. Two Fragments should never communicate directly.
http://developer.android.com/intl/es/training/basics/fragments/communicating.html
You can communicate the two fragments with a static variable in the MainActivity that you change in the first fragment and get the content of this variable in the second fragment.
Update:
Create Movie.class, to save all the data of a one movie:
public class Movie() {
String title;
String genre;
int year;
String plot;
int rating;
int runtime;
String img;
public Movie(String title, String genre, int year, String plot, int rating, int runtime, String img) {
this.title=title;
this.genre=genre;
this.year=year;
this.plot=plot;
this.rating=rating;
this.runtime=runtime;
this.img=img;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title=title;
}
//The same for the other variables
}
and in your MainActivity create a static variable of Movie:
public static Movie movie;
In onClick method save the data of the movie:
MainActivity.movie=new Movie(title, genre, year,plot,rating,runtime,img);
And to get the movie in the second fragment:
String title=MainActivity.movie.getTitle();
String genre=MainActivity.movie.getGenre();
...

Categories