How to refresh recyclerView after changing data? - android

I have a problem with RecyclerView. I need to refresh it after clicking a long click. I tried to play with notifyDataSetChanged() method. But nothing works. Here is my code. In current situation item removes from database right away. But I have to move to another activity and come back to see any UI changes. Thanks in advance for any help.
public class AlarmsActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private List<Alarm> alarmsList = new ArrayList<>();
private AlarmRecyclerAdapter mAdapter;
private AppDataBase db;
private AlarmsDao alarmDao;
private OnClickedRecyclerAdapter<Alarm> recyclerListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alarms_activity);
db = App.getInstance().getDataBase();
alarmDao = db.AlarmDao();
recyclerView = findViewById(R.id.recycler);
recyclerListener = new OnClickedRecyclerAdapter<Alarm>() {
#Override
public void onLongClicked(final Alarm data) {
removeAlarm(data);
}
#Override
public void onClicked(Alarm data) {
}
};
mAdapter = new AlarmRecyclerAdapter(alarmsList, recyclerListener);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
getData();
}
public void getData(){
new Thread(new Runnable() {
#Override
public void run() {
for (Alarm alarm : alarmDao.getAll()){
alarmsList.add(alarm);
}
}
}).start();
}
public void removeAlarm(final Alarm alarm){
new Thread(new Runnable() {
#Override
public void run() {
Log.e("xxx", "Long clicked");
alarmDao.deleteAlarm(alarm);
}
}).start();
}
}
OnClickListener
public interface OnClickedRecyclerAdapter<Alarm> {
void onLongClicked(Alarm data);
void onClicked(Alarm data);
}
Adapter.
public class AlarmRecyclerAdapter extends RecyclerView.Adapter<AlarmViewHolder> {
List<Alarm> alarms;
OnClickedRecyclerAdapter listener;
private AppDataBase db;
private AlarmsDao alarmsDao;
public AlarmRecyclerAdapter(List<Alarm> alarms, OnClickedRecyclerAdapter listener) {
this.alarms = alarms;
this.listener = listener;
db = App.getInstance().getDataBase();
alarmsDao = db.AlarmDao();
}
#NonNull
#Override
public AlarmViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recycler, parent, false);
return new AlarmViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull AlarmViewHolder holder, final int position) {
final Alarm alarm = alarms.get(position);
holder.time.setText(alarm.getHour()+" : " + alarm.getMinute());
holder.days.setText(alarm.getDays());
holder.isOn.setChecked(alarm.isIs_on());
holder.isOn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
Log.e("xxx", b + " ");
}
});
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onClicked(alarm);
}
});
holder.cardView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
listener.onLongClicked(alarm);
return true;
}
});
}
#Override
public int getItemCount() {
return alarms.size();
}
}

Change this:
holder.cardView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
listener.onLongClicked(alarm);
return true;
}
});
To this:
holder.cardView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
listener.onLongClicked(alarm);
alarms.remove(holder.getAdapterPosition()); //or alarms.remove(alarm);
notifyItemRemoved(holder.getAdapterPosition()); //or notifyDataSetChanged();
return true;
}
});
The problem is that you're removing the alarm from your database when you call removeAlarm() in your Activity, but you're not actually removing it from the alarms list in your Adapter. The change isn't being reflected because the data set never changes in your code. When you recreate your Activity, you pass the new database list into the Adapter, so it updates then.
I also recommend not doing this:
public void getData(){
new Thread(new Runnable() {
#Override
public void run() {
for (Alarm alarm : alarmDao.getAll()){
alarmsList.add(alarm);
}
}
}).start();
}
While alarmsList in your Activity and alarms are the same instance, and thus reflect the same additions and removals, there's no guarantee this logic will complete before the RecyclerView is inflated and the adapter attached. That means you could end up with missing data, especially on slower devices.
Unless you have an absolute ton of Alarms, there's no need to run that in a new Thread. You could just move that for-loop right above where you initialize the Adapter, and use the addAll() method:
alarmsList.addAll(alarmDuo.getAll());
mAdapter = //your assignment from your code
If you do need it to be async, attach the Adapter later, inside your Thread:
public void getData(){
new Thread(new Runnable() {
#Override
public void run() {
alarmsList.addAll(alarmDuo.getAll());
runOnUiThread(new Runnable() {
mAdapter = new AlarmRecyclerAdapter(alarmsList, recyclerListener);
recyclerView.setAdapter(mAdapter);
}
}
}).start();
}
Remove the assignment, adapter setting and notifyDataSetChanged() calls from your onCreate() method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alarms_activity);
db = App.getInstance().getDataBase();
alarmDao = db.AlarmDao();
recyclerView = findViewById(R.id.recycler);
recyclerListener = new OnClickedRecyclerAdapter<Alarm>() {
#Override
public void onLongClicked(final Alarm data) {
removeAlarm(data);
}
#Override
public void onClicked(Alarm data) {
}
};
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
getData();
}

