Delayed load of elements in TabLayout Android Studio error - java

Problem
When I run on the phone, I press lib item(Bottom Menu Library Item). It shows correctly. Then, when I change the fragment (ex: Home Fragment(Bottom Menu Home Item) and reselect lib item(Bottom Menu Library Item) recycler view inside it disappears. To solve I need to wait or relaunch the app. Below my code in Java.
My Fragment Page Adapter
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
import java.util.List;
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> lstFragment = new ArrayList<>(); // this line can cause crashes
private final List<String> lstTitles = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
return lstFragment.get(i);
}
#Override
public int getCount() {
return lstFragment.size();
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return lstTitles.get(position);
}
public void AddFragment(Fragment fragment, String Title){
lstFragment.add(fragment); // this line can cause crashes
lstTitles.add(Title);
}
}
RecyclerView Adapter code
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder>{
Context mContext;
List<Focus> mData;
public RecyclerViewAdapter(Context mContext, List<Focus> mData) {
this.mContext = mContext;
this.mData = mData;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(mContext).inflate(R.layout.card_item_home, viewGroup, false);
MyViewHolder myViewHolder = new MyViewHolder(v);
return myViewHolder;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
myViewHolder.txtTitle.setText(mData.get(i).getTitle());
myViewHolder.imgView.setImageResource(mData.get(i).getImage());
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView txtTitle;
ImageView imgView;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
txtTitle = itemView.findViewById(R.id.card_view_title);
imgView = itemView.findViewById(R.id.card_view_image);
}
}
}
Main Activity Code
public class MainActivity extends AppCompatActivity {
private Button music_ImageView;
private TextView music_title, music_state, music_duration, music_currentTime;
private SeekBar music_playerSeekbar;
private MediaPlayer mediaPlayer;
private Handler handler = new Handler();
private BottomNavigationView bottomNav;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bottomNav = findViewById(R.id.bottom_nav_menu);
bottomNav.setOnNavigationItemSelectedListener(navListener);
/**-------------------------------------------------------------------------**/
music_ImageView = (Button) findViewById(R.id.music_player_btn);
music_currentTime = (TextView) findViewById(R.id.textCurrentTime);
music_duration = (TextView) findViewById(R.id.textTotalDuration);
music_playerSeekbar = (SeekBar) findViewById(R.id.music_player_seekbar);
music_title = (TextView) findViewById(R.id.music_player_title);
music_state = (TextView) findViewById(R.id.music_player_state);
mediaPlayer = new MediaPlayer();
music_playerSeekbar.setMax(100);
music_ImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()) {
handler.removeCallbacks(Updater);
mediaPlayer.pause();
music_ImageView.setBackgroundResource(R.drawable.ic_pause);
music_state.setText("Pause");
} else {
mediaPlayer.start();
music_ImageView.setBackgroundResource(R.drawable.ic_play);
music_state.setText("Playing");
updateSeekBar();
}
}
});
prepareMediaPlayer();
music_playerSeekbar.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
SeekBar seekBar = (SeekBar) v;
int playPosition = (mediaPlayer.getDuration() / 100) * seekBar.getProgress();
mediaPlayer.seekTo(playPosition);
music_currentTime.setText(milliSecondsToTimer(mediaPlayer.getCurrentPosition()));
return true;
}
});
mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
music_playerSeekbar.setSecondaryProgress(percent);
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
music_playerSeekbar.setProgress(0);
music_ImageView.setBackgroundResource(R.drawable.ic_play);
music_currentTime.setText(R.string.zero);
music_duration.setText(R.string.zero);
mediaPlayer.reset();
prepareMediaPlayer();
}
});
if(savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, new HomeFragment())
.commit();
}
ActionBar actionBar = getSupportActionBar();
actionBar.setElevation(0);
actionBar.setTitle("Brain.Music");
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
RelativeLayout muz = (RelativeLayout)findViewById(R.id.music_player);
ActionBar actionBar;
switch (item.getItemId()){
case R.id.menu_home: {
bottomNav.getMenu().getItem(1).setIcon(R.drawable.ic_favorite_border);
selectedFragment = new HomeFragment();
actionBar = getSupportActionBar();
actionBar.setTitle("Brain.Music");
muz.setVisibility(View.VISIBLE);
}
break;
case R.id.menu_fav: {
item.setIcon(R.drawable.ic_favorite);
selectedFragment = new FavFragment();
actionBar = getSupportActionBar();
actionBar.setTitle("Favorite");
muz.setVisibility(View.VISIBLE);
}
break;
case R.id.menu_lib: {
bottomNav.getMenu().getItem(1).setIcon(R.drawable.ic_favorite_border);
selectedFragment = new LibFragment();
actionBar = getSupportActionBar();
actionBar.setTitle("Library");
}
break;
}
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, selectedFragment)
.commit();
return true;
}
};
private void prepareMediaPlayer(){
try{
mediaPlayer.setDataSource("");
mediaPlayer.prepare();
music_duration.setText(milliSecondsToTimer(mediaPlayer.getDuration()));
}catch (Exception exception){
Toast.makeText(this, exception.getMessage(), Toast.LENGTH_SHORT).show();
}
}
private Runnable Updater = new Runnable() {
#Override
public void run() {
updateSeekBar();
long currentDuration = mediaPlayer.getDuration();
music_currentTime.setText(milliSecondsToTimer(currentDuration));
}
};
private void updateSeekBar(){
if ( mediaPlayer.isPlaying()){
music_playerSeekbar.setProgress((int)((float)mediaPlayer.getCurrentPosition() / mediaPlayer.getDuration() * 100));
handler.postDelayed(Updater, 1000);
}
}
private String milliSecondsToTimer(long milliSeconds){
String timerString = "";
String secondsString = "";
int hours = (int)(milliSeconds / (1000 * 60 * 60));
int minutes = (int)(milliSeconds % (1000 * 60 * 60) / (1000 * 60));
int seconds = (int)(milliSeconds % (1000 * 60 * 60) % ((1000 * 60)) / 1000);
if ( hours > 0 ){
timerString = hours + ":";
}
if ( seconds < 10 ){
secondsString = "0" + seconds;
}else{
secondsString = "" + seconds;
}
timerString = timerString + minutes + ":" + secondsString;
return timerString;
}
}
Lib Fragment
import android.app.ActionBar;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
public class LibFragment extends Fragment {
View v;
private TabLayout tabLayout;
private ViewPager viewPager;
private ViewPagerAdapter viewPagerAdapter;
private BottomNavigationView btnNav;
private Fragment fragment;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_lib, container, false);
tabLayout = (TabLayout)v.findViewById(R.id.tabLayout);
viewPager = (ViewPager)v.findViewById(R.id.viewPager);
/// Adding fragments
/// Adapter Setting
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setTabMode(TabLayout.MODE_FIXED);
tabLayout.getTabAt(2).select();
return v;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewPagerAdapter = new ViewPagerAdapter(getFragmentManager());
viewPagerAdapter.AddFragment(new FragmentFocus(), "Focus"); // `FragmentFocus()` should be inside `FragmentPagerAdapter.getItem()`
viewPagerAdapter.AddFragment(new FragmentSleep(), "Sleep"); // `FragmentSleep()` should be inside `FragmentPagerAdapter.getItem()`
viewPagerAdapter.AddFragment(new FragmentRelax(), "Relax"); // `FragmentRelax()` should be inside `FragmentPagerAdapter.getItem()`
}
}
Fragment Focus Code
package com.xcube.demo_nav;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import java.util.ArrayList;
import java.util.List;
public class FragmentFocus extends Fragment {
View v;
private RecyclerView recyclerView;
private List<Category> lstCategory;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.focus_fragment, container, false);
recyclerView = (RecyclerView)v.findViewById(R.id.recyclerView_library);
CategoryRecyclerView recyclerViewAdapter = new CategoryRecyclerView(getContext(), lstCategory);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(recyclerViewAdapter);
return v;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lstCategory = new ArrayList<>();
lstCategory.add(new Category("Lo-FI", R.drawable.icon_focus));
lstCategory.add(new Category("Lo-FI", R.drawable.icon_focus));
lstCategory.add(new Category("Forest", R.drawable.icon_relax));
}
}

Related

Previous fragment is not being replaced when selecting a navigation menu item

