Sending data from activity to fragment using set methods - android

I've posted a question regarding of passing data from activity to a fragment. And I've learnt that implementing Parcelable to a POJO class is a right way of doing it. After some research I also understand that in order to pass data to a fragment should use Bundle instead of Intent.
My previous question -->
Using same fragments but different content in Android
But now, my question is, what should I do in order to display a list of details (name, address, phone) using set methods when the cardview is clicked?
To be clear, what I want is
When first restaurant is clicked, the new intent that contains details fragment will be started. Inside the details fragment, it will display the restaurant name, address and phone of the first restaurant.
Can anyone guide me by showing me the code of two set of different details when two different restaurant cardview is clicked?
RestaurantListAdapter.java
I want to use if else statement under onClick, to display different details when different cardview is clicked
public class RestaurantListAdapter extends RecyclerView.Adapter<RestaurantListAdapter.ViewHolder> {
List<RestaurantList_Item> items;
private static ClickListener clickListener;
private Context context;
public RestaurantListAdapter(){
super();
items = new ArrayList<RestaurantList_Item>();
// POSITION 1
RestaurantList_Item restaurant = new RestaurantList_Item();
restaurant.setrImage(R.mipmap.img_anjappar);
restaurant.setrName("Anjappar Indian Chettinad Restaurant");
restaurant.setrCuisine("Indian");
items.add(restaurant);
// POSITION 2
restaurant = new RestaurantList_Item();
restaurant.setrImage(R.mipmap.img_morganfield);
restaurant.setrName("Morganfield");
restaurant.setrCuisine("Western");
items.add(restaurant);
// POSITION 3
restaurant = new RestaurantList_Item();
restaurant.setrImage(R.mipmap.img_nandos);
restaurant.setrName("Nando's");
restaurant.setrCuisine("Western");
items.add(restaurant);
// POSITION 4
restaurant = new RestaurantList_Item();
restaurant.setrImage(R.mipmap.img_shellout);
restaurant.setrName("Shellout");
restaurant.setrCuisine("Seafood");
items.add(restaurant);
// POSITION 5
restaurant = new RestaurantList_Item();
restaurant.setrImage(R.mipmap.img_beyond);
restaurant.setrName("Beyond Veggie");
restaurant.setrCuisine("Vegetarian");
items.add(restaurant);
// POSITION 6
restaurant = new RestaurantList_Item();
restaurant.setrImage(R.mipmap.img_myelephant);
restaurant.setrName("My Elephant");
restaurant.setrCuisine("Thai");
items.add(restaurant);
// POSITION 7
restaurant = new RestaurantList_Item();
restaurant.setrImage(R.mipmap.img_padangkota);
restaurant.setrName("Nasi Kandar Padang Kota");
restaurant.setrCuisine("Mamak");
items.add(restaurant);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.cardview_restaurant, viewGroup, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
final RestaurantList_Item restaurant = items.get(position);
viewHolder.resImage.setImageResource(restaurant.getrImage());
viewHolder.restaurantName.setText(restaurant.getrName());
viewHolder.cuisine.setText(restaurant.getrCuisine());
viewHolder.itemView.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
// Toast.makeText(context, "Item clicked with position " +position, Toast.LENGTH_LONG).show();
if(position == 0){
Intent i = new Intent(context, Restaurant.class);
context.startActivity(i);
}
}
});
}
#Override
public int getItemCount() {
return items.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public ImageView resImage;
public TextView restaurantName;
public TextView cuisine;
public ViewHolder(final View itemView) {
super(itemView);
resImage = (ImageView) itemView.findViewById(R.id.resImage);
restaurantName = (TextView) itemView.findViewById(R.id.restaurantName);
cuisine = (TextView) itemView.findViewById(R.id.cuisine);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
clickListener.onItemClick(getAdapterPosition(), v);
}
}
public void setOnItemClickListener (ClickListener clickListener){
RestaurantListAdapter.clickListener = clickListener;
}
public interface ClickListener{
void onItemClick (int position, View v);
}
}
RestaurantModel.java
This is the POJO class that contains get set methods, I want to use the set methods to display restaurant details
public class RestaurantModel implements Parcelable{
//empty constructor
public RestaurantModel(){}
//A constructor that initializes the Restaurant object
public RestaurantModel(String resName, String resAddress, String resPhone, String resCuisine, String resPriceRange){
this.resName = resName;
this.resAddress =resAddress;
this.resPhone = resPhone;
this.resCuisine = resCuisine;
this.resPriceRange = resPriceRange;
}
//Parcelling the object
public RestaurantModel(Parcel in){
String[] data = new String [5];
in.readStringArray(data);
this.resName = data[0];
this.resAddress = data[1];
this.resPhone = data[2];
this.resCuisine = data[3];
this.resPriceRange = data[4];
}
// variable main photo
private int mainImage;
//variables for details fragment
private String resName, resAddress, resPhone, resCuisine, resPriceRange;
//variables for menu fragment
private int foodPhoto;
private String foodPrice, foodDescription;
/*get set methods*/
public int getMainImage(){
return mainImage;
}
public void setMainImage(int mainImage){
this.mainImage = mainImage;
}
public String getResName(){
return resName;
}
public void setResName(String resName){
this.resName = resName;
}
public String getResAddress(){return resAddress;}
public void setResAddress(String resAddress){this.resAddress = resAddress;}
public String getResPhone(){return resPhone;}
public void setResPhone(String resPhone){this.resPhone = resPhone;}
public String getResCuisine(){return resCuisine;}
public void setResCuisine(String resCuisine){this.resCuisine = resCuisine;}
public String getResPriceRange(){return resPriceRange;}
public void setResPriceRange(String resPriceRange){this.resPriceRange = resPriceRange;}
public int getFoodPhoto(){return foodPhoto;}
public void setFoodPhoto(int foodPhoto){this.foodPhoto = foodPhoto;}
public String getFoodDescription(){return foodDescription;}
public void setFoodDescription(String foodDescription){this.foodDescription = foodDescription;}
public String getFoodPrice(){return foodPrice;}
public void setFoodPrice(String foodPrice){this.foodPrice = foodPrice;}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray(new String[]{
this.resName,this.resAddress,this.resPhone, this.resCuisine, this.resPriceRange
});
}
// Creator
public static final Parcelable.Creator<RestaurantModel> CREATOR = new Parcelable.Creator<RestaurantModel>(){
#Override
public RestaurantModel createFromParcel(Parcel source) {
return new RestaurantModel(source);
}
#Override
public RestaurantModel[] newArray(int size) {
return new RestaurantModel[size];
}
};
}
Restaurant.java
This activity contains the fragments that will be shown when the cardview is clicked
public class Restaurant extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_restaurant);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager){
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new details(), "Details");
adapter.addFragment(new menu(), "Menu");
adapter.addFragment(new tableBooking(), "Table booking");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter{
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> fragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager){
super(manager);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
public void addFragment (Fragment fragment, String title){
fragmentList.add(fragment);
fragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
}
}
Details.java
This class extends fragment that contains restaurant details such as name, address and phone
public class details extends Fragment {
private TextView resName, resAddress, resPhone, resCuisine, resPriceRange;
public details() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* resName = (TextView) getView().findViewById (R.id.resName);
resAddress = (TextView) getView().findViewById (R.id.resAddress);
resPhone = (TextView) getView().findViewById (R.id.resPhone);
resCuisine = (TextView) getView().findViewById (R.id.resCuisine);
resPriceRange = (TextView) getView().findViewById (R.id.resPriceRange);*/
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_details, container, false);
}
}
Homepage.java
public class Homepage extends Activity {
RecyclerView recyclerView;
RecyclerView.LayoutManager llm;
RecyclerView.Adapter adapter;
private static final String TAG = Homepage.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//super.onCreateDrawer(R.layout.activity_homepage);
setContentView(R.layout.activity_homepage);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
llm = new LinearLayoutManager(Homepage.this);
recyclerView.setLayoutManager(llm);
adapter = new RestaurantListAdapter();
recyclerView.setAdapter(adapter);
}
}
EDIT: I'm not sure if I'm doing this correctly. I created multiple arraylist that describes different details for different restaurant. I put the code at onClick methods in RestaurantListAdapter.
#Override
public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
final RestaurantList_Item restaurant = items.get(position);
viewHolder.resImage.setImageResource(restaurant.getrImage());
viewHolder.restaurantName.setText(restaurant.getrName());
viewHolder.cuisine.setText(restaurant.getrCuisine());
viewHolder.itemView.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
RestaurantModel rAnjappar = new RestaurantModel();
details fragment = new details();
Intent i = new Intent(context, Restaurant.class);
// Array List
ArrayList<RestaurantModel> a1 = new ArrayList<RestaurantModel>();
rAnjappar.setResName("Anjappar");
rAnjappar.setResAddress("Bandar Kinrara");
rAnjappar.setResPhone("03-80807362");
rAnjappar.setResCuisine("Mamak");
rAnjappar.setResPriceRange("RM 30 for 2 person");
ArrayList<RestaurantModel> a2 = new ArrayList<RestaurantModel>();
rAnjappar.setResName("Morganfield");
rAnjappar.setResAddress("Bandar Utama");
rAnjappar.setResPhone("03-80807362");
rAnjappar.setResCuisine("Western");
rAnjappar.setResPriceRange("RM 60 for 2 person");
// action when card view is clicked
if(position == 0){
Bundle b1 = new Bundle();
b1.putParcelableArrayList("anjappar", a1);
fragment.setArguments(b1);
context.startActivity(i);
}
}
});
}
If this is acceptable, next thing I should do is retrieve the bundle in my fragment code right? But since I will be having multiple bundles, how am I supposed to retrieve all the bundles in a correct way?