Related

Andriod Retrofit 2: Refreshing Recycler View From from another Activity

So I have a app where I am displaying the products list from the database using a Recycler View.
There is delete button beside each item which is working fine.
And there is a scan item button which opens a BARCODE SCANNER which on succesfull scanning adds the new product to the database and goes back to the Recycler View display is supposed to refresh the view and display the new Item.
but I am having problem with refreshing the recycler view on adding a new Product.
there is also a delete product function which works perfectly so I tried to do the add item method the same way, but the recycler view doesn't refresh.
UserPage activity
public class UserPage extends AppCompatActivity implements ProductAdaptar.clickedItem {
Toolbar toolbar;
RecyclerView recyclerView;
String rfidNo;
public static String barcode;
Button scanItem;
Button payBill;
TextView total;
ProductAdaptar productAdaptar;
Call<List<UserLoginResp>> productList;
List<UserLoginResp> productListsItems = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_page);
toolbar=findViewById(R.id.toolbar);
recyclerView=findViewById(R.id.recyclerview);
scanItem = findViewById(R.id.scanItem);
payBill = findViewById(R.id.payBill);
total = findViewById(R.id.total);
scanItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),ScannerView.class).putExtra("rfid",rfidNo));
}
});
payBill.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkout();
}
});
LinearLayoutManager manager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(manager);
recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
productAdaptar = new ProductAdaptar(this::clickedItem, this);
Intent intent =getIntent();
if(intent.getExtras()!=null){
rfidNo= intent.getStringExtra("rfid");
}
getAllProducts(rfidNo);
}
public void getAllProducts(String rfidno){
LinearLayoutManager manager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(manager);
productAdaptar = new ProductAdaptar(this::clickedItem,this);
productList= ApiClient.getUserPageService().getCartItems(rfidno);
productList.enqueue(new Callback<List<UserLoginResp>>() {
#Override
public void onResponse(Call<List<UserLoginResp>> call, Response<List<UserLoginResp>> response) {
if (response.isSuccessful()) {
productListsItems = response.body();
productAdaptar.setData(productListsItems);
RecyclerView recyclerView = findViewById(R.id.recyclerview);
recyclerView.setAdapter(productAdaptar);
getTotal();
}
}
#Override
public void onFailure(Call<List<UserLoginResp>> call, Throwable t) {
Log.e("listfailed",t.getLocalizedMessage());
}
});
}
public void getTotal(){
Call<getBill> bill = ApiClient.getUserPageService().getBill(rfidNo);
bill.enqueue(new Callback<getBill>() {
#Override
public void onResponse(Call<getBill> call, Response<getBill> response) {
if(response.isSuccessful()){
getBill getBill = response.body();
String bill = String.valueOf(getBill.getBill());
total.setText(bill);
}
}
#Override
public void onFailure(Call<getBill> call, Throwable t) {
Log.e("bill error",""+t);
}
});
}
public void checkout(){
Call<String> payment= APIClientString.getUserPageService().checkout(rfidNo);
payment.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if(response.isSuccessful()){
getAllProducts(rfidNo);
Toast.makeText(UserPage.this, "Payment Successful", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Log.e("paymentfail",""+t);
}
});
}
#Override
public void clickedItem(UserLoginResp userLoginResp) {
Log.e("clicked prodcut", userLoginResp.toString());
}
}
ScannerView Class
enter #Override
public void handleResult(Result rawResult) {
barcode = rawResult.getText();
if(addItem(barcode,rfidNo)) {
userPage.getAllProducts(rfidNo);
}
onBackPressed();
}
public boolean addItem(String barcode,String rfidNo){
final boolean[] res = {false};
Call<String> resp = APIClientString.getUserPageService().addProduct(barcode,rfidNo);
resp.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if(response.isSuccessful()){
Toast.makeText(ScannerView.this, response.body().toString(), Toast.LENGTH_SHORT).show();
res[0] =true;
}
}
This is the scanner class which is suppose to call the call the getAllproducts function from the UserPage Activity to refresh the view. It shows no error but the recycler view doesn't get updated.
This is the Adapter Class
public class ProductAdaptar extends RecyclerView.Adapter<ProductAdaptar.ProductAdaptarVH> {
private List<UserLoginResp> productListItems;
private UserPage context;
private clickedItem clickedItem;
public ProductAdaptar(clickedItem clickedItem, UserPage activity) {
this.clickedItem = clickedItem;
this.context= activity;
}
public void setData(List<UserLoginResp> productListItems) {
this.productListItems = productListItems;
notifyDataSetChanged();
}
#NonNull
#Override
public ProductAdaptarVH onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new ProductAdaptar.ProductAdaptarVH(LayoutInflater.
from(context).inflate(R.layout.row_products,parent,false));
}
#Override
public void onBindViewHolder(#NonNull ProductAdaptarVH holder, int position) {
UserLoginResp userLoginResp = productListItems.get(position);
String pName = userLoginResp.getProductName();
String pQuan = userLoginResp.getQuantity();
String pPrice = userLoginResp.getProductPrice();
String pBarcode = userLoginResp.getProductID();
String userID = userLoginResp.getUserID();
holder.pName.setText(pName);
holder.pQuan.setText(pQuan);
holder.pPrice.setText(pPrice);
holder.delProdcut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
delProduct(userID,pBarcode);
}
});
holder.moreDetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
public interface clickedItem{
public void clickedItem(UserLoginResp userLoginResp);
}
public void delProduct(String userID, String pBarcode){
Call<String> res = APIClientString.getUserPageService().deleteProduct(pBarcode,userID);
res.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if(response.isSuccessful()){
Toast.makeText(context, response.body().toString(), Toast.LENGTH_SHORT).show();
context.getAllProducts(userID);
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Log.e("deletefailed",""+t);
}
});
}
#Override
public int getItemCount() {
return productListItems.size();
}
public static class ProductAdaptarVH extends RecyclerView.ViewHolder {
TextView pName;
TextView pQuan;
TextView pPrice;
Button delProdcut;
Button moreDetails;
public ProductAdaptarVH(#NonNull View itemView) {
super(itemView);
pName=itemView.findViewById(R.id.pName);
pQuan=itemView.findViewById(R.id.pQuantity);
pPrice=itemView.findViewById(R.id.pPrice);
delProdcut=itemView.findViewById(R.id.delProduct);
moreDetails=itemView.findViewById(R.id.moreDetails);
}
}
}
In this Product Apdapter there is a delete product item function
holder.delProdcut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
delProduct(userID,pBarcode);
}
});
public void delProduct(String userID, String pBarcode){
Call<String> res = APIClientString.getUserPageService().deleteProduct(pBarcode,userID);
res.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if(response.isSuccessful()){
Toast.makeText(context, response.body().toString(), Toast.LENGTH_SHORT).show();
context.getAllProducts(userID);
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Log.e("deletefailed",""+t);
}
});
}
Which also calls the getProduts function from UserPage activity and it works perfectly fine but the AddItem function doesn't refresh the view.
The Retrofit APIs are working completly fine too, the problem is only with refreshing the recycler view display on Item Add.
I am new to android coding so I can't seem to understand how to do it.
As you are refreshing your adapter using getAllProducts() method but it is being called in onCreate(). Now whenever you start a ScannerView activity, UserPage activity gets paused and then started (not created) when ScannerView activity finishes. So, you should call getAllProducts() in onStart() method like this:
#Override
protected void onStart() {
super.onStart();
Intent intent = getIntent();
if (intent.getExtras() != null) {
rfidNo = intent.getStringExtra("rfid");
}
getAllProducts(rfidNo);
}