I have a navigation drawer activity that shows a list of restaurants based on some data passed from the previous activity as the home fragment. On clicking on one of the restaurant cards, another fragment is created which shows the details of the restaurant. All of these fragments have the navigation drawer activity as their parent activity. When I am selecting the home fragment menu on the navigation item, the fragment does not replace the previous fragment rather it superimposes itself on the previous fragment. I will add some images to explain the scenario.
This is my Navigation Drawer -
This is the home fragment containing the restaurant lists -
This is the fragment showing the restaurant details when clicking on one restaurant -
When I press the home item on the navigation drawer from the restaurant detail screen this happens -
Here is the relevant code-
MainActivity2.class
package com.example.wfdmockapp;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.Menu;
import com.example.wfdmockapp.ui.home.HomeFragment;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.navigation.NavigationView;
import androidx.annotation.NonNull;
import androidx.core.view.GravityCompat;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import com.example.wfdmockapp.databinding.ActivityMain2Binding;
public class MainActivity2 extends AppCompatActivity{
private static final String TAG = "MainActivity2";
private String cityId = null;
private String townId = null;
private DrawerLayout drawer;
private AppBarConfiguration mAppBarConfiguration;
private ActivityMain2Binding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMain2Binding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
setSupportActionBar(binding.appBarMain.toolbar);
binding.appBarMain.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();
}
});
drawer = binding.drawerLayout;
NavigationView navigationView = binding.navView;
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home)
.setOpenableLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
Intent getRestaurantIntent = getIntent();
cityId = getRestaurantIntent.getStringExtra("cityId");
townId = getRestaurantIntent.getStringExtra("townId");
Bundle bundle = new Bundle();
bundle.putString("cityId",cityId);
bundle.putString("townId",townId);
System.out.println(cityId+" "+townId);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.setReorderingAllowed(true)
.replace(R.id.nav_host_fragment_content_main, HomeFragment.class, bundle)
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_activity2, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
}```
HomeFragment.Java
public class HomeFragment extends Fragment {
private static final String TAG = "HomeFragment";
private RequestQueue mRequestQueue;
private String cityId = null;
private String townId = null;
private String ShopListUrl= Global.base_url+"v1/get-shop-list";
private ArrayList<Shop> shops = new ArrayList<>();
private RecyclerView recyclerView;
private ShopRecyclerViewAdapter adapter;
private GifImageView loadingAnimation;
#Override
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
Bundle bundle = this.getArguments();
if(bundle!=null){
cityId = bundle.getString("cityId");
townId = bundle.getString("townId");
System.out.println(cityId+" "+townId);
}
return inflater.inflate(R.layout.fragment_home, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mRequestQueue = Volley.newRequestQueue(getContext());
loadingAnimation = view.findViewById(R.id.loading_animation);
initRecyclerView(view);
getShopList();
}
public void getShopList(){
Log.d(TAG,"Creating Shop Object");
JSONObject shopInfoObject = new JSONObject();
try {
shopInfoObject.put("city",cityId);
shopInfoObject.put("town",townId);
shopInfoObject.put("shop_type",null);
shopInfoObject.put("api_token","a4e426652ed46154d67c8af897e77022");
} catch (JSONException e) {
e.printStackTrace();
}
Log.d(TAG,"JSON Shop Object created,collecting response for Request");
JsonObjectRequest ShopListRequest = new JsonObjectRequest(Request.Method.POST, ShopListUrl, shopInfoObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.d(TAG,"Getting response");
JSONArray shopList = response.getJSONArray("shopList");
for(int i=0;i<shopList.length();i++){
JSONObject jsonObject = shopList.getJSONObject(i);
Shop shop = new Shop();
shop.setShopId(jsonObject.getString("shopId"));
shop.setName(jsonObject.getString("title"));
shop.setTypeName(jsonObject.getString("typeName"));
shop.setLogo(Global.base_imageUrl+jsonObject.getString("logo"));
shop.setSpecialOffer(jsonObject.getString("special_offer_text"));
shop.setDeliveredBy(jsonObject.getInt("deliveredBy"));
shop.setMixMatch(jsonObject.getInt("mixAndMatch"));
shop.setDeliveryFee(jsonObject.getString("delivery_fee"));
shop.setMinimumOrder(jsonObject.getString("minOrder"));
shop.setPaymentModeText(jsonObject.getString("paymentModeText"));
shop.setShopStatus(jsonObject.getString("currentStatus"));
shops.add(shop);
}
adapter.notifyDataSetChanged();
Log.d(TAG,"Shop data fetched");
loadingAnimation.setVisibility(View.GONE);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof TimeoutError) {
Global.displayToast("Timeout! Please Try Again",getContext());
}
}
});
ShopListRequest.setRetryPolicy(new DefaultRetryPolicy(
6000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
mRequestQueue.add(ShopListRequest);
}
public void initRecyclerView(View view){
recyclerView = view.findViewById(R.id.recycler_view);
adapter = new ShopRecyclerViewAdapter(shops,getContext(),this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
}
}```
RestaurantDetailsFragment.Java
package com.example.wfdmockapp;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.example.wfdmockapp.models.Restaurant;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import de.hdodenhof.circleimageview.CircleImageView;
import pl.droidsonroids.gif.GifImageView;
public class RestaurantDetailsFragment extends Fragment {
private static final String TAG = "RestaurantDetails";
private RequestQueue mRequestQueue;
private Restaurant restaurant = new Restaurant();
private String getShopDetailsUrl = Global.base_url+"v1/get-shop-details";
private String shopId;
private ArrayList<String> FoodTypeList;
//UI Components
private TextView name;
private TextView typeName;
private TextView shopMessage;
private TextView minOrder;
private TextView paymentModeText;
private RecyclerView foodTypeListRecyclerView;
private FoodTypeRecyclerViewAdapter adapter;
private TextView deliveryText;
private TextView deliveryFee;
private TextView deliveryTime;
private TextView shopStatus;
private CircleImageView shopLogo;
private LinearLayout shopDetailsView;
private GifImageView loadingAnimation;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
shopId = getArguments().getString("shopId");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_restaurant_details, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
loadingAnimation = view.findViewById(R.id.shop_details_loading_animation);
shopDetailsView = view.findViewById(R.id.shop_view);
shopDetailsView.setVisibility(View.GONE);
FoodTypeList = restaurant.getFoodTypeList();
mRequestQueue = Volley.newRequestQueue(getContext());
initRecyclerView(view);
initUIComponents(view);
showRestaurantDetails(view);
}
public void showRestaurantDetails(View view){
JSONObject ShopInfoObject = new JSONObject();
try {
ShopInfoObject.put("api_token","cadbc10d3aa13257cd7c69bb3d434d00");
ShopInfoObject.put("shopId",shopId);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest getShopDetailsRequest = new JsonObjectRequest(Request.Method.POST, getShopDetailsUrl, ShopInfoObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray shopDetails = response.getJSONArray("shop");
String deliveryTextResponse = response.getString("deliveryText");
restaurant.setDeliveryText(deliveryTextResponse);
for(int i=0;i<shopDetails.length();i++){
JSONObject shopJsonObject = shopDetails.getJSONObject(i);
restaurant.setName(shopJsonObject.getString("title"));
restaurant.setTypeName(shopJsonObject.getString("typeName"));
restaurant.setShop_message(shopJsonObject.getString("shop_message"));
String ImageUrl = Global.base_imageUrl+shopJsonObject.getString("logo");
restaurant.setLogo(ImageUrl);
restaurant.setMinOrder(shopJsonObject.getString("minOrder"));
restaurant.setStatus(shopJsonObject.getString("currentStatus"));
JSONArray foodTypeListJSONArray = shopJsonObject.getJSONArray("foodTypeList");
for(int j=0;j<foodTypeListJSONArray.length();j++){
JSONObject foodTypeListJSONObject = foodTypeListJSONArray.getJSONObject(j);
Log.d(TAG,foodTypeListJSONObject.getString("foodTypeName"));
restaurant.addFoodListItems(foodTypeListJSONObject.getString("foodTypeName"));
}
adapter.notifyDataSetChanged();
restaurant.setDelivery_fee(shopJsonObject.getString("delivery_fee"));
JSONObject deliveryHours = shopJsonObject.getJSONObject("deliveryHours");
String openingHours = deliveryHours.getString("openingHour");
String closingHours = deliveryHours.getString("closingHour");
restaurant.setDeliveryTime("Delivery: "+openingHours+" - "+closingHours);
restaurant.setPaymentModeText(shopJsonObject.getString("paymentModeText"));
setUIComponentValues(restaurant,view);
loadingAnimation.setVisibility(View.GONE);
shopDetailsView.setVisibility(View.VISIBLE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof TimeoutError) {
Global.displayToast("Timeout error!Please try again",getContext());
}
}
});
getShopDetailsRequest.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
mRequestQueue.add(getShopDetailsRequest);
}
public void initUIComponents(View view){
name = view.findViewById(R.id.shopName);
typeName = view.findViewById(R.id.shopTypename);
shopMessage = view.findViewById(R.id.shop_message);
minOrder = view.findViewById(R.id.min_order);
paymentModeText = view.findViewById(R.id.payment_Method);
deliveryFee = view.findViewById(R.id.min_delivery_fee);
deliveryText = view.findViewById(R.id.delivery_time_today);
deliveryTime = view.findViewById(R.id.shop_delivery_time);
shopLogo = view.findViewById(R.id.shopLogo);
shopStatus = view.findViewById(R.id.status);
}
public void setUIComponentValues(Restaurant restaurant,View view){
Glide.with(getContext()).load(restaurant.getLogo()).into(shopLogo);
name.setText(restaurant.getName());
typeName.setText(restaurant.getTypeName());
String message = restaurant.getShop_message();
System.out.println(message);
if(message.equals("")||message.equals("null")){
Log.d(TAG,"No shop message,hiding field");
LinearLayout shopMsgField = view.findViewById(R.id.shop_message_field);
shopMsgField.setVisibility(View.GONE);
}else{
shopMessage.setText(message);
}
minOrder.setText("\u20ac "+restaurant.getMinOrder()+" MIN ");
paymentModeText.setText(restaurant.getPaymentModeText());
deliveryFee.setText("Delivery \u20ac "+restaurant.getDelivery_fee());
String text = restaurant.getDeliveryText();
if(text.equals("null")||text.equals("")){
deliveryText.setVisibility(View.GONE);
}else{
deliveryText.setText(text);
}
deliveryTime.setText(restaurant.getDeliveryTime());
Global.setCurrentStatusText(restaurant.getStatus(),shopStatus);
}
public void initRecyclerView(View view){
foodTypeListRecyclerView = view.findViewById(R.id.FoodTypeRecyclerView);
adapter = new FoodTypeRecyclerViewAdapter(FoodTypeList,getContext());
foodTypeListRecyclerView.setAdapter(adapter);
foodTypeListRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
}
}```
ShopRecyclerViewAdapter.java
package com.example.wfdmockapp;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.wfdmockapp.models.Shop;
import java.io.FileNotFoundException;
import java.util.ArrayList;
public class ShopRecyclerViewAdapter extends RecyclerView.Adapter<ShopRecyclerViewAdapter.ViewHolder> {
private static final String TAG="ShopRecyclerViewAdapter";
private ArrayList<Shop> shops;
private Context mContext;
private Fragment fragment;
public ShopRecyclerViewAdapter(ArrayList<Shop> shops,Context mContext,Fragment fragment) {
this.shops = shops;
this.mContext = mContext;
this.fragment = fragment;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Log.d(TAG,"Reached onCreate");
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.shoplistitem,parent,false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Log.d(TAG,"Reached onBind");
try{
Glide.with(mContext).load(shops.get(position).getLogo()).into(holder.shopLogo);
}catch (Exception e){
Glide.with(mContext).load(R.drawable.shop_logo_base).into(holder.shopLogo);
}
holder.deliveryFee.setText("Delivery \u20ac "+shops.get(position).getDeliveryFee());
holder.minOrder.setText("\u20ac "+shops.get(position).getMinimumOrder()+" MIN ");
holder.paymentMethod.setText(shops.get(position).getPaymentModeText());
String status = shops.get(position).getShopStatus();
Global.setCurrentStatusText(status,holder.shopStatus);
holder.shopName.setText(shops.get(position).getName());
holder.shopTypeName.setText(shops.get(position).getTypeName());
String offerText = shops.get(position).getSpecialOffer();
if(!(offerText==null)){
holder.shopOffer.setText(offerText);
}else{
holder.offerSection.setVisibility(View.GONE);
}
int deliveredBy = shops.get(position).getDeliveredBy();
makeViewInvisible(holder.delivery_layout,deliveredBy);
int mixAndMatch = shops.get(position).getMixMatch();
makeViewInvisible(holder.mixMatchLayout,mixAndMatch);
holder.parent_layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Bundle bundle = new Bundle();
bundle.putString("shopId",shops.get(position).getShopId());
FragmentManager fm = fragment.getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTrans = fm.beginTransaction();
fragmentTrans.replace(R.id.nav_host_fragment_content_main,RestaurantDetailsFragment.class,bundle);
fragmentTrans.setReorderingAllowed(true);
fragmentTrans.addToBackStack(null);
fragmentTrans.commit();
}
});
}
#Override
public int getItemCount() {
return shops.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView shopLogo;
TextView shopName;
TextView shopTypeName;
TextView shopOffer;
TextView minOrder;
TextView deliveryFee;
TextView paymentMethod;
TextView shopStatus;
RelativeLayout offerSection;
RelativeLayout parent_layout;
RelativeLayout delivery_layout;
RelativeLayout mixMatchLayout;
public ViewHolder(#NonNull View itemView) {
super(itemView);
shopLogo = itemView.findViewById(R.id.shop_logo);
shopName = itemView.findViewById(R.id.shop_title);
shopTypeName = itemView.findViewById(R.id.shop_typename);
shopOffer = itemView.findViewById(R.id.offer_text);
offerSection = itemView.findViewById(R.id.offer_section);
minOrder = itemView.findViewById(R.id.shop_min_order);
deliveryFee = itemView.findViewById(R.id.deliver_fee);
shopStatus = itemView.findViewById(R.id.status);
paymentMethod = itemView.findViewById(R.id.shop_payment);
parent_layout = itemView.findViewById(R.id.parent_layout);
delivery_layout = itemView.findViewById(R.id.delivered_by);
mixMatchLayout = itemView.findViewById(R.id.mix_and_match);
}
}
public void makeViewInvisible(View view,int flag){
if(flag==1){
view.setVisibility(View.GONE);
}
}
}```
You need to pop the fragment onBackPressed and function needs to execute from MainActivity thus.
MainActivity
public void popFragment() {
if (getSupportFragmentManager() == null)
return;
getSupportFragmentManager().popBackStack();
}
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
popFragment();
}
}
Turns out, the problem was in the ShopRecyclerViewAdapter.java file.
In the line
FragmentManager fm = fragment.getActivity().getSupportFragmentManager
fragment.getActivity made the context null. Grabbing context from view instead solved the problem.
I replaced the above line with the following:
FragmentManager fm = ((FragmentActivity) view.getContext()).getSupportFragmentManager()
Here is the reference to the solution:
Replace fragment from recycler adapter