Ok so from as far as i understand you can do following things
1 Add this method in Adapter
public RestaurantList_Item getItem(int pos) {
return items.get(pos);
}
2. Homepage is your clicklistner activity (Hope so) in it
public void onItemClick(int position, view v) {
RestaurantList_Item row_object = adapter.getItem(position);
Intent i = new Intent(context, Restaurant.class);
i.putExtra(Common.Data_Object, row_object);
startActivity(i);
}
3. Replace code of Restaurant class
public class Restaurant extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
private RestaurantList_Item row_object;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_restaurant);
getIntentData(getIntent());
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void getIntentData(Intent i) {
if (i != null) {
row_object = i.getParcelableExtra(Common.Data_Object);
}
}
private void setupViewPager(ViewPager viewPager){
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
Fragment f = new details();
Bundle arguments = new Bundle();
arguments.putParcelable(Common.Data_Object, row_object);
f.setArguments(arguments);
adapter.addFragment(f, "Details");
adapter.addFragment(new menu(), "Menu");
adapter.addFragment(new tableBooking(), "Table booking");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter{
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> fragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager){
super(manager);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
public void addFragment (Fragment fragment, String title){
fragmentList.add(fragment);
fragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
}
}
4. get object from bundle in Detail fragment
private void getIntentData(Bundle b)
{
if (b != null)
{
detailObject = b.getParcelable(Common.Data_Object);
}
}
Hope it will help.

You can use setArguments() method of the fragment to pass your restaurant model class to new fragment while creating the new instance of it.You can get it back using getArguments() in newly created fragment's onCreate() method. You have to make your resturantModel.java class Serializable.
public class RestaurantModel implements Serializable{
...
}
Add data:-
Bundle bundle = new Bundle();
bundle.putSerializable("restaurant", restaurant);
Fragment1 frag1 = new Fragment1();
frag1.setArguments(bundle);
Get data :-
RestauranModel restaurant = (RestauranModel) getArguments().getSerializable("restaurant");
FYI: Difference between Parcelable and Serializable : https://stackoverflow.com/a/3323554/4690731

Related

False data in customList in a dynamically created fragment

I have an Activity with 2 fragments.
Declared a ParentTabFragment in my Activity in which there is a TabLayout and a ViewPager.
There's a method in my ParentTabFragment called addPage which gets called in the Activity.
The addPage has another method called addFrag which is called from a ViewPagerAdapter creating the views in the ChildTabFragment dynamically.
There is a for loop which runs in the Activity, so the Fragments are created according to the number of items in the customList, creating the amount of tabs and pages in the Fragments.
In my ChildTabFragment I load a customList on tab selection event,
when I select a Tab in the ParentTabFragment, I call a getTabID() method from the ChildTabFragment and send the id of the Tab due to which I load the customList according to the id in the ParentTabFragment.
Problem is when I swipe or select tabs, duplicate/false data gets created in the customList.
I get the proper Id of the selected tab but when I try to pass it in the method, random id is called.
In my Activity Class:
for (int j =0;j<it.size();j++){
parentTabFragment.addPage(it.get(j).getTabMenuItem(), it.get(j).getTabMenuId() , selectedMenu);
}
ParentTabFragment:
public void addPage(String pagename, String pageId, String selectedMenu) {
Bundle bundle = new Bundle();
bundle.putString("data", pagename);
//bundle.putString("pageID", pageId);
childTabFragment = new ChildTabFragment();
childTabFragment.setArguments(bundle);
adapter.addFrag(childTabFragment, pagename, pageId);
adapter.notifyDataSetChanged();
if (selectedMenu == null) {
viewPager.setCurrentItem(0);
} else {
for (int i = 0; i < tabLayout.getTabCount(); i++) {
if (tabLayout.getTabAt(i).getText().equals(selectedMenu)) {
viewPager.setCurrentItem(i);
}
}
}
if (adapter.getCount() > 0) tabLayout.setupWithViewPager(viewPager);
setupTabLayout();
}
public void setupTabLayout() {
selectedTabPosition = viewPager.getCurrentItem();
for (int i = 0; i < tabLayout.getTabCount(); i++) {
tabLayout.getTabAt(i).setCustomView(adapter.getTabView(i));
}
}
ChildTabFragment:
public class ChildTabFragment extends Fragment {
String childname;
int menuItemId;
TextView textViewChildName, txtViewItemId;
ListView childTabMenuList;
private ArrayList<ChildTabMenu_POJO> childTabMenuPojoList = new ArrayList<>();
private ListView listView;
private ChildTabMenuAdapter childTabMenuAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.child_tab_fragment, container, false);
Bundle bundle = getArguments();
childname = bundle.getString("data");
getIDs(view);
return view;
}
private void getIDs(View view) {
childTabMenuList = (ListView) view.findViewById(R.id.childTabMenuList);
loadChildMenu();
}
private void loadChildMenu(menuItemId) {
ChildTabMenu_POJO menu_pojo4 = new ChildTabMenu_POJO(String.valueOf(menuItemId), "4");
childTabMenuPojoList.add(menu_pojo4);
childTabMenuAdapter = new ChildTabMenuAdapter(childTabMenuPojoList, getActivity());
childTabMenuList.setAdapter(childTabMenuAdapter);
}
public void getTabID(int tabId) {
menuItemId = tabId;
Log.e("updatefrag", String.valueOf(menuItemId));
}
}
ViewPagerAdapter:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final ArrayList<Fragment> mFragmentList = new ArrayList<>();
private final ArrayList<Adapter_POJO> mFragmentTitleList = new ArrayList<>();
Context context;
ViewPager viewPager;
TabLayout tabLayout;
Adapter_POJO adapter_pojo;
public ViewPagerAdapter(FragmentManager manager, Context context, ViewPager viewPager,
TabLayout tabLayout) {
super(manager);
this.context = context;
this.viewPager = viewPager;
this.tabLayout = tabLayout;
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public int getItemCount() {
return mFragmentTitleList.size();
}
public void addFrag(Fragment fragment, String title, String pageId) {
mFragmentList.add(fragment);
adapter_pojo = new Adapter_POJO(title,pageId);
mFragmentTitleList.add(adapter_pojo);
}
public View getTabView(final int position) {
View view = LayoutInflater.from(context).inflate(R.layout.view_pager_adapter_layout, null);
TextView tabItemName = (TextView) view.findViewById(R.id.textViewTabItemName);
tabItemName.setText(mFragmentTitleList.get(position).adapterMenuItem);
tabItemName.setTextColor(context.getResources().getColor(android.R.color.background_light));
return view;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position).adapterMenuItem;
}
public String getPageId(int position){
return mFragmentTitleList.get(position).adapterMenuId;
}
}
If i understand your question so you need to create newInstance constructor for creating fragment with arguments
public static ChildTabFragment newInstance(int page, String title) {
FirstFragment fragmentFirst = new FirstFragment();
Bundle args = new Bundle();
args.putInt("someInt", page);
args.putString("someTitle", title);
fragmentFirst.setArguments(args);
return fragmentFirst;
}
And Store instance variables based on arguments passed in your ChildTabFragment .
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
page = getArguments().getInt("someInt", 0);
title = getArguments().getString("someTitle");
}
And now update the view in your onCreateView method
TextView tvLabel = (TextView) view.findViewById(R.id.tvLabel);
tvLabel.setText(page + " -- " + title);
And the main thing you should returns the ChildTabFragment to display for that page from your ViewPagerAdapter like this.
#Override
public Fragment getItem(int position) {
return ChildTabFragment.newInstance(position,"page "+String.valueOf(position));
}