When I run my app it's ok only at the firts time only

This is the code of my fragment, when i created a recyclerview, when i can see a list if I click on I can see detail in antoher page, but when I come back I can't see the list.
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SharedPreferences pref = getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
adapter = new PlatformAdapter(data);
recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
//recyclerView.setAdapter(adapter);
if (pref.getBoolean("firstTime", true)) {
RequestVolley.getInstance(getContext())
.doGetRequest("http://www....json", new RequestVolley.OnCompleteCallback() {
#Override
public void onCompleted(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.optJSONObject(i);
if (object != null) {
data.add(Platform.parseJSON(object));
}
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
new Thread(new Runnable() {
#Override
public void run() {
DB.getInstance(getContext()).getPlatformDao().insert(data);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged();
}
});
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("firstTime", false);
editor.apply();
final PlatformAdapter adapter = new PlatformAdapter(data);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
recyclerView.setAdapter(adapter);
}
});
}
}).start();
}
if(pref.getBoolean("firstTime",false)){
new Thread(new Runnable() {
#Override
public void run() {
data.addAll(DB.getInstance(getContext()).getPlatformDao().findAll());
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged();
}
});
final PlatformAdapter adapter = new PlatformAdapter(data);
recyclerView.post(new Runnable() {
#Override
public void run() {
recyclerView.setAdapter(adapter);
}
});
}
}).start();
}
}
}
this is the code of my app in the point of inserto or reload from roomDatabase, the first time I oper the page it's ok, but the second time I can see only a white page.Why? I dont'have any error.
Why it isn't on the DB, or it isn't reload?
This is my Dao
#Dao
public interface PlatformDao {
#Insert(onConflict = OnConflictStrategy.REPLACE)
public void insertOne(Platform platform);
#Insert(onConflict=OnConflictStrategy.REPLACE)
public void insert(List<Platform> platforms);
#Insert(onConflict=OnConflictStrategy.REPLACE)
public void insertVarArgs(Platform...platforms);
#Update
public void update(Platform platform);
#Delete
public void delete(Platform platform);
#Query("SELECT * FROM platforms")
public List<Platform> findAll();
#Query("SELECT * FROM platforms WHERE cdenominazione__=:cdenominazione__")
public Platform findById(String cdenominazione__);
}
When you add the fragment are you doing an add or a replace? Aso are you adding the fragment to the backstack?