[Android Studio]How to start an Activity from a nested Recycleview in a Fragment?

I want to click on a custom object in my RecycleView, which then starts a new Activity inclusive Data about the object clicked but i get no response on clicking.
I tried following this question but either I did something wrong or it doesn't work.
JokeCategory
package com.example.jokestarapplication;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class JokeCategory implements Parcelable{
private String name;
private List<Joke> jokes;
public JokeCategory(String name) {
this.name = name;
this.jokes= new ArrayList<>();
}
protected JokeCategory(Parcel in){
name=in.readString();
in.readList(jokes,List.class.getClassLoader());
}
public JokeCategory(String name, List<Joke> jokes) {
this.name = name;
this.jokes = jokes;
}
public static final Creator<JokeCategory> CREATOR = new Creator<JokeCategory>() {
#Override
public JokeCategory createFromParcel(Parcel in) {
return new JokeCategory(in);
}
#Override
public JokeCategory[] newArray(int size) {
return new JokeCategory[size];
}
};
public String getName() {
return name;
}
public String getJokeNumString() {
return String.valueOf(jokes.size());
}
public List<Joke> getJokes() {
return jokes;
}
#Override
public String toString() {
return name;
}
public void addJoke(Joke joke) {
jokes.add(joke);
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeList(jokes);
}
}
CategoryListAdapter
package com.example.jokestarapplication;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class CategoryListAdapter extends RecyclerView.Adapter<CategoryListAdapter.CategoryViewHolder> {
private List<JokeCategory> mItems;
private Context mContext;
private ListItemClickListener mListItemClickListener;
public CategoryListAdapter(List<JokeCategory> mItems, Context mContext, ListItemClickListener mListItemClickListener) {
this.mItems = mItems;
this.mContext = mContext;
this.mListItemClickListener = mListItemClickListener;
}
#Override
public int getItemViewType(final int position) {
return R.layout.category_list_item;
}
#NonNull
#Override
public CategoryViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Context context = parent.getContext();
mContext = context;
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.category_list_item, parent, false);
return new CategoryViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull CategoryViewHolder holder, int position) {
holder.bind(position);
}
#Override
public int getItemCount() {
return (mItems==null) ? 0 : mItems.size();
}
interface ListItemClickListener {
void onListItemClick(JokeCategory item);
}
public void setOnListItemClickListener(ListItemClickListener listItemClickListener) {
mListItemClickListener = listItemClickListener;
}
public class CategoryViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private TextView tvCatName, tvCatNum;
public CategoryViewHolder(#NonNull View itemView) {
super(itemView);
tvCatName = itemView.findViewById(R.id.tvCatName);
tvCatNum = itemView.findViewById(R.id.tvCatNum);
}
public TextView getTvCatName() {
return tvCatName;
}
public TextView getTvCatNum() {
return tvCatNum;
}
public void bind(int position) {
tvCatName.setText(mItems.get(position).getName());
tvCatNum.setText(mItems.get(position).getJokeNumString());
}
#Override
public void onClick(View v) {
if (mListItemClickListener!=null){
int clickedIndex = getAdapterPosition();
JokeCategory jokeCategory = mItems.get(clickedIndex);
mListItemClickListener.onListItemClick(jokeCategory);
}
}
}
}
MainFragment
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.LinkedList;
import java.util.List;
public class MainFragment extends Fragment implements CategoryListAdapter.ListItemClickListener {
private CategoryListAdapter mAdapter;
private RecyclerView rvcategories;
private List<JokeCategory> categories;
private onCategoryITemSelected listener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
categories = (List<JokeCategory>) getArguments().getSerializable("Categories");
// Add the following lines to create RecyclerView
rvcategories = view.findViewById(R.id.rvcategories);
rvcategories.setHasFixedSize(true);
rvcategories.setLayoutManager(new LinearLayoutManager(view.getContext()));
mAdapter = new CategoryListAdapter(categories, getContext(), this);
rvcategories.setAdapter(mAdapter);
return view;
}
#Override
public void onResume() {
categories = (List<JokeCategory>) getArguments().getSerializable("Categories");
rvcategories.getAdapter().notifyDataSetChanged();
super.onResume();
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
if (context instanceof onCategoryITemSelected)
listener = (onCategoryITemSelected) context;
else
throw new ClassCastException(context.toString() + "must implement listener");
}
#Override
public void onListItemClick(JokeCategory item) {
Intent i = new Intent(getContext(), ActivityCategory.class);
i.putExtra(ActivityCategory.KEY_EXTRACATEGORY, item);
startActivity(i);
}
public interface onCategoryITemSelected {
void onListItemClick(JokeCategory item);
}
private List<JokeCategory> DemoData() {
List<JokeCategory> data = new LinkedList<>();
data.add(new JokeCategory("Short Jokes"));
data.add(new JokeCategory("Long Jokes"));
data.add(new JokeCategory("One Liner"));
data.add(new JokeCategory("Dumb Jokes"));
data.add(new JokeCategory("Chuck Norris"));
return data;
}
}
MainActivity
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.material.navigation.NavigationView;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
//global available user data
public static String displayUserName;
public static String displayUserEmail;
GoogleSignInClient mGoogleSignInClient;
private TextView displayName;
private TextView displayEmail;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
private Toolbar toolbar;
private NavigationView navigationView;
private FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
private List<JokeCategory> categories;
private Bundle bundle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawerLayout = findViewById(R.id.drawer);
navigationView = findViewById(R.id.navigationView);
navigationView.setNavigationItemSelectedListener(this);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open, R.string.close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.setDrawerIndicatorEnabled(true);
actionBarDrawerToggle.syncState();
categories = DemoData();
bundle = new Bundle();
bundle.putSerializable("Categories", (Serializable) categories);
//load default fragment
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
MainFragment mainFragment = new MainFragment();
mainFragment.setArguments(bundle);
fragmentTransaction.replace(R.id.container_fragment, mainFragment);
fragmentTransaction.commit();
// Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
// Build a GoogleSignInClient with the options specified by gso.
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
// Side navigation elements (needs headerView since sidenav can be hidden (null)
View headerView = navigationView.getHeaderView(0);
displayName = (TextView) headerView.findViewById(R.id.displayName);
displayEmail = (TextView) headerView.findViewById(R.id.displayEmail);
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
if (account != null) {
//account.getDisplayName()
Log.d("AUTH", "User is logged-in automatically");
Toast.makeText(this, "Google Login automatically (already signed in previously)",
Toast.LENGTH_LONG).show();
updateMainActivityUI(account);
} else {
Log.d("AUTH", "User is NOT logged-in automatically");
}
}
public void updateMainActivityUI(GoogleSignInAccount account) {
// Global vars
displayUserName = account.getDisplayName();
displayUserEmail = account.getEmail();
//Side nav vars
Log.d("AUTH", "side nav vars: " + displayUserName);
Log.d("AUTH", "side nav vars: " + displayUserEmail);
// if (displayUserName != null) {
displayName.setText(displayUserName);
// }
// if (displayUserEmail != null) {
displayEmail.setText(displayUserEmail);
// }
}
//move to new Fragment
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
drawerLayout.closeDrawer(GravityCompat.START);
bundle = new Bundle();
bundle.putSerializable("Categories", (Serializable) categories);
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
switch (item.getItemId()) {
case R.id.home:
MainFragment mainFragment = new MainFragment();
mainFragment.setArguments(bundle);
fragmentTransaction.replace(R.id.container_fragment, mainFragment);
break;
case R.id.newJoke:
NewJokeFragment newJokeFragment = new NewJokeFragment();
newJokeFragment.setArguments(bundle);
fragmentTransaction.replace(R.id.container_fragment, newJokeFragment);
break;
case R.id.logInOut:
fragmentTransaction.replace(R.id.container_fragment, new LogInOutFragment());
break;
case R.id.aboutUs:
fragmentTransaction.replace(R.id.container_fragment, new AboutUsFragment());
break;
case R.id.register:
fragmentTransaction.replace(R.id.container_fragment, new RegisterFragment());
break;
}
fragmentTransaction.commit();
return true;
}
private List<JokeCategory> DemoData() {
List<JokeCategory> data = new ArrayList<>();
data.add(new JokeCategory("Short Jokes"));
data.add(new JokeCategory("Long Jokes"));
data.add(new JokeCategory("One Liner"));
data.add(new JokeCategory("Dumb Jokes"));
data.add(new JokeCategory("Chuck Norris"));
return data;
}
public void updateCategories(List<JokeCategory> list){
categories = list;
}
}
It looks like the itemView.onClickListener is never registered.
add the following line to the constructor.
itemView.setOnClickListener(this);
It would look like:
public CategoryViewHolder(#NonNull View itemView) {
super(itemView);
itemView.setOnClickListener(this);
tvCatName = itemView.findViewById(R.id.tvCatName);
tvCatNum = itemView.findViewById(R.id.tvCatNum);
}