Communicating between 2 fragments in a Viewpager - Updating RecyclerView in Fragment B from Fragment A

I'm building a simple stock display app that allows you to fetch stocks of interest (frag A), store them in a TinyDB, and display them in a recyclerView (frag B).
The framework used to work fine - until I decided to incorporate a viewpager and Tablayout host. I cannot get the RecyclerView in Frag B to display new data live. This is because the activity viewpager initializes both fragments at launch, meaning you can't call the onCreateView code again, I believe.
Communicating between two fragments through an Activity has been touched before on this site, but I found the best example to be this one:
(https://github.com/kylejablonski/InterfaceDemo),
which uses two interfaces, one to communicate from Frag A to Activity, and another one to communicate from Activity to Frag B. But I have a serious problem -
Currently, clicking both the "clear portfolio" and "add stock" to portfolio buttons in Frag A result in an empty screen in Frag B, which means something is being called yet new data is not being displayed/associated with the Adapter
Activity (https://github.com/EXJUSTICE/Investr/blob/master/app/src/main/java/com/xu/investo/ViewHolderActivity.java)
public class ViewHolderActivity extends AppCompatActivity implements CommunicateToActivity,CommunicateToFragment{
//Job of ViewHolderActivity is to allow swiping between list and MainFragment/Fragment
TabLayout tablayout;
ViewPager viewPager;
List<HistoricalQuote> historicaldata;
Bundle bundle;
Adapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_holder);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager =(ViewPager)findViewById(R.id.viewpager);
tablayout= (TabLayout)findViewById(R.id.tabs);
tablayout.setupWithViewPager(viewPager);
setupViewPager(viewPager);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
//----------------------- Interface code-----------
#Override
public void communicateup(){
communicatedown();
//call communicate down STRAIGHT, since we call it from mainfrag
}
#Override
public void communicatedown(){
//This line works
ListFragment currentFragment =(ListFragment)adapter.instantiateItem(viewPager,1);
currentFragment.refreshUI();
}
private void setupViewPager(ViewPager viewPager) {
adapter = new Adapter(getSupportFragmentManager());
adapter.addFragment(new MainFragment(), "Add Stock");
adapter.addFragment(new ListFragment(), "Portfolio");
viewPager.setAdapter(adapter);
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public Adapter(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);
}
}
Frag A (MainFragment)
(https://github.com/EXJUSTICE/Investr/blob/master/app/src/main/java/com/xu/investo/MainFragment.java)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view =inflater.inflate(R.layout.content_main,container,false);
stocknames = new ArrayList<String>();
stocktickers = new ArrayList<String>();
tinyDB = new TinyDB(getContext());
/*
menu.setDisplayShowHomeEnabled(true);
//menu.setLogo("INSERT LOGO HERE");
menu.setDisplayUseLogoEnabled(true);
menu.setTitle(" Stock Selector");
*/
fetch =(Button) view.findViewById(R.id.fetchBtn);
enterID =(EditText)view.findViewById(R.id.enterID);
display =(TextView)view.findViewById(R.id.display);
mCalendar = Calendar.getInstance();
clear = (Button)view.findViewById(R.id.clearportfolio);
fetch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//TODO all the main page should do is add stocktickers and names to portfolio
//Fetch id and the dates
id =enterID.getText().toString();
/*to = Calendar.getInstance();
from = Calendar.getInstance();
to.setTime(dateto);
from.setTime(datefrom);
*/
FetchXDayData getData = new FetchXDayData();
getData.execute(id);
}
});
clear.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
tinyDB.clear();
recyclerinterface.communicateup();
}
});
return view;
}
//----------------------------INTERFACE CODE
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
recyclerinterface = (CommunicateToActivity) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement RecyclerUpdateInterface");
}
}
///-------End of Oncreate---------------------------------------------------------------
//Called by AsyncTask, moving result to main thread
public void moveResultToUI(Stock result){
this.stock = result;
Toast.makeText(getActivity(),"Stock "+stock.getName()+" successfully added to portofolio",Toast.LENGTH_LONG).show();
//reverse the list of course, stock names and tickrs to portfolio
stocknames.add(stock.getName());
stocktickers.add(stock.getSymbol());
/*DEBUG Test code, Test. 30012017 WORKS
for (int i =0;i<historicaldata.size();i++){
HistoricalQuote current = historicaldata.get(i);
Toast toast = Toast.makeText(this,current.getClose().toString(),Toast.LENGTH_SHORT);
toast.show();
}
*/
//
if (stock != null){
display.setText("Name: "+stock.getName() +"\n"+"Price: "+ stock.getQuote().getPrice()+"\n"+ "Change(%)"+stock.getQuote().getChangeInPercent());
/*SMA = getSMA(10);
decision=checkSimpleCrossover(SMA,stock.getQuote().getPrice().longValue());
decisionView.setText("SMA: " + SMA + "\n"+decision);
*/
tinyDB.putListString("names",stocknames);
tinyDB.putListString("tickers",stocktickers);
//call interface activity comming up to Activity, then down to next fragment
recyclerinterface.communicateup();
}else{
Toast error = Toast.makeText(getActivity(),"Network Problem",Toast.LENGTH_SHORT);
error.show();
}
}
Frag B (ListFragment)
(https://github.com/EXJUSTICE/Investr/blob/master/app/src/main/java/com/xu/investo/ListFragment.java)
public class ListFragment extends Fragment {
private HistoricalQuote[] hisstocks;
private Stock[] stocks;
private RecyclerView recyclerView;
private StockAdapter mAdapter;
public ArrayList<String> stocknames;
public ArrayList<String>stocktickers;
TinyDB tinyDB;
#Override
public void onCreate(Bundle savedInstanceState){
//exists only to set the options menu
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
//fetching arraylists
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.content_list, container, false);
//Convert the arraylist into an array for arrayadapter
stocknames = new ArrayList<String>();
stocktickers = new ArrayList<String>();
tinyDB = new TinyDB(getContext());
stocknames = tinyDB.getListString("names");
stocktickers= tinyDB.getListString("tickers");
if (!stocknames.isEmpty()){
for (int i =0;i<stocknames.size();i++){
Toast toast= Toast.makeText(getActivity(),stocknames.get(i),Toast.LENGTH_SHORT);
toast.show();
}
}
recyclerView = (RecyclerView)view.findViewById(R.id.recylerView);
recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.HORIZONTAL));
//http://stackoverflow.com/questions/24618829/how-to-add-dividers-and-spaces-between-items-in-recyclerview
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setItemAnimator(new DefaultItemAnimator());
//layoutManager necessary because it positions views on screen, in this case linearly
if (stocknames.isEmpty() ||stocknames ==null){
recyclerView.setVisibility(View.GONE);
}else{
updateUI();
}
return view;
}
public void refreshUI(){
stocknames.clear();
stocktickers.clear();
stocknames = tinyDB.getListString("names");
stocktickers= tinyDB.getListString("tickers");
if (mAdapter == null) {
mAdapter = new StockAdapter(stocknames,stocktickers);
recyclerView.setAdapter(mAdapter);
} else {
recyclerView.invalidate();
mAdapter.notifyDataSetChanged();
}
}
public void updateUI() {
//updateUI must be called EXPLICITLY!
stocknames = tinyDB.getListString("names");
stocktickers= tinyDB.getListString("tickers");
if (mAdapter == null) {
mAdapter = new StockAdapter(stocknames,stocktickers);
recyclerView.setAdapter(mAdapter);
} else {
mAdapter.notifyDataSetChanged();
}
}
private class StockAdapter extends RecyclerView.Adapter<StockHolder>{
private ArrayList<String>stocknames;
private ArrayList<String>stocktickers;
public StockAdapter(ArrayList<String>names,ArrayList<String> tickers){
this.stocknames=names;
this.stocktickers=tickers;
}
#Override
public StockHolder onCreateViewHolder(ViewGroup parent, int viewType){
LayoutInflater layoutinflater = LayoutInflater.from(getActivity());
View view= layoutinflater.inflate(R.layout.row,parent,false);
return new StockHolder (view);
}
//Bind datato stockholder depending on position in arraylist
public void onBindViewHolder(StockHolder holder, int position){
String stockname = stocknames.get(position);
String stockticker =stocktickers.get(position);
holder.bindStock(stockname,stockticker);
}
#Override
public int getItemCount (){
return stocknames.size();
}
}
private class StockHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private String stockname;
private String stockticker;
private TextView nametextView;
private TextView tickertextView;
public StockHolder(View itemView){
super(itemView);
itemView.setOnClickListener(this);
nametextView =(TextView)itemView.findViewById(R.id.name);
tickertextView= (TextView)itemView.findViewById(R.id.ticker);
}
#Override
public void onClick(View v){
Intent launchGraph= new Intent(v.getContext(),GraphActivity.class);
launchGraph.putExtra("stockticker",stockticker);
launchGraph.putExtra("stockname",stockname);
startActivity(launchGraph);
//Animations?
}
//Actual binder method, maybe add a current
public void bindStock(String stocknom, String stocktick){
this.stockname=stocknom;
this.stockticker = stocktick;
nametextView.setText(stockname);
tickertextView.setText(stockticker);
}
}
Thanks in advance.
EDIT: Solved issue by creating a new adapter and linking it to new arraylists pulled from the TinyDB, thereby effectively swapping adapters.
Solved the issue by creating a whole new RecyclerView adapter, to which new arraylist data was binded to, and the whole recyclerview was then set to use this new adapter. All of this was done in a single step from FragA, using interfaces shown in the code in the solution.
Method shown below:
public void refreshUI(){
tinyDB = null;
tinyDB = new TinyDB(getContext());
newnames = tinyDB.getListString("names");
newtickers= tinyDB.getListString("tickers");
mAdapter = new StockAdapter(newnames,newtickers);
recyclerView.setAdapter(mAdapter);
}