how to stop recyclerview automatic refresh when a new item added firebase Realtime database

Hey I am making an app that has a feature to upload Instagram reels like videos and I setup exoplayer in recycler view but when new data is added by another user or a user uploaded a new reel the recycler view automatic refresh on another mobile and all the videos are stuck please help here is my code
public class NotificationFragemt extends Fragment implements Player.EventListener {
private RecyclerView recyclerView;
List<ModelVideos> videosList;
int currentPage=-1;
LinearLayoutManager layoutManager;
boolean is_user_stop_video=false;
VideoAdapter videoAdapter;
private CardView plus_card;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_notification_fragemt, container, false);
// getActivity().getWindow().setStatusBarColor(getActivity().getColor(R.color.black));
// Inflate the layout for this fragment
recyclerView = view.findViewById(R.id.videorecyclerview);
videosList = new ArrayList<>();
layoutManager=new LinearLayoutManager(getContext());
recyclerView.setHasFixedSize(false);
plus_card = view.findViewById(R.id.plus_card);
plus_card.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), Upload_reels.class);
startActivity(intent);
}
});
// LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,true);
// layoutManager.setStackFromEnd(true);
// layoutManager.setReverseLayout(true);
recyclerView.setLayoutManager(layoutManager);
SnapHelper snapHelper = new PagerSnapHelper();
snapHelper.attachToRecyclerView(recyclerView);
Collections.shuffle(videosList);
videoAdapter = new VideoAdapter(getActivity(),videosList);
loadpost();
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
//here we find the current item number
final int scrollOffset = recyclerView.computeVerticalScrollOffset();
final int height = recyclerView.getHeight();
int page_no=scrollOffset / height;
if(page_no!=currentPage ){
currentPage=page_no;
Release_Previous_Player();
Set_Player(currentPage);
}
}
});
return view;
}
SimpleExoPlayer privious_player;
public void Release_Previous_Player(){
if(privious_player!=null) {
privious_player.removeListener(this);
privious_player.release();
}
}
private void loadpost() {
DatabaseReference ref;
ref = FirebaseDatabase.getInstance().getReference("TravelReels");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
videosList.clear();
for (DataSnapshot ds : snapshot.getChildren()){
ModelVideos modelPost = ds.getValue(ModelVideos.class);
videosList.add(modelPost);
Collections.reverse(videosList);
Collections.shuffle(videosList);
}
setAdapter();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void setAdapter() {
if (!videoAdapter.hasObservers()) {
videoAdapter.setHasStableIds(true);
}
recyclerView.setAdapter(videoAdapter);
}
public boolean is_fragment_exits(){
FragmentManager fm = getActivity().getSupportFragmentManager();
if(fm.getBackStackEntryCount()==0){
return false;
}else {
return true;
}
}
public void Set_Player(int currentPage){
try {
LoadControl loadControl = new DefaultLoadControl.Builder()
.setAllocator(new DefaultAllocator(true, 16))
.setBufferDurationsMs(1 * 1024, 1 * 1024, 500, 1024)
.setTargetBufferBytes(-1)
.setPrioritizeTimeOverSizeThresholds(true)
.createDefaultLoadControl();
DefaultTrackSelector trackSelector = new DefaultTrackSelector();
final SimpleExoPlayer player = ExoPlayerFactory.newSimpleInstance(getContext(), trackSelector, loadControl);
DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(getContext(),
Util.getUserAgent(getContext(), getContext().getResources().getString(R.string.app_name)));
Log.d("video_url"+currentPage,videosList.get(currentPage).getVideoUrl());
MediaSource videoSource = new ExtractorMediaSource.Factory(dataSourceFactory)
.createMediaSource(Uri.parse(videosList.get(currentPage).getVideoUrl()));
/* MediaSource videoSource = new ExtractorMediaSource.Factory(dataSourceFactory)
.createMediaSource(Uri.parse(proxyUrl));
Log.d(Variables.tag,item.video_url);
Log.d(Variables.tag,proxyUrl);*/
player.prepare(videoSource);
player.setRepeatMode(Player.REPEAT_MODE_ALL);
player.addListener(this);
View layout = layoutManager.findViewByPosition(currentPage);
final PlayerView playerView = layout.findViewById(R.id.reels_player);
playerView.setPlayer(player);
player.setPlayWhenReady(is_visible_to_user);
privious_player = player;
}
catch (Exception e){
}
}
boolean is_visible_to_user;
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
is_visible_to_user=isVisibleToUser;
if(privious_player!=null && (isVisibleToUser && !is_user_stop_video)){
privious_player.setPlayWhenReady(true);
}
else if(privious_player!=null && !isVisibleToUser){
privious_player.setPlayWhenReady(false);
}
}
#Override
public void onResume() {
super.onResume();
is_visible_to_user = true;
if((privious_player!=null && (!is_user_stop_video)) && !is_fragment_exits() ){
privious_player.setPlayWhenReady(true);
}
}
#Override
public void onPause() {
super.onPause();
if(privious_player!=null){
privious_player.setPlayWhenReady(false);
}
}
#Override
public void onStop() {
super.onStop();
if(privious_player!=null){
privious_player.setPlayWhenReady(false);
}
}
#Override
public void onDestroy() {
super.onDestroy();
if(privious_player!=null){
privious_player.release();
}
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onTimelineChanged(Timeline timeline, #Nullable Object manifest, int reason) {
}
#Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
}
#Override
public void onLoadingChanged(boolean isLoading) {
}
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
}
#Override
public void onRepeatModeChanged(int repeatMode) {
}
#Override
public void onShuffleModeEnabledChanged(boolean shuffleModeEnabled) {
}
#Override
public void onPlayerError(ExoPlaybackException error) {
}
#Override
public void onPositionDiscontinuity(int reason) {
}
#Override
public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
}
#Override
public void onSeekProcessed() {
}
}
Inside your loadpost function you're using addValueEventListener which calls onDataChange everytime there is a change in your TravelReels node.
If you don't want that it should listen to these continues changes. Only load the data once. Then you can use addListenerForSingleValueEvent which will get called only once. Read more here: https://firebase.google.com/docs/database/android/read-and-write#read_once_using_a_listener
But if you want to control it yourself then just add one boolean flag shouldRefresh make it true /false according to your needs & notify adapter only when it's true. Write you logic.