How do I extablish context for an Activity within a recyclerview adapter

I have buttons within the rows of a recyclerview within a fragment within an activity. When the user clicks one of the buttons, I want to switch to a different activity. How do I establish context for the Intent to switch to the new activity.
OR, should I move the onClickListener back to the fragment or activity (is it incorrect to place onClickListener within the recyclerview adapter code). If so, how do I obtain reference to the button clicked from outside the recyclerview adapter.
Here is the fragment code (CheckInRecentList.java)
package com.example.checkingin;
import android.app.Application;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.google.android.material.snackbar.Snackbar;
import java.util.List;
import static androidx.constraintlayout.widget.Constraints.TAG;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link CheckInRecentList.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link CheckInRecentList#newInstance} factory method to
* create an instance of this fragment.
*/
public class CheckInRecentList extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private RecyclerView recyclerView;
private RecyclerView.Adapter checkInListAdapter;
//private RecyclerView.LayoutManager layoutManager;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private MainViewModel mViewModel;
private CheckInListAdapter mAdapter;
private MainViewModelProviderFactory viewModelFactory;
private TextView checkInLastDateTime;
private TextView checkInTitle;
private TextView checkInDestinationName;
private TextView checkInComments;
private Context context;
private OnFragmentInteractionListener mListener;
public CheckInRecentList() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment CheckInRecentList.
*/
// TODO: Rename and change types and number of parameters
public static CheckInRecentList newInstance(String param1, String param2) {
CheckInRecentList fragment = new CheckInRecentList();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate: On Create");
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mViewModel = new ViewModelProvider(this, viewModelFactory).get(MainViewModel.class);
Log.i(TAG, "onCreateView: On Create View");
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_check_in_recent_list, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
Log.i(TAG, "onButtonPressed: ");
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
Log.i(TAG, "onAttach: OnAttach");
viewModelFactory = new MainViewModelProviderFactory(context.getApplicationContext());
mViewModel = new ViewModelProvider(this, viewModelFactory).get(MainViewModel.class);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
Log.i(TAG,"OnAttach completed");
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.i(TAG, "onActivityCreated: On Activity Created");
mViewModel = new ViewModelProvider(this, viewModelFactory).get(MainViewModel.class);
mAdapter = new CheckInListAdapter(R.layout.fragment_check_in_recent_list);
RecyclerView recyclerView = getView().findViewById(R.id.check_in_recent_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(mAdapter);
recyclerView.addItemDecoration(new DividerItemDecoration(getContext(),
LinearLayoutManager.VERTICAL));
observerSetup();
Log.i(TAG, "onActivityCreated: Observer SetUp");
ItemTouchHelper.SimpleCallback callback = new
ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT | ItemTouchHelper.LEFT) {
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
int position = viewHolder.getAdapterPosition();
mAdapter.deleteItem(position);
Snackbar snackbar = Snackbar.make(viewHolder.itemView, "Item " + (direction == ItemTouchHelper.RIGHT ? "deleted" : "archived") + ".", Snackbar.LENGTH_LONG);
snackbar.setAction(android.R.string.cancel, new View.OnClickListener() {
#Override
public void onClick(View view) {
mAdapter.undoDelete();
}
});
snackbar.show();
}
#Override
public void onChildDraw (Canvas c, RecyclerView
recyclerView, RecyclerView.ViewHolder viewHolder,float dX, float dY,
int actionState, boolean isCurrentlyActive){
new RecyclerViewSwipeDecorator.Builder(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
.addSwipeLeftBackgroundColor(ContextCompat.getColor(getContext(), R.color.recycler_view_item_swipe_left_background))
.addSwipeLeftActionIcon(R.drawable.ic_archive_white_24dp)
.addSwipeRightBackgroundColor(ContextCompat.getColor(getContext(), R.color.recycler_view_item_swipe_right_background))
.addSwipeRightActionIcon(R.drawable.ic_delete_white_24dp)
.addSwipeRightLabel(getString(R.string.action_delete))
.setSwipeRightLabelColor(Color.WHITE)
.addSwipeLeftLabel(getString(R.string.action_archive))
.setSwipeLeftLabelColor(Color.WHITE)
.create()
.decorate();
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}
};
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(callback);
itemTouchHelper.attachToRecyclerView(recyclerView);
CustomToast newtoast = new CustomToast(getContext(),"you clicked on this" );
newtoast.show();
}
#Override
public void onDetach() {
super.onDetach();
Log.i(TAG, "onDetach: ");
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
private void clearFields() {
checkInLastDateTime.setText("");
checkInDestinationName.setText("");
checkInTitle.setText("");
checkInComments.setText("");
}
private void observerSetup() {
Log.i(TAG, "observerSetup:");
checkInLastDateTime = getView().findViewById(R.id.checkInLastDateTime);
checkInTitle = getView().findViewById(R.id.checkInTitle);
checkInDestinationName = getView().findViewById(R.id.checkInDestinationName);
checkInComments = getView().findViewById(R.id.checkInComments);
if(mViewModel.getAllCheckIn() != null)
mViewModel.getAllCheckIn().observe(getViewLifecycleOwner(), new Observer<List<CheckInTable>>(){
#Override
public void onChanged(#Nullable final List<CheckInTable> allCheckIn) {
mAdapter.setCheckInList(allCheckIn);
}
});
}
}
Here is the recyclerview adapter code
package com.example.checkingin;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
import static androidx.constraintlayout.widget.Constraints.TAG;
public class CheckInListAdapter extends RecyclerView.Adapter<CheckInListAdapter.ViewHolder>{
private int checkInListLayout;
private List<CheckInTable> checkInList;
private CoordinatorLayout coordinatorLayout;
private RecyclerView recyclerView;
private CheckInTable mRecentlyDeletedItem;
private int mCheckInTablePrimaryKey;
private int mRecentlyDeletedItemPosition;
private Context context;
public CheckInListAdapter(int layoutId) {
Log.i(TAG, "CheckInListAdapter: ");
checkInListLayout = layoutId;
}
public void setCheckInList(List<CheckInTable> allCheckIn) {
checkInList = allCheckIn;
Log.i(TAG, "setCheckInList: ");
notifyDataSetChanged();
}
public void deleteItem(int position) {
mRecentlyDeletedItem = checkInList.get(position);
mRecentlyDeletedItemPosition = position;
checkInList.remove(position);
notifyItemRemoved(position);
}
public void undoDelete() {
checkInList.add(mRecentlyDeletedItemPosition,
mRecentlyDeletedItem);
notifyItemInserted(mRecentlyDeletedItemPosition);
}
#Override
public int getItemCount() {
return checkInList == null ? 0 : checkInList.size();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.i(TAG, "onCreateViewHolder: ");
View view = LayoutInflater.from(
parent.getContext()).inflate(R.layout.recycler_view_item, parent, false);
ViewHolder checkInListViewHolder = new ViewHolder(view);
return checkInListViewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int listPosition) {
TextView checkInTablePrimaryKey = holder.checkInTablePrimaryKey;
TextView checkInLastDateTime = holder.checkInLastDateTime;
TextView checkInTitle = holder.checkInTitle;
TextView checkInDestinationName = holder.checkInDestinationName;
TextView checkInComments = holder.checkInComments;
holder.checkInEditButton.setImageResource(R.drawable.ic_menu_edit);
holder.checkInResendButton.setImageResource(R.drawable.ic_menu_share);
Log.i(TAG, "onBindViewHolder: ");
//checkInTablePrimaryKey.setText(checkInList.get(listPosition).getCheckInTablePrimaryKey());
checkInLastDateTime.setText(checkInList.get(listPosition).getCheckInLastDateTime());
checkInTitle.setText(checkInList.get(listPosition).getCheckInTitle());
checkInDestinationName.setText(checkInList.get(listPosition).getCheckInDestinationName());
checkInComments.setText(checkInList.get(listPosition).getCheckInComments());
ImageView checkInEditButton = holder.checkInEditButton;
ImageView checkInResendButton = holder.checkInResendButton;
ImageButton editCheckInButton = checkInEditButton.findViewById(R.id.checkInEditButton);
ImageButton resendCheckInButton = checkInResendButton.findViewById(R.id.checkInResendButton);
editCheckInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//put in edit check in logic
Integer value = (checkInList.get(listPosition).getCheckInTablePrimaryKey());
Intent intent = new Intent(context, CheckInNew.class);
intent.putExtra("checkInTablePrimaryKey",value);
context.startActivity(intent);
//Bundle extras = getIntent().getExtras();
//if (extras != null) {
// String value = extras.getInt("checkInTablePrimaryKey");
//The key argument here must match that used in the other activity
//}
}
});
resendCheckInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//put in resend logic
}
});
}
static class ViewHolder extends RecyclerView.ViewHolder {
TextView checkInTablePrimaryKey;
TextView checkInLastDateTime;
TextView checkInTitle;
TextView checkInDestinationName;
TextView checkInComments;
ImageView checkInEditButton;
ImageView checkInResendButton;
ViewHolder(View itemView) {
super(itemView);
Log.i(TAG, "ViewHolder: ");
checkInTablePrimaryKey = itemView.findViewById(R.id.checkInTablePrimaryKey);
checkInLastDateTime = itemView.findViewById(R.id.checkInLastDateTime);
checkInTitle = itemView.findViewById(R.id.checkInTitle);
checkInDestinationName = itemView.findViewById(R.id.checkInDestinationName);
checkInComments = itemView.findViewById(R.id.checkInComments);
checkInEditButton = itemView.findViewById(R.id.checkInEditButton);
checkInResendButton = itemView.findViewById(R.id.checkInResendButton);
}
}
}
Here is the Activity code CheckIn.java
package com.example.checkingin;
import android.net.Uri;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import android.view.View;
import android.view.Menu;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.tabs.TabLayout;
public class CheckIn extends AppCompatActivity implements
CheckInRecentList.OnFragmentInteractionListener,
CheckInApproveRequested.OnFragmentInteractionListener,
CheckInSearch.OnFragmentInteractionListener {
//private AdView mAdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_in);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
//MobileAds.initialize(this, new OnInitializationCompleteListener() {
// #Override
// public void onInitializationComplete(InitializationStatus initializationStatus) {
// }
//});
//mAdView = findViewById(R.id.adView);
//AdRequest adRequest = new AdRequest.Builder().build();
//mAdView.loadAd(adRequest);
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();
}
});
DrawerUtil.getDrawer(this,toolbar);
configureTabLayout();
}
private void configureTabLayout() {
TabLayout tabLayout = findViewById(R.id.check_in_main_tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Recent"));
tabLayout.addTab(tabLayout.newTab().setText("Approve Requested"));
tabLayout.addTab(tabLayout.newTab().setText("Search"));
final ViewPager viewPager = findViewById(R.id.check_in_main_pager);
final PagerAdapter adapter = new CheckInMainPagerAdapter
(getSupportFragmentManager(),
tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new
TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new
TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public void onFragmentInteraction(Uri uri) {
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.check_in, menu);
return true;
}
}
In the constructor of CheckInListAdapter pass another argument as context
public CheckInListAdapter(int layoutId, Context context) {
Log.i(TAG, "CheckInListAdapter: ");
checkInListLayout = layoutId;
this.context = context
}

Want to use a floating action button that adds an item to a recyclerview in a specific fragment that is contained in a ViewPager2

I have been having a lot of trouble trying to implement multiple recyclerviews across multiple pages(represented by fragments) in a viewpager2, and I want to use a floating action button that when clicked, props up a page where the user can input data that can eventually be added to the recyclerview within a specific page on the viewpager. The Viewpager2 is applied with a tab layout labeling the days "Monday" to "Sunday." I cannot seem to add to the recyclerview through the activity "activity_add_medication_to_list." There is a long segment of code with 7 intents that is meant to represent adding to a medication list. The project is essentially a medical scheduling/tracking application. For each day of the week, I want to be able to add a specific medication to the list and be able to see it visibly. There are seven fragments representing each of the days of the week. FirstFragment represents Monday, SecondFragment represents Tuesday, etc. I also have a recyclerviewAdapter class and a ViewPagerAdapter class representing the adapters for both the multiple recyclerviews and the viewPager2.
Main problem: After clicking on the floating action button and inputing my data, it is not adding to the end of the recyclerview for any of the pages (represented by FirstFragment class). What am I missing that is not allowing me to see a visible list of items for any of the recyclerviews? How do I properly integrate the recyclerviews into the fragments so that I can update the recyclerviews using the floating action button?
Only 5 of the 7 fragment classes are shown below to conserve space. They are all according to the day of the week. Monday, Tuesday, Wednesday, Thursday, Friday refer to these first 5 fragment classes.
Code:
Add Medication to List class
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class add_medication_to_list extends AppCompatActivity {
String name;
String time;
int quantity;
int dosage;
String dayOfWeek;
EditText nameInput;
EditText timeInput;
EditText quantityInput;
EditText dosageInput;
EditText dayOfWeekInput;
Button add;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_medication_to_list);
nameInput = findViewById(R.id.medicine_name);
timeInput = findViewById(R.id.time);
quantityInput = findViewById(R.id.medicine_quantity);
dosageInput = findViewById(R.id.dosage);
dayOfWeekInput = findViewById(R.id.dayOfWeek);
add = findViewById(R.id.addButton);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = nameInput.getText().toString();
time = timeInput.getText().toString();
quantity = Integer.parseInt(quantityInput.getText().toString());
dosage = Integer.parseInt(dosageInput.getText().toString());
dayOfWeek = dayOfWeekInput.getText().toString();
// setResult(RESULT_OK);
if (dayOfWeek.equalsIgnoreCase("monday")) {
FirstFragment.add_new_item(name, time, quantity, dosage);
Intent new_activity = new Intent(getApplicationContext(), MainActivity.class);
startActivity(new_activity);
} else if (dayOfWeek.equalsIgnoreCase("tuesday")) {
SecondFragmentClass.add_new_item(name, time, quantity, dosage);
Intent new_activity = new Intent(getApplicationContext(), MainActivity.class);
startActivity(new_activity);
} else if (dayOfWeek.equalsIgnoreCase("wednesday")) {
ThirdFragment.add_new_item(name, time, quantity, dosage);
Intent new_activity = new Intent(getApplicationContext(), MainActivity.class);
startActivity(new_activity);
} else if (dayOfWeek.equalsIgnoreCase("thursday")) {
FourthFragment.add_new_item(name, time, quantity, dosage);
Intent new_activity = new Intent(getApplicationContext(), MainActivity.class);
startActivity(new_activity);
} else if (dayOfWeek.equalsIgnoreCase("friday")) {
FifthFragment.add_new_item(name, time, quantity, dosage);
Intent new_activity = new Intent(getApplicationContext(), MainActivity.class);
startActivity(new_activity);
} else if (dayOfWeek.equalsIgnoreCase("saturday")) {
SixthFragment.add_new_item(name, time, quantity, dosage);
Intent new_activity = new Intent(getApplicationContext(), MainActivity.class);
startActivity(new_activity);
} else if (dayOfWeek.equalsIgnoreCase("sunday")) {
SeventhFragment.add_new_item(name, time, quantity, dosage);
Intent new_activity = new Intent(getApplicationContext(), MainActivity.class);
startActivity(new_activity);
}
}
});
}
}
FirstFragment Class
package com.example.myapplication;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
public class FirstFragment extends Fragment {
private static final String ARG_COUNT = "param1";
private Integer counter;
private static Context context;
private int[] COLOR_MAP = {
R.color.red_100, R.color.red_300, R.color.red_500, R.color.red_700, R.color.blue_100,
R.color.blue_300, R.color.blue_500, R.color.blue_700, R.color.green_100, R.color.green_300,
R.color.green_500, R.color.green_700
};
private RecyclerView myRecyclerView;
private static ArrayList<Medicine> medlist;
private static recyclerViewAdapter anAdapter;
private static int positionCounter;
View view;
public FirstFragment() {
// Required empty public constructor
}
public static void add_new_item(String name, String time, int quantity, int dosage) {
medlist.add(new Medicine(name, time, quantity, dosage, R.drawable.resized_pill));
anAdapter.notifyItemInserted(medlist.size()-1);
//anAdapter.notifyDataSetChanged();
}
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
public static FirstFragment newInstance(Integer counter) {
FirstFragment fragment = new FirstFragment();
Bundle args = new Bundle();
args.putInt(ARG_COUNT, counter);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
counter = getArguments().getInt(ARG_COUNT);
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_card, container, false);
return v;
}
#Override public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.setBackgroundColor(ContextCompat.getColor(context, COLOR_MAP[counter]));
FloatingActionButton new_button = view.findViewById(R.id.actionFloatingButton);
medlist = new ArrayList<>();
positionCounter = 0;
myRecyclerView = view.findViewById(R.id.prescription_list);
myRecyclerView.setHasFixedSize(true);
anAdapter = new recyclerViewAdapter(getContext(), medlist);
myRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
myRecyclerView.setAdapter(anAdapter);
new_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent new_activity = new Intent(context, add_medication_to_list.class);
startActivity(new_activity);
} });
}
}
SecondFragment Class
package com.example.myapplication;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
public class SecondFragmentClass extends Fragment {
private static final String ARG_COUNT = "param1";
private Integer counter;
private static Context context;
private int[] COLOR_MAP = {
R.color.red_100, R.color.red_300, R.color.red_500, R.color.red_700, R.color.blue_100,
R.color.blue_300, R.color.blue_500, R.color.blue_700, R.color.green_100, R.color.green_300,
R.color.green_500, R.color.green_700
};
private RecyclerView myRecyclerView;
private static ArrayList<Medicine> medlist;
private static recyclerViewAdapter anAdapter;
private static int positionCounter;
public static void add_new_item(String name, String time, int quantity, int dosage) {
medlist.add(new Medicine(name, time, quantity, dosage, R.drawable.resized_pill));
anAdapter.notifyItemInserted(medlist.size()-1);
//anAdapter.notifyDataSetChanged();
positionCounter++;
}
public static SecondFragmentClass newInstance(Integer counter) {
SecondFragmentClass fragment = new SecondFragmentClass();
Bundle args = new Bundle();
args.putInt(ARG_COUNT, counter);
fragment.setArguments(args);
return fragment;
}
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
positionCounter = 0;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
counter = getArguments().getInt(ARG_COUNT);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_card_2, container, false);
return v;
}
#Override public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.setBackgroundColor(ContextCompat.getColor(context, COLOR_MAP[counter]));
FloatingActionButton new_button = view.findViewById(R.id.actionFloatingButton);
positionCounter = 0;
medlist = new ArrayList<>();
myRecyclerView = view.findViewById(R.id.prescription_list_2);
anAdapter = new recyclerViewAdapter(getContext(), medlist);
myRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
myRecyclerView.setAdapter(anAdapter);
new_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent new_activity = new Intent(context, add_medication_to_list.class);
startActivity(new_activity);
}
});
}
}
ThirdFragment Class
package com.example.myapplication;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
public class ThirdFragment extends Fragment {
private static final String ARG_COUNT = "param1";
private Integer counter;
private static Context context;
private int[] COLOR_MAP = {
R.color.red_100, R.color.red_300, R.color.red_500, R.color.red_700, R.color.blue_100,
R.color.blue_300, R.color.blue_500, R.color.blue_700, R.color.green_100, R.color.green_300,
R.color.green_500, R.color.green_700
};
private RecyclerView myRecyclerView;
private static ArrayList<Medicine> medlist = new ArrayList<>();
private static recyclerViewAdapter anAdapter = new recyclerViewAdapter(context, medlist);
private static int positionCounter;
public static void add_new_item(String name, String time, int quantity, int dosage) {
medlist.add(new Medicine(name, time, quantity, dosage, R.drawable.resized_pill));
anAdapter.notifyItemInserted(medlist.size()-1);
//anAdapter.notifyDataSetChanged();
positionCounter++;
}
public static ThirdFragment newInstance(Integer counter) {
ThirdFragment fragment = new ThirdFragment();
Bundle args = new Bundle();
args.putInt(ARG_COUNT, counter);
fragment.setArguments(args);
return fragment;
}
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
positionCounter = 0;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
counter = getArguments().getInt(ARG_COUNT);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_card_3, container, false);
return v;
}
#Override public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.setBackgroundColor(ContextCompat.getColor(context, COLOR_MAP[counter]));
FloatingActionButton new_button = view.findViewById(R.id.actionFloatingButton);
positionCounter = 0;
medlist = new ArrayList<>();
myRecyclerView = view.findViewById(R.id.prescription_list_3);
myRecyclerView.setHasFixedSize(true);
anAdapter = new recyclerViewAdapter(getContext(), medlist);
myRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
myRecyclerView.setAdapter(anAdapter);
new_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent new_activity = new Intent(context, add_medication_to_list.class);
startActivity(new_activity);
}
});
}
}
FourthFragment Class
package com.example.myapplication;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
public class FourthFragment extends Fragment {
private static final String ARG_COUNT = "param1";
private Integer counter;
private static Context context;
private int[] COLOR_MAP = {
R.color.red_100, R.color.red_300, R.color.red_500, R.color.red_700, R.color.blue_100,
R.color.blue_300, R.color.blue_500, R.color.blue_700, R.color.green_100, R.color.green_300,
R.color.green_500, R.color.green_700
};
private RecyclerView myRecyclerView;
private static ArrayList<Medicine> medlist;
private static recyclerViewAdapter anAdapter;
private static int positionCounter;
public static void add_new_item(String name, String time, int quantity, int dosage) {
medlist.add(new Medicine(name, time, quantity, dosage, R.drawable.resized_pill));
anAdapter.notifyItemInserted(medlist.size()-1);
//anAdapter.notifyDataSetChanged();
positionCounter++;
}
public static FourthFragment newInstance(Integer counter) {
FourthFragment fragment = new FourthFragment();
Bundle args = new Bundle();
args.putInt(ARG_COUNT, counter);
fragment.setArguments(args);
return fragment;
}
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
counter = getArguments().getInt(ARG_COUNT);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_card_4, container, false);
return v;
}
#Override public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.setBackgroundColor(ContextCompat.getColor(context, COLOR_MAP[counter]));
FloatingActionButton new_button = view.findViewById(R.id.actionFloatingButton);
myRecyclerView = view.findViewById(R.id.prescription_list_4);
positionCounter = 0;
medlist = new ArrayList<>();
anAdapter = new recyclerViewAdapter(getContext(), medlist);
myRecyclerView.setHasFixedSize(true);
myRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
myRecyclerView.setAdapter(anAdapter);
new_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent new_activity = new Intent(context, add_medication_to_list.class);
startActivity(new_activity);
}
});
}
}
FifthFragment class
package com.example.myapplication;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
public class FifthFragment extends Fragment {
private static final String ARG_COUNT = "param1";
private Integer counter;
private static Context context;
private int[] COLOR_MAP = {
R.color.red_100, R.color.red_300, R.color.red_500, R.color.red_700, R.color.blue_100,
R.color.blue_300, R.color.blue_500, R.color.blue_700, R.color.green_100, R.color.green_300,
R.color.green_500, R.color.green_700
};
private RecyclerView myRecyclerView;
private static ArrayList<Medicine> medlist;
private static recyclerViewAdapter anAdapter;
private static int positionCounter;
public static void add_new_item(String name, String time, int quantity, int dosage) {
medlist.add(new Medicine(name, time, quantity, dosage, R.drawable.resized_pill));
anAdapter.notifyItemInserted(medlist.size()-1);
//anAdapter.notifyDataSetChanged();
positionCounter++;
}
public static FifthFragment newInstance(Integer counter) {
FifthFragment fragment = new FifthFragment();
Bundle args = new Bundle();
args.putInt(ARG_COUNT, counter);
fragment.setArguments(args);
return fragment;
}
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
positionCounter = 0;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
counter = getArguments().getInt(ARG_COUNT);
positionCounter = 0;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_card_5, container, false);
return v;
}
#Override public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.setBackgroundColor(ContextCompat.getColor(context, COLOR_MAP[counter]));
FloatingActionButton new_button = view.findViewById(R.id.actionFloatingButton);
medlist = new ArrayList<>();
positionCounter = 0;
myRecyclerView = view.findViewById(R.id.prescription_list_5);
myRecyclerView.setHasFixedSize(true);
anAdapter = new recyclerViewAdapter(getContext(), medlist);
myRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
myRecyclerView.setAdapter(anAdapter);
new_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent new_activity = new Intent(context, add_medication_to_list.class);
startActivity(new_activity);
}
});
}
}
ViewPagerAdapter
package com.example.myapplication;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import java.util.ArrayList;
public class ViewPagerAdapter extends FragmentStateAdapter {
private static final int CARD_ITEM_SIZE = 7;
private ArrayList<Fragment> arrayList = new ArrayList<>();
public ViewPagerAdapter(#NonNull FragmentActivity fragmentActivity) {
super(fragmentActivity);
}
#NonNull
#Override
public Fragment createFragment(int position) {
return arrayList.get(position);
}
#Override public int getItemCount() {
return CARD_ITEM_SIZE;
}
public void addFragment(Fragment fragment) {
arrayList.add(fragment);
}
}
recyclerViewAdapter
package com.example.myapplication;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class recyclerViewAdapter extends RecyclerView.Adapter<recyclerViewAdapter.MyViewHolder> {
Context data;
List<Medicine> new_list;
public recyclerViewAdapter(Context data, List<Medicine> new_list) {
this.data = data;
this.new_list = new_list;
}
public recyclerViewAdapter() {
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(data).inflate(R.layout.new_items, parent, false);
MyViewHolder view = new MyViewHolder(v);
return view;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.new_name.setText(new_list.get(position).getName());
holder.new_quantity.setText(Integer.toString(new_list.get(position).getFrequency()));
holder.new_image.setImageResource(new_list.get(position).getPhoto());
holder.new_time.setText(new_list.get(position).getTime());
}
#Override
public int getItemCount() {
return new_list.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
private TextView new_name;
private TextView new_quantity;
private ImageView new_image;
private TextView new_time;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
new_name = itemView.findViewById(R.id.prescription_name);
new_image = itemView.findViewById(R.id.new_image);
new_quantity = itemView.findViewById(R.id.quantity_items);
new_time = itemView.findViewById(R.id.new_time);
}
}
}
Medicine Class
package com.example.myapplication;
public class Medicine {
private String name_of_medicine, time_to_take;
private int quantity_remaining, Photo, frequency, dosage;
public Medicine(String name_of_medicine, String time_to_take, int quantity, int dosage, int photo) {
this.name_of_medicine = name_of_medicine;
this.time_to_take = time_to_take;
this.quantity_remaining = quantity;
this.dosage = dosage;
Photo = photo;
}
public String getName()
{
return name_of_medicine;
}
public String getTime()
{
return time_to_take;
}
public int getFrequency() {
return quantity_remaining;
}
public int getPhoto() {
return Photo;
}
}
Resolved this issue. Used finish() after calling add_new_item() method.