Issue viewing Fragment through tabs

I've tried to post a similar questions without any answer, though of posting again.
The issue I am having is with viewing Fragment through Tabs, I have 3 Tabs in an AppBar displayed with ViewPager & FragmentPagerAdapter.
The problem is when the activity start, one of the tabs does not behave in a consistent way, upon logging in to the app & activity for the first time it would display the content of the Fragment ( Video clips ) but during switching between activities in the app, and going back to the Activity containing the 3 Tabs, choosing that specific Tab does not display anything, althou in the Logcat, i could tell it is retrieving Data related to the Vid Clip that should be displayed, also going back that Activity i see in the Logcat that even when i choose a different Tab, ( pictures ) Data from the 2 others Tab is being retrieved !?
The setup is as follows;
Main activity;
public class Member extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.member);
Firebase.setAndroidContext(this);
ButterKnife.bind(this);
// Adding Toolbar to Main screen
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Setting ViewPager for each Tabs
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
// Set Tabs inside Toolbar
TabLayout tabs = (TabLayout) findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getSupportFragmentManager());
adapter.addFragment(new PicContentMMFragment(), "Pictures");
adapter.addFragment(new VidContentFragment(), "Videos");
adapter.addFragment(new LocationsContentFragment(), "Locations");
viewPager.setAdapter(adapter);
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public Adapter(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);
}
}
Well, as one of the users commented on the post pointed out that the problem could be from the specific fragemnt itself and not the way Tabs and Viewpager following is the VidContentFragment;
public class VidContentFragment extends android.support.v4.app.Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final RecyclerView recyclerView = (RecyclerView) inflater.inflate(
R.layout.recycler_view, container, false);
Log.i("MyTag_onCreate","vidContentFragment_Loaded");
ContentAdapter adapter = new ContentAdapter(recyclerView.getContext());
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return recyclerView;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public VideoView video;
public TextView authorName;
public TextView ratingValue;
public TextView locationValue;
public RatingBar ratingB;
public Button submitRating;
public LinearLayout placeNameHolder;
public int newRating;
public ViewHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.item_card_vid, parent, false));
authorName = (TextView) itemView.findViewById(R.id.card_title);
ratingValue = (TextView) itemView.findViewById(R.id.ratingValue);
locationValue = (TextView) itemView.findViewById(R.id.locationValue);
video = (VideoView) itemView.findViewById(R.id.placeVid);
ratingB = (RatingBar)itemView.findViewById(R.id.ratingBarMM);
ratingB.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
newRating = (int) ratingB.getRating();
}
});
submitRating = (Button) itemView.findViewById(R.id.submitRatingMM);
submitRating.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
public_id = publicID[getPosition()];
Log.i("MyTag_Rating",public_id);
public static class ContentAdapter extends RecyclerView.Adapter<ViewHolder> {
// Set numbers of List in RecyclerView.
private Context mContext;
public ContentAdapter(Context context) {
this.mContext = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()), parent);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.authorName.setText(author[position]);
holder.ratingValue.setText(ratingV[position]);
holder.locationValue.setText(locationV[position]);
Uri video = Uri.parse(mVideos[position]);
holder.video.setVideoURI(video);
holder.video.setMediaController(new MediaController(mContext));
holder.video.requestFocus();
holder.video.seekTo(1000);
holder.video.pause();
try{
String url1 = mVideos[position];
URL ulrn = new URL(url1);
HttpURLConnection con = (HttpURLConnection)ulrn.openConnection();
InputStream is = con.getInputStream();
Bitmap bmp = BitmapFactory.decodeStream(is);
if (null != bmp)
Palette.generateAsync(bmp, new Palette.PaletteAsyncListener() {
public void onGenerated(Palette palette) {
int bgColor = palette.getVibrantColor(mContext.getResources().getColor(android.R.color.black));
holder.placeNameHolder.setBackgroundColor(bgColor);
}
});
else
Log.e("MyTag_BMP","The Bitmap is NULL");
}catch (Exception e){
}
}
#Override
public int getItemCount() {
return LENGTH;
}
}
}
Some part of the code (related to retrieving data from firebase) is left out to shorten it.
Although the other 2 fragments are organized the same way, the behavior of this fragment is inconsistent ?
Here is the version of the adapter with viewholder that I have for a recyclerview you said would likely be helpful. You'll need to refactor to adjust for your situation. I have gutted it mostly to help show just the bare interactions.
public class AnimalAdapter extends RecyclerView.Adapter<AnimalAdapter.AnimalCardViewHolder>{
private List<Animals> animalList;
public AnimalAdapter adapter = this;
Context context;
public AnimalAdapter(List<Animals> animalList, Context context) {
this.animalList = animalList;
this.context = context;
this.setInterface((iAdapterInterface) context);
}
#Override
public int getItemCount() {
return animalList.size();
}
#Override
public void onBindViewHolder(AnimalCardViewHolder holder, int position) {
Animals animal = animalList.get(position);
holder.txtName.setText(animal.getName());
holder.txtType.setText(animal.getType());
}
#Override
public AnimalCardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.animal_card_view, parent, false);
return new AnimalCardViewHolder(itemView);
}
public class AnimalCardViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
protected TextView txtName;
protected TextView txtType;
public AnimalCardViewHolder(final View itemView) {
super(itemView);
txtName = (TextView) itemView.findViewById(R.id.txtName);
txtType = (TextView) itemView.findViewById(R.id.txtType);
imgClose = (ImageView) itemView.findViewById(R.id.txtRemove);
listItem = itemView.findViewById(R.id.list_item);
listItem.setOnClickListener(this);
imgClose.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.txtRemove:
break;
case R.id.list_item:
break;
}
}
}
}