android viewpager2 page buton controller

if the page is loaded, the button is active, if not, how can I do passive control?
What I want to do is, if the Viewpager Page is loaded, the button is active, if not, the Button is Passive. But I couldn't do any kind.
Is there anyone who can help?
If viewpager2 is installed Button enabled, if viewpager2 is not installed button false;
List<Movie> movieList = new ArrayList<>();
private ImageButton btn_down, btn_fav;
private Button btn_setter;
private DatabaseReference movies;
private IFirebaseLoadDone iFirebaseLoadDone;
public CartoonFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_cartoon, container, false);
movies = FirebaseDatabase.getInstance().getReference("Sports");
movies.keepSynced(true);
iFirebaseLoadDone = this;
loadMovie();
viewPager2 = view.findViewById(R.id.viewPager2_);
btn_down = view.findViewById(R.id.btn_down);
btn_setter = view.findViewById(R.id.btn_setter);
btn_fav = view.findViewById(R.id.btn_fav);
btn_down.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SaveToGallery();
}
});
btn_setter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
btn_fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return view;
}
private void loadMovie() {
movies.addValueEventListener(this);
}
#Override
public void onFirebaseLoadSuccess(List<Movie> movieList) {
viewPagerAdapter = new ViewPagerAdapter(getContext(), movieList, viewPager2);
viewPager2.setAdapter(viewPagerAdapter);
}
#Override
public void onFirebasLoadFailed(String message) {
}
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot moviesSnapShot : dataSnapshot.getChildren())
movieList.add(moviesSnapShot.getValue(Movie.class));
Collections.reverse(movieList);
iFirebaseLoadDone.onFirebaseLoadSuccess(movieList);
viewPagerAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
iFirebaseLoadDone.onFirebasLoadFailed(databaseError.getMessage());
}
#Override
public void onDestroy() {
movies.removeEventListener(this);
super.onDestroy();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onStop() {
movies.removeEventListener(this);
super.onStop();
}
}
Replace your methods with mine.
private void loadMovie() {
movies.addValueEventListener(this);
btn_down.setEnabled(false);
btn_fav.setEnabled(false);
btn_setter.setEnabled(false);
}
Firebase methods
#Override
public void onFirebaseLoadSuccess(List<Movie> movieList) {
viewPagerAdapter = new ViewPagerAdapter(getContext(), movieList, viewPager2);
viewPager2.setAdapter(viewPagerAdapter);
if(movieList!=null && !movieList.isEmpty()){
btn_down.setEnabled(true);
btn_fav.setEnabled(true);
btn_setter.setEnabled(true);
}
}
#Override
public void onFirebasLoadFailed(String message) {
btn_down.setEnabled(false);
btn_fav.setEnabled(false);
btn_setter.setEnabled(false);
}
There was an error loading
private void loadMovie() {
movies.addValueEventListener(this);
btn_down.setEnabled(false);
btn_fav.setEnabled(false);
btn_setter.setEnabled(false);
}
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setEnabled(boolean)' on a null object reference
at com.example.duvarlar.Fragment.CartoonFragment.loadMovie(CartoonFragment.java:386)
at com.example.duvarlar.Fragment.CartoonFragment.onCreateView(CartoonFragment.java:90)