How to refresh RecyclerView in one fragment when data changed in another fragment

How do I refresh the data from a local database to RecyclerView when data was successfully submitted? I use the tabs on the application. 2nd-Tab functions to submit the data, and if successful, the data will be stored in localDB.
Data on localDB I will present at the 3rd-Tab.
But what happens, I have to swipe 1st-Tab, then swipe to the 2nd-Tab and then swipe to the new 3rd-Tab data on my localDB successfully displayed.
If the 2nd-Tab me to submit the data, then I swipe to 3rd-Tab, the data will not appear on the list of data.
How do I get the data directly displayed without the need to swipe to the first 1st-Tab and then to the 2nd-Tab and 3rd-Tab ???
MainActivity :
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import com.bertho.gmyl.fragments.EngagedFragment;
import com.bertho.gmyl.fragments.RequestFragment;
import com.bertho.gmyl.fragments.SigninFragment;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.engine_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
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.addFrag(new SigninFragment(), "SIGN-IN");
adapter.addFrag(new EngagedFragment(), "ENGAGED ID");
adapter.addFrag(new RequestFragment(), "LOCATION");
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 addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
EngagedFragment (2nd-Tab) Form to save data
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.bertho.gmyl.R;
import com.bertho.gmyl.model.Engaged;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.bertho.gmyl.realm.RealmHelper;
public class EngagedFragment extends Fragment implements View.OnClickListener {
private static final String TAG = EngagedFragment.class.getSimpleName();
private EditText nama, email, nohp;
private Button btnSaveConnection;
private DatabaseReference mFirebaseDatabase;
private FirebaseDatabase mFirebaseInstance;
private RelativeLayout mRoot;
private View rootView;
private String userId;
private TextView lblNama, lblEmail, lblNohp;
private RelativeLayout relativeLayout;
private RealmHelper realmHelper;
public EngagedFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_engaged, container, false);
realmHelper = new RealmHelper(getActivity());
String appName = getResources().getString(R.string.app_name);
loadLocalDB();
nama = (EditText) rootView.findViewById(R.id.txtName);
email = (EditText) rootView.findViewById(R.id.txtEmail);
nohp = (EditText) rootView.findViewById(R.id.txtNoHp);
lblNama = (TextView) rootView.findViewById(R.id.lblNameval);
lblEmail = (TextView) rootView.findViewById(R.id.lblEmailval);
lblNohp = (TextView) rootView.findViewById(R.id.lblNohpval);
relativeLayout = (RelativeLayout) rootView.findViewById(R.id.panelLabelDetail);
btnSaveConnection = (Button) rootView.findViewById(R.id.btnEngaged);
mFirebaseInstance = FirebaseDatabase.getInstance();
mFirebaseDatabase = mFirebaseInstance.getReference("tbl_engaged");
mFirebaseInstance.getReference("titleapp").setValue(appName);
mFirebaseInstance.getReference("titleapp").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.e(TAG, "TITLE UPDATED FROM FIREBASE");
String appTitle = dataSnapshot.getValue(String.class);
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(appTitle);
}
#Override
public void onCancelled(DatabaseError error) {
Log.e(TAG, "FAILED TO READ TITLE FROM FIREBASE.", error.toException());
}
});
btnSaveConnection.setOnClickListener(this);
return rootView;
}
private void showSnack(String notify) {
mRoot = (RelativeLayout) rootView.findViewById(R.id.frag_engaged);
Snackbar snackbar = Snackbar.make(mRoot, notify, Snackbar.LENGTH_LONG);
snackbar.show();
}
public void onClick(View v) {
if(v.getId() == R.id.btnEngaged) {
String txtName = nama.getText().toString();
String txtEmail = email.getText().toString();
String txtNo = nohp.getText().toString();
if(txtName.equals("") || txtName.isEmpty()) {
showSnack("Name must filled");
nama.requestFocus();
} else if (txtEmail.equals("") || txtEmail.isEmpty()) {
showSnack("Email must filled");
email.requestFocus();
} else if (txtNo.equals("") || txtNo.isEmpty()) {
showSnack("No.HP must filled");
nohp.requestFocus();
} else {
createUser(txtName, txtEmail, txtNo);
saveToLocalDB(txtName, txtEmail, txtNo);
}
}
}
private void saveToLocalDB(String txtName, String txtEmail, String txtNo) {
realmHelper.addEngaged(txtName, txtEmail, txtNo);
}
private void loadLocalDB() {
realmHelper.getAllData();
}
private void createUser(String name, String email, String nohp) {
userId = mFirebaseDatabase.push().getKey();
Engaged user = new Engaged(name, email, nohp);
mFirebaseDatabase.child(userId).setValue(user);
addUserChangeListener();
}
private void addUserChangeListener() {
mFirebaseDatabase.child(userId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Engaged user = dataSnapshot.getValue(Engaged.class);
if (user == null) {
Log.e(TAG, "ENGAGED DATA IS NULL");
return;
}
Log.e(TAG, "ENGAGED DATA IS CHANGED!" + user.name + ", " + user.email);
lblNama.setText(user.name);
lblEmail.setText(user.email);
lblNohp.setText(user.nohp);
//relativeLayout.setVisibility(View.VISIBLE);
nama.setText("");
email.setText("");
nohp.setText("");
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.e(TAG, "FAILED TO READ USER", error.toException());
}
});
}
}
RequestFragment (3rd-Tab) To display localDB
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.bertho.gmyl.R;
import com.bertho.gmyl.adapter.AdapterEngaged;
import com.bertho.gmyl.model.ModelEngaged;
import com.bertho.gmyl.realm.RealmHelper;
import java.util.ArrayList;
public class RequestFragment extends Fragment {
private static final String TAG = "RequestFragment";
private RecyclerView recyclerView;
private View rootView;
private ArrayList<ModelEngaged> data;
private RealmHelper helper;
public RequestFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_request, container, false);
data = new ArrayList<>();
helper = new RealmHelper(getActivity());
recyclerView = (RecyclerView) rootView.findViewById(R.id.rvArticle);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
setRecyclerView();
return rootView;
}
public void setRecyclerView() {
try {
data = helper.findAllArticle();
} catch (Exception e) {
e.printStackTrace();
}
AdapterEngaged adapter = new AdapterEngaged(data, new AdapterEngaged.OnItemClickListener() {
#Override
public void onClick(ModelEngaged item) {
Toast.makeText(getContext(), "LIST CLICKED", Toast.LENGTH_LONG).show();
}
});
recyclerView.setAdapter(adapter);
}
#Override
public void onResume() {
super.onResume();
try {
data = helper.findAllArticle();
} catch (Exception e) {
e.printStackTrace();
}
setRecyclerView();
}
}
Everything went smoothly, it's just that I hope the data can be displayed when the form is submitted and can be directly viewed on the 3rd-Tab
Try this,
Create an Interface in EngagedFragment
say,
public interface SubmitListener {
void onSubmit();
}
private SubmitListener onSubmitListener;
public void setSubmitListener(SubmitListener onSubmitListener){
this.onSubmitListener = onSubmitListener;
}
public SubmitListener getOnSubmitListener(){
return onSubmitListener;
}
In saveToLocalDB(...) method
call
onSubmitListener.onSubmit();
In MainActivity:
1) Update the below statement:
public class MainActivity extends AppCompatActivity implements EngagedFragment.SubmitListener
2) Make your ViewPagerAdapter adapter; variable as Global variable;
while adding fragment:
EngagedFragment engagedFrag = new EngagedFragment();
adapter.addFrag(engagedFrag, "ENGAGED ID");
...
viewPager.setAdapter(adapter);
3) add this after setting adapter
engagedFrag.setSubmitListener(this);
4) Override onSubmit() method and try the below code in that method
if(viewPager != null){
if(adapter != null){
Fragment fragment = adapter.getItem(2);
if(fragment != null){
RequestFragment requestFragment = (RequestFragment) fragment;
requestFragment.setRecyclerView();
}
}
}
try this
mViewPager.setOffscreenPageLimit(0);
if that doesnt help, please check below SO question:
fragment refresh On Swip
and about : mViewPager.setOffscreenPageLimit(0); this might not work as i found in one of #commonware 's answer's, the following :-
"Does ViewPager require a minimum of 1 offscreen pages
Yes. If I am reading the source code correctly, you should be getting a warning about this in LogCat, something like:
Requested offscreen page limit 0 too small; defaulting to 1"

Categories

Resources