How to sort list in RecyclerView which is been populated through ViewPager

I have a fragment(say X) which contain ViewPager and TabLayout and i am passing a fragment((say Y)with a list) three times to adapter of this viewpager but every time list is sorted by some parameter.
Y fragment contain RecyclerView. And i am passing that list to the adapter of this RecyclerView.
I am able to populate all the 3 tabs with fragment.But list inside recyclerview is not sorted.Only last tab with recyclerview was comming sorted
Please help me to find shortcoming of the code.
X Fragment
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = getLayoutInflater(savedInstanceState).inflate(R.layout.available_bus_fragment, null);
tabLayout = (TabLayout) rootView.findViewById(R.id.tabs);
viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());
List<Bus> departureTimeList = mBusList;
Collections.sort(departureTimeList, new Comparator<Bus>() {
#Override
public int compare(Bus lhs, Bus rhs) {
return lhs.getDepartureTime().compareTo(rhs.getDepartureTime());
}
});
Fragment departureFragment = new AvailableRecyclerViewFragment(departureTimeList);
if (getArguments()!= null) {
departureFragment.setArguments(getArguments());
}
adapter.addFragment(departureFragment, "Departure");
List<Bus> durationTimeList = mBusList;
Collections.sort(durationTimeList, new Comparator<Bus>() {
#Override
public int compare(Bus lhs, Bus rhs) {
return lhs.getDurationForSorting() - rhs.getDurationForSorting();
}
});
Fragment durationFragment = new AvailableRecyclerViewFragment(durationTimeList);
if (getArguments() != null) {
durationFragment.setArguments(getArguments());
}
adapter.addFragment(durationFragment, "Duration");
List<Bus> priceList = mBusList;
Collections.sort(priceList, new Comparator<Bus>() {
#Override
public int compare(Bus lhs, Bus rhs) {
return lhs.getFares() - rhs.getFares();
}
});
Fragment priceFragment = new AvailableRecyclerViewFragment(priceList);
if (getArguments()!= null) {
priceFragment.setArguments(getArguments());
}
adapter.addFragment(priceFragment, "Fare");
viewPager.setAdapter(adapter);
adapter.notifyDataSetChanged();
tabLayout.setupWithViewPager(viewPager);
return rootView;
}
This is my adapter of viewpager.
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragments = new ArrayList();
private final List<String> mFragmentTitles = new ArrayList();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
Y fragment (AvailableRecyclerViewFragment.java)
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = getLayoutInflater(savedInstanceState).inflate(R.layout.available_list_fragment, null);
recycler_view = (RecyclerView) rootView.findViewById(R.id.recycler_view);
adapter = new CustomRecyclerViewAdapter(getActivity(), mBusList);
adapter.notifyDataSetChanged();
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
recycler_view.setLayoutManager(mLayoutManager);
recycler_view.setItemAnimator(new DefaultItemAnimator());
recycler_view.setHasFixedSize(true);
recycler_view.setAdapter(adapter);
return rootView;
}
Adapter for Recyclerview
public class CustomRecyclerViewAdapter extends RecyclerView.Adapter<CustomRecyclerViewAdapter.CustomViewHolder> {
private List<Bus> dataList;
Context mContext;
public CustomRecyclerViewAdapter(Context context, List<Bus> list) {
dataList = list;
mContext = context;
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
public TextView tv_departureTime;
public TextView tv_arrivalTime;
public TextView tv_duration;
public TextView tv_price;
public TextView tv_availableSeats;
public TextView tv_travels;
public TextView tv_busType;
public CustomViewHolder(View view) {
super(view);
tv_departureTime = (TextView) view.findViewById(R.id.tv_departureTime);
tv_arrivalTime = (TextView) view.findViewById(R.id.tv_arrivalTime);
tv_duration = (TextView) view.findViewById(R.id.tv_duration);
tv_price = (TextView) view.findViewById(R.id.tv_price);
tv_availableSeats = (TextView) view.findViewById(R.id.tv_availableSeats);
tv_travels = (TextView) view.findViewById(R.id.tv_travels);
tv_busType = (TextView) view.findViewById(R.id.tv_busType);
}
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.custom_list_row, parent, false);
final Animation anim = AnimationUtils.loadAnimation(mContext, android.R.anim.slide_in_left);
itemView.setAnimation(anim);
return new CustomViewHolder(itemView);
}
#Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
Bus bus = dataList.get(position);
holder.tv_arrivalTime.setText("" + bus.getArrivalTime());
String[] data = bus.getDuration().split(":");
holder.tv_departureTime.setText("" + bus.getDepartureTime());
holder.tv_duration.setText("" + data[0] + "hr " + data[1] + "min");
if (bus.getFareList() != null) {
String fare = "";
for (FareDetails tempFare : bus.getFareList()) {
fare = fare + tempFare.getTotalFare() + ("/");
}
holder.tv_price.setText("" + fare.substring(0, fare.length() - 1).toString());
} else {
holder.tv_price.setText("" + bus.getFares());
}
holder.tv_availableSeats.setText("" + bus.getAvailableSeats() + " seats");
holder.tv_travels.setText(bus.getTravels());
holder.tv_busType.setText(bus.getBusType());
}
#Override
public int getItemCount() {
return dataList.size();
}
}
inside of Fragment X(where your ViewPager is) call method setOnPageChangeListener:
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
viewPagerAdapter.notifyDataSetChanged();
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
As you see inside of onPageSelected() call notifyDataSetChanged for your viewpager adapter. Then it should sort fragment that you're on.