Firebase Recycler Adapter is not showing my Recyclerview in Fragments

Basically i followed the accepted answer of this with few changes in my Activity and it worked perfect. My problem is that I wrote the exact same codes for my Fragment. when I open my app, it doesn't show anything. Before I changed my code in my fragment from a custom Adapter to the FirebaseRecyclerAdapter, everything worked fine.
This is my Fragment class
public class HomeFragment extends BaseFragment {
public Button buttonsrch, openFreezer, openRef, openPantry, scrollToFreezer, scrollToRef, scrollToPantry;
public NestedScrollView scrollView;
public RelativeLayout mFreezerLayout,mRefrigeratorLayout, mPantryLayout;
public FloatingActionButton mAddItems;
public DatabaseReference mDatabaseFreezer;
public RecyclerView mFreezerRecyclerView;
public ArrayList<Event> mDataSet;
private FirebaseRecyclerAdapter<Event, ProductHolder> firebaseRecyclerAdapter;
#Override
public int getLayoutResId() {
return R.layout.fragment_home;
}
#Override
public View inOnCreateView(View root, #Nullable ViewGroup container, Bundle savedInstancesState) {
View view = mRoot;
buttonsrch = view.findViewById(R.id.searchButton);
openPantry = view.findViewById(R.id.ShowMorePantry);
openRef = view.findViewById(R.id.ShowMoreRefrigerator);
openFreezer = view.findViewById(R.id.ShowMoreFreezer);
scrollToFreezer = view.findViewById(R.id.bringToFreezer);
scrollToPantry = view.findViewById(R.id.bringToPantry);
scrollToRef = view.findViewById(R.id.bringToRefrigerator);
scrollView = view.findViewById(R.id.scrollViewHomeFragment);
mFreezerLayout = view.findViewById(R.id.FreezerLayout);
mPantryLayout =view.findViewById(R.id.PantryRelativeLayout);
mRefrigeratorLayout = view.findViewById(R.id.RefrigeratorRelativeLayout);
mAddItems = view.findViewById(R.id.addItems_Inventory);
mAddItems.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getActivity(), AddInventoryActivity.class));
}
});
buttonsrch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getActivity(), Search_Activity.class);
getActivity().startActivity(i);
}
});
openPantry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent h = new Intent(getActivity(), PantryActivity.class);
getActivity().startActivity(h);
}
});
openRef.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent g = new Intent(getActivity(), RefActivity.class);
getActivity().startActivity(g);
}
});
openFreezer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent s = new Intent(getActivity(), FreezerActivity.class);
getActivity().startActivity(s);
}
});
scrollToFreezer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FocusToFreezer();
}
});
scrollToRef.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FocusToRef();
}
});
scrollToPantry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FocusToPantry();
}
});
mDataSet = new ArrayList<>();
mFreezerRecyclerView = view.findViewById(R.id.FreezerRecyclerView);
mFreezerRecyclerView.setHasFixedSize(true);
mFreezerRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mDatabaseFreezer = FirebaseDatabase.getInstance().getReference().child("FreezerItems");
Query query = mDatabaseFreezer;
FirebaseRecyclerOptions<Event> firebaseRecyclerOptions = new FirebaseRecyclerOptions.Builder<Event>()
.setQuery(query, Event.class).build();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Event, ProductHolder>(firebaseRecyclerOptions) {
#Override
protected void onBindViewHolder(ProductHolder holder, int position, Event model) {
model = mDataSet.get(position);
holder.mItemName.setText(model.getName());
holder.mItemDate.setText(model.getDate());
final Event finalModel = model;
holder.mDeleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDatabaseFreezer.child(finalModel.get_id()).removeValue();
}
});
}
#Override
public ProductHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recycler_view_row_inventory,parent,false);
return new ProductHolder(view);
}
};
mDatabaseFreezer.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
HashMap<String, String> value = (HashMap<String,String>) dataSnapshot.getValue();
if (value != null) {
String name = value.get("Name");
String date = value.get("Date");
String key = value.get("Key");
mDataSet.add(new Event(name,date,null, key));
Collections.sort(mDataSet, new Comparator<Event>() {
#Override
public int compare(Event event, Event t1) {
if (event.getDate() == null || t1.getDate() == null)
return 0;
return event.getDate().compareTo(t1.getDate());
}
});
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mFreezerRecyclerView.setAdapter(firebaseRecyclerAdapter);
return root;
}
private class ProductHolder extends RecyclerView.ViewHolder{
private TextView mItemName, mItemDate;
private Button mDeleteBtn;
public ProductHolder(View itemView) {
super(itemView);
mItemName = itemView.findViewById(R.id.ItemNameTxtView);
mItemDate = itemView.findViewById(R.id.BestBeoforeTxtView);
mDeleteBtn = itemView.findViewById(R.id.deleteItem);
}
}
#Override
public void onStart() {
super.onStart();
firebaseRecyclerAdapter.startListening();
}
#Override
public void onStop() {
super.onStop();
if (firebaseRecyclerAdapter != null){
firebaseRecyclerAdapter.startListening();
}
}
private void FocusToFreezer(){
scrollView.post(new Runnable() {
#Override
public void run() {
scrollView.smoothScrollTo(0, mFreezerLayout.getTop());
}
});
}
private void FocusToRef(){
scrollView.post(new Runnable() {
#Override
public void run() {
scrollView.smoothScrollTo(0, mRefrigeratorLayout.getTop());
}
});
}
private void FocusToPantry(){
scrollView.post(new Runnable() {
#Override
public void run() {
scrollView.smoothScrollTo(0, mPantryLayout.getTop());
}
});
}
}
The only difference I could find is OnStart() and onStop() in activity are protected while on fragments are public
EDIT I found another page with the same problem and apparently FirebaseRecyclerAdapter doesn't work well with Fragments
I finally found an answer
simply remove mFreezerRecyclerView.setHasFixedSize(true);

Categories

Resources