Update RecyclerView in a fragment from another fragment onClick

I have a ViewPager with two Fragments with RecyclerViews that show Locations and Items. Each location contains different items. Now I want to update the recyclerView inside ItemsFragment when a location is selected in LocationsFragment. I set onClick method to location element to update the activeLocation field but I don't know how to refresh the data in items' recyclerView.
I would need to supply a new List object I get from getItems() into the adapter, but the adapter is null whenever ItemsFragment loses focus or make it so the fragment is recreated every time the activeLocation changes.
The only time it refreshes now is when the ItemsFragment's onCreateView is called. The list updates, because a new ItemAdapter is created and getItems() is called inside constructor. But this only happens when I scroll to 4th tab and back, so that the itemsFragment (2nd) is cleared from memory and reloaded.
Activity:
public class MainActivity extends AppCompatActivity implements MaterialTabListener {
MaterialTabHost tabHost;
ViewPager pager;
ViewPagerAdapter adapter;
private final int[] icons = {R.drawable.icon_locations, R.drawable.icon_items};
public static Location activeLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
Realm.setDefaultConfiguration(new RealmConfiguration.Builder(this).build());
Realm realm = Realm.getDefaultInstance();
activeLocation = realm.where(Location.class).findFirst();
pager = (ViewPager) findViewById(R.id.view_pager);
adapter = new ViewPagerAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
tabHost = (MaterialTabHost) this.findViewById(R.id.materialTabHost);
for (int i = 0; i < adapter.getCount(); i++) {
tabHost.addTab(
tabHost.newTab()
.setIcon(ResourcesCompat.getDrawable(getResources(), icons[i], null)).setTabListener(this)
);
}
}
ViewPager:
class ViewPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = {"Locations", "Items"};
private final int[] ICONS = {R.drawable.icon_locations, R.drawable.icon_items};
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position) {
case FragmentType.LOCATIONS: {
fragment = LocationsFragment.newInstance();
break;
}
case FragmentType.ITEMS: {
fragment = ItemsFragment.newInstance();
break;
}
}
return fragment;
}
}
LocationsFragment:
public class LocationsFragment extends Fragment {
private RecyclerView recyclerView;
private LocationAdapter adapter;
public static LocationsFragment newInstance() {
return new LocationsFragment();
}
public LocationsFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragment_locations, container, false);
recyclerView = (RecyclerView) layout.findViewById(R.id.locations_recycler_view);
adapter = new LocationAdapter(getActivity(), getLocations());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return layout;
}
public List<Location> getLocations() {
List<Location> locations;
Log.d("null act", getActivity() == null? "null" : "not null");
Realm realm = Realm.getDefaultInstance();
locations = realm.where(Location.class).findAll();
return locations;
}
}
LocationAdapter:
public class LocationAdapter extends RecyclerView.Adapter<LocationAdapter.LocationHolder> {
List<Location> list = Collections.emptyList();
Context context;
private LayoutInflater inflater;
public LocationAdapter(Context context, List<Location> list) {
this.list = list;
this.context = context;
inflater = LayoutInflater.from(context);
}
#Override
public LocationHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.card_location, parent, false);
return new LocationHolder(view);
}
#Override
public void onBindViewHolder(final LocationHolder holder, int position) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("clicked", "Location " + location.getId() + " " + location.getName() + " pressed");
if (context instanceof MainActivity) {
MainActivity mainActivity = (MainActivity) context;
MainActivity.activeLocation = location;
mainActivity.setFragment(1); //this changes the title on actionBar and tab highlights
}
}
});
}
ItemsFragment and ItemAdapter are the same as Locations.

Categories

Resources