I'm making a voting system in an android app that uses firebase as it's backend. I'm in the process of getting the user's vote status from their history, updating the view accordingly, and responding to vote touches on the buttons. The problem I'm having is that when a user clicks on the up or down vote buttons it redraws the listview, sometimes omitting two of the options, and always moving the scrolling of the view back up to the top. Can I update the data inside of a listview without completely redrawing that listview? If so, how?
MovieActivity.java
public class MovieActivity extends AppCompatActivity {
private static final String KEY_IMDB = "KEY_IMDB";
private ImageView mPosterImageView;
private TextView mTitleTextView;
private TextView mYearTextView;
private TextView mSummaryTextView;
private ListView triggerListView;
private ArrayList<Trigger> mTriggerPrefList;
private Movie mMovie;
private LinkedList<Trigger> resultList;
DatabaseReference movieDB;
DatabaseReference userDB;
DatabaseReference thisMovieDB;
DatabaseReference triggerDB;
DatabaseReference adminDB;
FirebaseAuth mFirebaseAuth;
FirebaseUser mUser;
ArrayList<Trigger> mTriggerList;
String imdbID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie);
mPosterImageView = (ImageView) findViewById(R.id.posterImageView);
mTitleTextView = (TextView) findViewById(R.id.titleTextView);
mYearTextView = (TextView) findViewById(R.id.yearTextView);
mSummaryTextView = (TextView) findViewById(R.id.summaryTextView);
triggerListView = (ListView) findViewById(R.id.triggerListView);
mFirebaseAuth = FirebaseAuth.getInstance();
mUser = mFirebaseAuth.getCurrentUser();
movieDB = FirebaseDatabase.getInstance().getReference("movies");
userDB = FirebaseDatabase.getInstance().getReference("users");
adminDB = FirebaseDatabase.getInstance().getReference("admin");
Intent intent = getIntent();
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
imdbID = intent.getStringExtra("ID_KEY");
final String keyTitle = intent.getStringExtra("TITLE_KEY");
final String keyYear = intent.getStringExtra("YEAR_KEY");
final String keyPoster = intent.getStringExtra("POSTER_KEY");
try {
getMovieDetails(imdbID, new Runnable() {
#Override
public void run() {
CheckForTriggerValues(new Runnable() {
#Override
public void run() {
populateTriggers(new Runnable() {
#Override
public void run() {
populatePrefs(new Runnable() {
#Override
public void run() {
reOrderList(new Runnable() {
#Override
public void run() {
Movie passMovie = new Movie();
passMovie.setImdbID(imdbID);
passMovie.setPosterURL(keyPoster);
passMovie.setYear(keyYear);
passMovie.setTitle(keyTitle);
TriggerAdapter adapter = new TriggerAdapter(MovieActivity.this, resultList, passMovie, imdbID );
triggerListView.setAdapter(adapter);
}
});
}
});
}
});
}
});
}
});
} catch (JSONException e) {
e.printStackTrace();
}
thisMovieDB = movieDB.child(imdbID);
triggerDB = thisMovieDB.child("Triggers");
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(KEY_IMDB, imdbID);
}
#Override
protected void onStart() {
super.onStart();
Intent intent = getIntent();
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
imdbID = intent.getStringExtra("ID_KEY");
}
private void getMovieDetails(String imdbID, Runnable runnable) throws JSONException {
String apiKey = OMITTED;
String theURL = "http://www.omdbapi.com/?i=" + imdbID + "&apikey=" + apiKey;
final OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(theURL).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
final String jsonData = response.body().string();
if (response.isSuccessful()) {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
Movie movie = parseMovieDetails(jsonData);
updateMovieUI(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
});
runnable.run();
}
private Movie parseMovieDetails(String jsonData) throws JSONException {
JSONObject jsonObject = new JSONObject(jsonData);
Movie movie = new Movie();
movie.setPosterURL(jsonObject.getString("Poster"));
movie.setTitle(jsonObject.getString("Title"));
movie.setYear(jsonObject.getString("Year"));
movie.setSummary(jsonObject.getString("Plot"));
mMovie = movie;
return movie;
}
private void updateMovieUI(Movie movie){
Context mContext = getApplicationContext();
mSummaryTextView.setText(movie.getSummary());
mYearTextView.setText(movie.getYear());
mTitleTextView.setText(movie.getTitle());
Picasso.with(mContext).load(movie.getPosterURL()).into(mPosterImageView);
}
private void populatePrefs(final Runnable runnable) {
mTriggerPrefList = new ArrayList<>();
mFirebaseAuth = FirebaseAuth.getInstance();
mUser = mFirebaseAuth.getCurrentUser();
movieDB = FirebaseDatabase.getInstance().getReference("movies");
userDB = FirebaseDatabase.getInstance().getReference("users");
adminDB = FirebaseDatabase.getInstance().getReference("admin");
thisMovieDB = movieDB.child(imdbID);
thisMovieDB.child("Details").setValue(mMovie);
triggerDB = thisMovieDB.child("Triggers");
userDB.child(mUser.getUid()).child("preferences").child("trigger").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot triggerSnapshot : dataSnapshot.getChildren()) {
String name = String.valueOf(triggerSnapshot.child("triggerName").getValue());
Trigger trigger = new Trigger();
trigger.setTriggerName(name);
trigger.setTriggerVotesTotal(0);
trigger.setTriggerVotesYes(0);
mTriggerPrefList.add(trigger);
}
Intent intent = getIntent();
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
imdbID = intent.getStringExtra("ID_KEY");
runnable.run();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void populateTriggers(final Runnable runnable) {
mTriggerList = new ArrayList<>();
mFirebaseAuth = FirebaseAuth.getInstance();
mUser = mFirebaseAuth.getCurrentUser();
movieDB = FirebaseDatabase.getInstance().getReference("movies");
userDB = FirebaseDatabase.getInstance().getReference("users");
adminDB = FirebaseDatabase.getInstance().getReference("admin");
thisMovieDB = movieDB.child(imdbID);
thisMovieDB.child("Details").setValue(mMovie);
triggerDB = thisMovieDB.child("Triggers");
triggerDB.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mTriggerList.clear();
for (DataSnapshot triggerSnapshot : dataSnapshot.getChildren()) {
Trigger trigger = triggerSnapshot.getValue(Trigger.class);
mTriggerList.add(trigger);
}
runnable.run();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void reOrderList(Runnable runnable) {
resultList = new LinkedList<>();
for (Trigger triggerA : mTriggerList) {
boolean found = false;
for (Trigger triggerB : mTriggerPrefList) {
if (triggerB.getTriggerName().equals(triggerA.getTriggerName())) {
found = true;
}
}
if (found) {
resultList.add(triggerA);
}
}
mTriggerList.removeAll(resultList);
resultList.addAll(mTriggerList);
runnable.run();
}
private void CheckForTriggerValues(final Runnable runnable) {
adminDB.child("triggerList").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
GenericTypeIndicator<Map<String, Object>> genericTypeIndicator = new GenericTypeIndicator<Map<String, Object>>() {};
final Map<String, Object> triggerList = dataSnapshot.getValue(genericTypeIndicator);
triggerDB.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (Map.Entry<String, Object> entry : triggerList.entrySet())
{
if (dataSnapshot.hasChild(entry.getKey())){
}
else {
Trigger trigger1 = new Trigger(entry.getKey(), 0, 0);
triggerDB.child(trigger1.getTriggerName()).setValue(trigger1);
}
}
runnable.run();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
int isTrue(Boolean boolDown, Boolean boolUp) {
int x = 0;
if (boolUp) {
x = 1;
}
if (boolDown) {
x = -1;
}
return x;
}
}
TriggerAdapter.java
package me.paxana.cwnet.Adapters;
import android.app.Activity;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Typeface;
import android.os.Build;
import android.provider.ContactsContract;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import com.andremion.counterfab.CounterFab;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
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.MutableData;
import com.google.firebase.database.Transaction;
import com.google.firebase.database.ValueEventListener;
import java.util.List;
import me.paxana.cwnet.Model.Movie;
import me.paxana.cwnet.Model.Trigger;
import me.paxana.cwnet.R;
import me.paxana.cwnet.ui.AdminPanelActivity;
import me.paxana.cwnet.ui.MovieActivity;
/**
* Created by paxie on 10/11/17.
*/
public class TriggerAdapter extends BaseAdapter {
private Context mContext;
private List<Trigger> mTriggers;
private Movie mMovie;
private String mImdbID;
private String mTitle;
private String mYear;
private String mPosterURL;
private DatabaseReference movieDB;
private DatabaseReference userDB;
private DatabaseReference triggerDB;
private DatabaseReference adminDB;
public TriggerAdapter(Context context, List<Trigger> triggerList, Movie movie, String imdbID){
mContext = context;
this.mTriggers = triggerList;
mMovie = movie;
mImdbID = imdbID;
mTitle = movie.getTitle();
mYear = movie.getYear();
mPosterURL = movie.getPosterURL();
};
public TriggerAdapter(Context context, List<Trigger> triggerList) {
mContext = context;
this.mTriggers = triggerList;
}
#Override
public int getCount() {
return this.mTriggers.size();
}
#Override
public Object getItem(int i) {
return mTriggers.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, final ViewGroup viewGroup) {
final ViewHolder holder;
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser user = firebaseAuth.getCurrentUser();
movieDB = FirebaseDatabase.getInstance().getReference("movies");
userDB = FirebaseDatabase.getInstance().getReference("users");
adminDB = FirebaseDatabase.getInstance().getReference("admin");
final String mUserId = user.getUid();
final Trigger trigger = mTriggers.get(i);
if (view == null) {
view = LayoutInflater.from(mContext).inflate(R.layout.trigger_list_item, null);
holder = new ViewHolder();
holder.triggerName = view.findViewById(R.id.triggerName);
holder.upButton = view.findViewById(R.id.mTriggerButtonUp);
holder.downButton = view.findViewById(R.id.mTriggerButtonDown);
holder.total = view.findViewById(R.id.triggerCounter);
view.setTag(holder);
}
else {
holder = (ViewHolder) view.getTag();
}
holder.triggerName.setText(trigger.getTriggerName());
if (mContext instanceof AdminPanelActivity) {
holder.upButton.setVisibility(View.INVISIBLE);
holder.downButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
adminDB.child("triggerList").child(trigger.getTriggerName()).removeValue();
int i = mTriggers.indexOf(trigger);
mTriggers.remove(i);
TriggerAdapter.this.notifyDataSetChanged();
}
});
}
if (mContext instanceof MovieActivity) {
userDB.child(mUserId).child("changes").child(mImdbID).child("triggers").child(trigger.getTriggerName()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
int userVote = dataSnapshot.getValue(Integer.class);
if (userVote == 0) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
holder.upButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.colorAccent, null));
holder.downButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.colorAccent, null));
}
else {
holder.upButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.colorAccent));
holder.downButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.colorAccent));
}
neitherButtonIsSelected(holder, trigger, mUserId);
}
if (userVote == 1) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
holder.upButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.votebuttons, null));
holder.downButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.colorAccent, null));
}
else {
holder.upButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.votebuttons));
holder.downButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.colorAccent));
}
upButtonIsSelected(holder, trigger, mUserId);
}
if (userVote == -1) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
holder.upButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.colorAccent, null));
holder.downButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.votebuttons, null));
}
else {
holder.upButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.colorAccent));
holder.downButton.setBackgroundTintList(mContext.getResources().getColorStateList(R.color.votebuttons));
}
downButtonIsSelected(holder, trigger, mUserId);
}
}
else {
userDB.child(mUserId).child("changes").child(mImdbID).child("triggers").child(trigger.getTriggerName()).setValue(0);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
holder.total.setText(String.valueOf(trigger.getTriggerVotesYes()));
holder.upButton.setCount(trigger.getTriggerVotesYes());
if (trigger.getTriggerVotesTotal() != 0){
holder.total.setText(String.valueOf(trigger.getTriggerVotesTotal()));
int downButtonCount = (trigger.getTriggerVotesTotal() - trigger.getTriggerVotesYes());
holder.downButton.setCount(downButtonCount);
}
return view;
}
private static class ViewHolder {
TextView triggerName;
CounterFab upButton;
CounterFab downButton;
TextView total;
}
private void neitherButtonIsSelected(final ViewHolder holder, final Trigger trigger, final String mUserId) {
holder.upButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
triggerDB = movieDB.child(mImdbID).child("Triggers").child(trigger.getTriggerName());
triggerDB.child("triggerVotesYes").runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
int count = mutableData.getValue(Integer.class);
mutableData.setValue(count + 1);
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
}
});
triggerDB.child("triggerVotesTotal").runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
int count = mutableData.getValue(Integer.class);
mutableData.setValue(count + 1);
userDB.child(mUserId).child("changes").child(mImdbID).child("triggers").child(trigger.getTriggerName()).setValue(1);
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
}
});
userDB.child(mUserId).child("changes").child(mImdbID).child("triggers").child(trigger.getTriggerName()).setValue(1);
}
});
holder.downButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
triggerDB.child("triggerVotesTotal").runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
int count = mutableData.getValue(Integer.class);
mutableData.setValue(count + 1);
userDB.child(mUserId).child("changes").child(mImdbID).child("triggers").child(trigger.getTriggerName()).setValue(1);
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
}
});
userDB.child(mUserId).child("changes").child(mImdbID).child("triggers").child(trigger.getTriggerName()).setValue(1);
}
});
}
private void upButtonIsSelected(final ViewHolder holder, final Trigger trigger, final String mUserId) {
holder.upButton.setOnClickListener(null);
holder.downButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
triggerDB = movieDB.child(mImdbID).child("Triggers").child(trigger.getTriggerName());
triggerDB.child("triggerVotesYes").runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
int count = mutableData.getValue(Integer.class);
mutableData.setValue(count - 1);
userDB.child(mUserId).child("changes").child(mImdbID).child("triggers").child(trigger.getTriggerName()).setValue(-1);
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
holder.downButton.getBackground().setAlpha(127);
}
});
}
});
}
private void downButtonIsSelected(final ViewHolder holder, final Trigger trigger, final String mUserId) {
holder.downButton.setOnClickListener(null);
holder.upButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
triggerDB = movieDB.child(mImdbID).child("Triggers").child(trigger.getTriggerName());
triggerDB.child("triggerVotesYes").runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
int count = mutableData.getValue(Integer.class);
mutableData.setValue(count + 1);
userDB.child(mUserId).child("changes").child(mImdbID).child("triggers").child(trigger.getTriggerName()).setValue(1);
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
holder.downButton.getBackground().setAlpha(127);
}
});
}
});
}
}
Following things might help you.
Use android:stackFromBottom="true" in the xml of your ListView
Instead of using mTriggerList.clear(); when updating, do not clear it and add the item to list only if the item does not already exist in the list.
Eg.
for(Trigger trigger: triggerSnapShot...){
if (!mTriggerList.contains(trigger)){
mTriggerList.add(trigger);
}
}
You may need to override the equals method in the Trigger class in order to make the method contains work properly.
Related
RETRIEVADATA CLASS
package com.dikolobe.salesagent;
public class RetrieveData extends AppCompatActivity implements View.OnClickListener,OnNoteClickListener{
private static final String TAG = "";
private FirebaseRecyclerAdapter<Product, ViewHolder> firebaseRecyclerAdapter;
//FirebaseRecyclerAdapter adapter;
FirebaseDatabase mDatabase;
DatabaseReference mRef;
FirebaseStorage mStorage;
ItemsAdapter itemsAdapter;
List<Product> productList=new ArrayList<>();
RecyclerView recyclerView;
TextView phone_num;
ViewHolder viewHolder;
private static final int PERMISSION_REQUEST_CODE = 1;
ImageView img;
OnNoteClickListener onNoteClickListener;
Context context;
private List<Product> listItems= new ArrayList<>();
private List<Product> listItemsFull;
public ArrayList<Product> filterList = new ArrayList<>();
private int progressStatus = 0;
private Handler handler = new Handler();
String imageUrl = null;
SearchView searchView;
//ImageView delete;
String productId;
String image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retrieve_data);
// delete =findViewById(R.id.delete);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.SEND_SMS)
== PackageManager.PERMISSION_DENIED) {
Log.d("permission", "permission denied to SEND_SMS - requesting it");
String[] permissions = {Manifest.permission.SEND_SMS};
requestPermissions(permissions, PERMISSION_REQUEST_CODE);
}
}
searchView=findViewById(R.id.search);
FirebaseRecyclerOptions<Product> options = new FirebaseRecyclerOptions.Builder<Product>()
.setQuery(FirebaseDatabase.getInstance().getReference()
.child("Items"),Product.class)
.build();
mDatabase = FirebaseDatabase.getInstance();
mRef = mDatabase.getReference().child("Items");
mStorage = FirebaseStorage.getInstance();
recyclerView = findViewById(R.id.recyclerview_id);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
productList = new ArrayList<Product>();
itemsAdapter = new ItemsAdapter(RetrieveData.this, productList,this,options);
recyclerView.setAdapter(itemsAdapter);
mRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Product product = dataSnapshot.getValue(Product.class);
productList.add(product);
itemsAdapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
protected void onStart(){
super.onStart();
FirebaseRecyclerOptions<Product> options = new FirebaseRecyclerOptions.Builder<Product>()
.setQuery(FirebaseDatabase.getInstance()
.getReference().child("Items"), Product.class)
.build();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Product, ViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull com.dikolobe.salesagent.ViewHolder holder, final int
position, #NonNull Product product) {
}
#NonNull
#Override
public com.dikolobe.salesagent.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int
viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.design_row_for_recyclerview, parent, false);
return new com.dikolobe.salesagent.ViewHolder(view,onNoteClickListener);
}
public void deleteProduct(int position) {
try{
FirebaseDatabase.getInstance().getReference().child("Items")
.child(getRef(position).getKey())
.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(context,"Deleted succesfully",Toast.LENGTH_SHORT).show();
}
});
}
catch (Exception e){
Log.e("error", e.getMessage());
}
}
};
firebaseRecyclerAdapter.startListening();
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
#Override
protected void onStop() {
super.onStop();
firebaseRecyclerAdapter.stopListening();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
MenuItem menuItem=menu.findItem(R.id.search);
SearchView searchView=(SearchView) menuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
search_product(query);
// itemsAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
search_product(newText);
//itemsAdapter.getFilter().filter(newText.toString());
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.add_product) {
startActivity(new Intent(this, MainActivity.class));
Toast.makeText(this, "post a product", Toast.LENGTH_SHORT).show();
} else if (item.getItemId() == R.id.tutorial) {
// startActivity(new Intent(this, AddRider.class));
// Toast.makeText(this,"Add a rider to an Event",Toast.LENGTH_SHORT).show();
} else if (item.getItemId() == R.id.logOut) {
startActivity(new Intent(this, MainActivity.class));
Toast.makeText(this, "bye", Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
ItemTouchHelper.SimpleCallback simpleCallback=new
ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.RIGHT | ItemTouchHelper.LEFT) {
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, Re
cyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
removeItem((long) viewHolder.itemView.getTag());
productList.remove(viewHolder.getAdapterPosition());
itemsAdapter.notifyDataSetChanged();
}
private void removeItem(long id) {
}
};
private boolean updateItem(String seller, String description, String price,String location,String
phone,String productId,String image,String posted_date) {
//getting the specified product reference
DatabaseReference dR = FirebaseDatabase.getInstance().getReference("Items").child(productId);
//updating product
Product product = new Product(productId, seller,
description,price,phone,location,image,posted_date);
dR.setValue(product);
Toast.makeText(getApplicationContext(), "Product Updated", Toast.LENGTH_LONG).show();
return true;
}
#Override
public void onNoteClick(final int position) {
CharSequence[] items = {"Update", "Delete"};
AlertDialog.Builder dialog = new AlertDialog.Builder(RetrieveData.this);
dialog.setTitle("Choose Action");
dialog.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0){
Intent update_activty = new Intent(getApplicationContext(),Update_Product.class);
startActivity(update_activty);
}
if (i==1){
Product product=productList.get(position);
productId =product.getProductId();
image =product.getImage();
final AlertDialog.Builder dialogdelete = new
AlertDialog.Builder(RetrieveData.this);
dialogdelete.setTitle("Warning");
dialogdelete.setMessage("Are You Sure You Want to Delete?");
dialogdelete.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Query mQuery = mRef.orderByChild("productId").equalTo(productId);
mQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds: dataSnapshot.getChildren()){
ds.getRef().removeValue();
}
Toast.makeText(RetrieveData.this,"deleted..!",Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(RetrieveData.this,databaseError.getMessage(),Toast.LENGTH_SHORT).show();
}
});
Query mPictureReference =
FirebaseDatabase.getInstance().getReference("Items").orderByChild("image").equalTo(image);
mPictureReference.getRef().removeValue().addOnSuccessListener(new
OnSuccessListener() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(RetrieveData.this,"Image
deleted",Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(RetrieveData.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
});
dialogdelete.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
dialogdelete.show();
}
}
});
dialog.show();
// Toast.makeText(getApplicationContext(),"cliked",Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View v) {
}
public static String getTimeDate(long timestamp){
try{
DateFormat dateFormat = getDateTimeInstance();
Date netDate = (new Date(timestamp));
return dateFormat.format(netDate);
} catch(Exception e) {
return "date";
}
}
}
ADAPTER CLASS
package com.dikolobe.salesagent;
public class ItemsAdapter extends RecyclerView.Adapter implements Filterable {
public ArrayList<Product> filterList = new ArrayList<>();
private int progressStatus = 0;
private Handler handler = new Handler();
private OnNoteClickListener onNoteClickListener;
Context context;
private List<Product> listItems;
private List<Product> listItemsFull;
private Product product;
FirebaseRecyclerOptions<Product> options;
String imageUrl = null;
public ItemsAdapter(Context context, List<Product> listItems,OnNoteClickListener
onNoteClickListener,FirebaseRecyclerOptions options) {
this.context = context;
this.listItems = listItems;
listItemsFull = new ArrayList<>(listItems);
this.onNoteClickListener = onNoteClickListener;
this.options=options;
}
public ItemsAdapter(FirebaseRecyclerOptions<Product> options) {
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v =
LayoutInflater.from(parent.getContext()).inflate(R.layout.design_row_for_recyclerview,parent,false);
return new ViewHolder(v,onNoteClickListener);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
product = listItems.get(position);
holder.seller.setText(listItems.get(position).getSeller());
holder.desc.setText(listItems.get(position).getDescription());
holder.price.setText(listItems.get(position).getPrice());
holder.location.setText(listItems.get(position).getLocation());
holder.phone.setText(listItems.get(position).getPhone());
holder.time.setText((CharSequence) listItems.get(position).getPosted_date());
holder.progress_Bar = new ProgressBar(context);
new Thread(new Runnable() {
public void run() {
while (progressStatus < 100) {
progressStatus += 1;
handler.post(new Runnable() {
public void run() {
holder.progressBar.setProgress(progressStatus);
holder.textView.setText(progressStatus+"/"+holder.progressBar.getMax());
}
});
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
imageUrl = product.getImage();
Picasso.get().load(imageUrl).into(holder.imageView, new Callback() {
#Override
public void onSuccess() {
holder.image_layout.setVisibility(View.INVISIBLE);
}
#Override
public void onError(Exception e) {
Toast.makeText(context, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
holder.phone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id=v.getId();
if (id==R.id.phoneTv){
String phoneNumber = product.getPhone();
String message = "I am interested";
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, message, null, null);
Toast.makeText(context,"Interest message sent successfully",
Toast.LENGTH_LONG).show();
}
}
});
holder.call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id=v.getId();
if(id==R.id.call){
String phoneNumber = product.getPhone();
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+phoneNumber));
context.startActivity(intent);
}
}
}); }
#Override
public int getItemCount() {
return listItems.size();
}
#Override
public Filter getFilter() {
return filterProducts;
}
private Filter filterProducts = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
///*to delete*/String search_text = constraint.toString().toLowerCase();
List<Product> productFiltrate = new ArrayList<>();
if (constraint.length()==0 ){
productFiltrate.addAll(listItemsFull);
}else
{
String pattern = constraint.toString().toLowerCase().trim();
for (Product product:listItemsFull){
if(product.getSeller().toLowerCase().contains(pattern)){
productFiltrate.add(product);
}
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = productFiltrate;
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filterList.clear();
filterList.addAll((List) results.values);
notifyDataSetChanged();
}
};
}
INSERT DATA/MAIN_ACTIVITY
package com.dikolobe.salesagent;
public class MainActivity extends AppCompatActivity {
FirebaseRecyclerAdapter firebaseRecyclerAdapter;
ItemsAdapter itemsAdapter;
FirebaseDatabase mDatabase;
DatabaseReference mRef;
FirebaseStorage mStorage;
EditText seller_name,desc,price,location,phone;
Button btnInsert,list;
ImageButton imageButton,take_Photo;
ProgressBar progressBar;
private ProgressDialog mProgress;
Uri imageUri = null;
final int REQUEST_CODE_IMAGE=999;
static final int REQUEST_IMAGE_CAPTURE = 1;
private int progressStatus = 0;
private TextView textView;
private Handler handler = new Handler();
ViewHolder holder;
FrameLayout image_layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seller_name = findViewById(R.id.seller_nameEt);
desc = findViewById(R.id.descEt);
price = findViewById(R.id.priceEt);
location = findViewById(R.id.locationEt);
phone = findViewById(R.id.phoneEt);
btnInsert = findViewById(R.id.save);
//list = findViewById(R.id.list);
imageButton = findViewById(R.id.imageButton);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
textView = (TextView) findViewById(R.id.textView);
image_layout = (FrameLayout) findViewById(R.id.layout_image);
take_Photo = (ImageButton) findViewById(R.id.take_pic);
take_Photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id = v.getId();
if (id==R.id.take_pic){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
}
});
mDatabase = FirebaseDatabase.getInstance();
mRef = mDatabase.getReference().child("Items");
mStorage = FirebaseStorage.getInstance();
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE_IMAGE);
}
});
progressBar = new ProgressBar(MainActivity.this);
image_layout.setVisibility(View.INVISIBLE);
btnInsert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
image_layout.setVisibility(View.VISIBLE);
new Thread(new Runnable() {
public void run() {
while (progressStatus < 100) {
progressStatus += 1;
// Update the progress bar and display the
//current value in the text view
handler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressStatus);
textView.setText(progressStatus+"/"+progressBar.getMax());
}
});
try {
// Sleep for 200 milliseconds.
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
final String seller = seller_name.getText().toString().trim();
final String fn = desc.getText().toString().trim();
final String ln = price.getText().toString().trim();
final String place = location.getText().toString().trim();
final String phon = phone.getText().toString().trim();
final String id = mRef.push().getKey();
if (!(seller.isEmpty() && fn.isEmpty() && ln.isEmpty() && place.isEmpty() &&
phon.isEmpty() && imageUri!=null)){
StorageReference filepath =
mStorage.getReference().child("images").child(imageUri.getLastPathSegment());
filepath.putFile(imageUri).addOnSuccessListener(new
OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
image_layout.setVisibility(View.INVISIBLE);
Task<Uri> downloadUrl =
taskSnapshot.getStorage().getDownloadUrl().addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
String t=task.getResult().toString();
final DatabaseReference newPost=mRef.push();
newPost.child("seller").setValue(seller);
newPost.child("description").setValue(fn);
newPost.child("price").setValue(ln);
newPost.child("location").setValue(place);
newPost.child("phone").setValue(phon);
newPost.child("productId").setValue(id);
newPost.child("image").setValue(task.getResult().toString());
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String strDate = dateFormat.format(date).toString();
newPost.child("posted_date").setValue(strDate);
Toast.makeText(MainActivity.this,"successfully uploaded",
Toast.LENGTH_SHORT).show();
seller_name.setText("");
desc.setText("");
price.setText("");
location.setText("");
phone.setText("");
imageButton.setImageURI(null);
goToRetrieveDataClass();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(),"Failed to
upload..!",Toast.LENGTH_LONG).show();
}
});
}
});
}else Toast.makeText(MainActivity.this,"Please write all your
details..!",Toast.LENGTH_LONG).show();
}
});
if (!hasCamera())
take_Photo.setEnabled(false);
}
#Override
protected void onStart() {
super.onStart();
// firebaseRecyclerAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
// firebaseRecyclerAdapter.stopListening();
}
private Boolean hasCamera() {
return getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
}
public void launchCamera(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[]
grantResults) {
if (requestCode == REQUEST_CODE_IMAGE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Intent gallery = new Intent(Intent.ACTION_GET_CONTENT);
gallery.setType("image/*");
startActivityForResult(gallery, REQUEST_CODE_IMAGE);
} else {
Toast.makeText(this, "no permission", Toast.LENGTH_SHORT).show();
}
return;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_IMAGE && resultCode == RESULT_OK) {
imageUri = data.getData();
CropImage.activity(imageUri).setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1).start(this);
imageButton.setImageURI(imageUri);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK){
}
else if(resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE){
Exception error = result.getError();
}
}
super.onActivityResult(requestCode, resultCode,data);
}
}
I've created a listView, and since i'm opening one of the item, the application need to fetch all image of the application, but it's doesn't work, i can't figure it out why that's showing me this error.
Thank you for helping !
That's my model on Firebase :
imageSection.java
package com.flashpub.flash;
import java.util.List;
public class imageSection {
String imageUrl;
public imageSection(){
}
public imageSection(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getImageUrl() {
return imageUrl;
}
}
chooseSection.java
package com.flashpub.flash;
import java.util.List;
public class chooseSection {
String sectionn;
public chooseSection() {
}
public chooseSection(String sectionn) {
this.sectionn = sectionn;
}
public String getSectionn() {
return sectionn;
}
}
chooseSectionActivity.java
public class ChooseSectionActivity extends AppCompatActivity {
ListView listView;
FirebaseListAdapter<chooseSection> adapter;
chooseSection sectionChosse;
//private HashMap<Integer, String> allItemsList = new HashMap<Integer, String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_section);
listView = findViewById(R.id.listView);
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference();
myRef.keepSynced(true);
Query query = FirebaseDatabase.getInstance().getReference().child("Sections");
Log.i("salut", query.toString());
FirebaseListOptions<chooseSection> options = new FirebaseListOptions.Builder<chooseSection>()
.setLayout(R.layout.section_list)
.setQuery(query,chooseSection.class)
.build();
adapter = new FirebaseListAdapter<chooseSection>(options) {
#Override
protected void populateView(#NonNull View view, #NonNull chooseSection model, int position) {
TextView sectionView = (TextView) view.findViewById(R.id.sectionView);
sectionView.setText(model.getSectionn());
chooseSection lu = sectionChosse;
//String LatLng = lu.getLocationUserLatitude() + "," + lu.getLocationUserLongitude();
//allItemsList.put(position, model.getSectionn());
}
};
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//String item = allItemsList.get(position);
Intent intent = new Intent(ChooseSectionActivity.this, PubsSectionActivity.class);
//intent.putExtra("key", item);
startActivity(intent);
}
});
listView.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
PubsSectionActivity.java
public class PubsSectionActivity extends AppCompatActivity {
ViewFlipper viewFlipp;
private DatabaseReference databaseReference;
private List<imageSection> slideLists;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pubs_section);
viewFlipp = findViewById(R.id.viewFlipper);
databaseReference = FirebaseDatabase.getInstance().getReference();
slideLists = new ArrayList<>();
}
#Override
protected void onStart() {
super.onStart();
usingFirebaseDatabase();
}
private void usingFirebaseDatabase() {
String lolipop = "Coiffeur";
databaseReference.child("Sections/Restaurant")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
slideLists.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
imageSection model = snapshot.getValue(imageSection.class);
slideLists.add(model);
}
Toast.makeText(PubsSectionActivity.this, "All data fetched", Toast.LENGTH_SHORT).show();
usingFirebaseImages(slideLists);
} else {
Toast.makeText(PubsSectionActivity.this, "No images in firebase", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(PubsSectionActivity.this, "NO images found \n" + databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
private void usingFirebaseImages(List<imageSection> slideLists) {
for (int i = 0; i < slideLists.size(); i++) {
String downloadImageUrl = slideLists.get(i).getImageUrl();
Toast.makeText(this, downloadImageUrl, Toast.LENGTH_LONG).show();
ImageView imageView = new ImageView(this);
Picasso.get().load(downloadImageUrl).fit().centerCrop().into(imageView);
viewFlipp.addView(imageView);
viewFlipp.setInAnimation(this, android.R.anim.slide_in_left);
viewFlipp.setOutAnimation(this, android.R.anim.slide_out_right);
}
}
}
Help me please, i'm stuck !!
i don't know why there is this error...
You're attaching a listener to Sections/Restaurant. Since that is one specific restaurant, you don't need to loop over the children in onDataChange.
So:
databaseReference.child("Sections/Restaurant")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
slideLists.clear();
imageSection model = snapshot.getValue(imageSection.class);
slideLists.add(model);
Toast.makeText(PubsSectionActivity.this, "All data fetched", Toast.LENGTH_SHORT).show();
usingFirebaseImages(slideLists);
} else {
Toast.makeText(PubsSectionActivity.this, "No images in firebase", Toast.LENGTH_SHORT).show();
}
}
I am using RecyclerView to show data that is fetching from firebase Realtime Database. When I am opening recycler view activity it is showing nothing but when I go to previous activity come again then it is showing.
THIS IS THE ACTIVITY IN WHICH DATA HAS TO BE SHOWN-
public class BrakesItemActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private FloatingActionButton floatingActionButton;
private FirebaseDatabase database;
private DatabaseReference BrakestransactionDb, brakesDb;
private FirebaseRecyclerOptions<Transaction> options;
private FirebaseRecyclerAdapter<Transaction, TransactionViewHolder> adapter;
int sumofbrakescost = 0;
String sumofbrakescostvalue;
BottomAppBar bottomAppBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_last2);
bottomAppBar = findViewById(R.id.bottom_app_bar);
recyclerView = findViewById(R.id.recycler_view);
floatingActionButton = findViewById(R.id.floating_button);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
setSupportActionBar(bottomAppBar);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(BrakesItemActivity.this, BInputActivity.class);
startActivity(intent);
}
});
database = FirebaseDatabase.getInstance();
BrakestransactionDb = database.getReference().child("Brakes Items Transaction");
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(BrakesItemActivity.this));
BrakestransactionDb.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Map<String, Object> map = (Map<String, Object>) ds.getValue();
Object totalcost = map.get("totalcoststring");
int totalcostvalue = Integer.parseInt(String.valueOf(totalcost));
sumofbrakescost += totalcostvalue;
sumofbrakescostvalue = String.valueOf(sumofbrakescost);
}
brakesDb = database.getReference().child("Department").child("Brakes").child("Cost");
brakesDb.setValue(sumofbrakescostvalue);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
showTask();
}
private void showTask() {
options = new FirebaseRecyclerOptions.Builder<Transaction>().setQuery(BrakestransactionDb, Transaction.class).build();
adapter = new FirebaseRecyclerAdapter<Transaction, TransactionViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull TransactionViewHolder holder, int position, #NonNull Transaction model) {
holder.item_name_card.setText(model.getNameofitemstring());
holder.bought_by_card.setText(model.getBoughtbystring());
holder.bought_from_card.setText(model.getBoughtfromstring());
holder.date_card.setText(model.getDatestring());
holder.time_card.setText(model.getTimestring());
holder.cost_of_one_item_card.setText(model.getCostofoneitemstring());
holder.number_of_items_card.setText(model.getNumberofitemstring());
holder.total_cost_card.setText(model.getTotalcoststring());
}
#NonNull
#Override
public TransactionViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.transaction_row, parent, false);
return new TransactionViewHolder(itemView);
}
};
recyclerView.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
#Override
public boolean onContextItemSelected(#NonNull MenuItem item) {
if (item.getTitle().equals("Delete")) {
deleteTransaction(adapter.getRef(item.getOrder()).getKey());
}
return super.onContextItemSelected(item);
}
private void deleteTransaction(String key) {
BrakestransactionDb.child(key).removeValue();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.bottommenu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == R.id.delete_all) {
BrakestransactionDb.removeValue();
}
if (item.getItemId() == R.id.home_button) {
Intent intent = new Intent(this, NavActivity.class);
finish();
startActivity(intent);
if (item.getItemId() == R.id.back_item_activity) {
Intent intent1 = new Intent(this, Department.class);
finish();
startActivity(intent1);
}
}
return super.onOptionsItemSelected(item);
}
}
THIS IS THE MODEL CLASS I MADE-
package com.example.android.zfr.Model;
public class Transaction {
private String nameofitemstring,boughtbystring,boughtfromstring,costofoneitemstring,datestring,
timestring,totalcoststring,numberofitemstring;
public String getNameofitemstring() { return nameofitemstring; }
public void setNameofitemstring(String nameofitemstring) { this.nameofitemstring = nameofitemstring; }
public String getBoughtbystring() {return boughtbystring; }
public void setBoughtbystring(String bought string) {
this.boughtbystring = boughtbystring;
}
public String getBoughtfromstring() { return boughtfromstring; }
public void setBoughtfromstring(String boughtfromstring) { this.boughtfromstring = boughtfromstring; }
public String getCostofoneitemstring() {
return costofoneitemstring;
}
public void setCostofoneitemstring(String costofoneitemstring) { this.costofoneitemstring = costofoneitemstring; }
public String getDatestring() { return datestring; }
public void setDatestring(String datestring) { this.datestring = datestring; }
public String getTimestring() { return timestring; }
public void setTimestring(String timestring) { this.timestring = timestring; }
public String getTotalcoststring() { return totalcoststring; }
public void setTotalcoststring(String totalcoststring) { this.totalcoststring = totalcoststring; }
public String getNumberofitemstring() { return numberofitemstring; }
public void setNumberofitemstring(String numberofitemstring) { this.numberofitemstring = numberofitemstring; }
public Transaction() { }
public Transaction(String nameofitemstring,String boughtbystring,String boughtfromstring,String costofoneitemstring, String timestring,
String datestring ,String totalcoststring , String numberofitemstring ){
this.nameofitemstring=nameofitemstring;
this.boughtbystring=boughtbystring;
this.boughtfromstring=boughtfromstring;
this.costofoneitemstring=costofoneitemstring;
this.datestring=datestring;
this.timestring=timestring;
this.numberofitemstring=numberofitemstring;
this.totalcoststring=totalcoststring;
}
}
THIS THE VIEWHOLDER CLASS-
package com.example.android.zfr.ViewHolder;
import android.view.ContextMenu;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.android.zfr.R;
import com.facebook.shimmer.ShimmerFrameLayout;
public class TransactionViewHolder extends RecyclerView.ViewHolder implements
View.OnCreateContextMenuListener{
public TextView item_name_card,bought_by_card,bought_from_card,date_card,
time_card,cost_of_one_item_card,number_of_items_card,total_cost_card;
public TransactionViewHolder(#NonNull View itemView) {
super(itemView);
item_name_card=itemView.findViewById(R.id.item_name_card);
bought_by_card=itemView.findViewById(R.id.bought_by_card);
bought_from_card=itemView.findViewById(R.id.bought_from_card);
date_card=itemView.findViewById(R.id.date_card);
time_card=itemView.findViewById(R.id.time_card);
cost_of_one_item_card=itemView.findViewById(R.id.cost_of_one_item_card);
number_of_items_card=itemView.findViewById(R.id.number_of_items_card);
total_cost_card=itemView.findViewById(R.id.total_cost_card);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{ menu.add(0,0,getAdapterPosition(),"Delete"); }
}
Please help.
you need to realize that Firebase is Asynchronous, meaning that your showTask() gets called even before your database is able to send you the data. To avoid this issue, you need to put your showTask() inside your addValueEventListener. Try this:
BrakestransactionDb.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Map<String, Object> map = (Map<String, Object>) ds.getValue();
Object totalcost = map.get("totalcoststring");
int totalcostvalue = Integer.parseInt(String.valueOf(totalcost));
sumofbrakescost += totalcostvalue;
sumofbrakescostvalue = String.valueOf(sumofbrakescost);
}
brakesDb = database.getReference().child("Department").child("Brakes").child("Cost");
brakesDb.setValue(sumofbrakescostvalue);
showTask();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
It worked by putting
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(BrakesItemActivity.this));
in onDatachange method like this:
BrakestransactionDb.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Map<String, Object> map = (Map<String, Object>) ds.getValue();
Object totalcost = map.get("totalcoststring");
int totalcostvalue = Integer.parseInt(String.valueOf(totalcost));
sumofbrakescost += totalcostvalue;
sumofbrakescostvalue = String.valueOf(sumofbrakescost);
}
brakesDb = database.getReference().child("Department").child("Brakes").child("Cost");
brakesDb.setValue(sumofbrakescostvalue);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(BrakesItemActivity.this));
}
I can get key and show in Log.d but it don't show in RecyclerView. What's wrong with it?
HistoryActivity.java it contains my recyclerView:
public class HistoryActivity extends AppCompatActivity {
FirebaseFirestore mFirestore;
FirebaseAuth firebaseAuth;
FirebaseDatabase database;
RecyclerView mHisList;
ArrayList<PreviousLst> history;
adt_rv_HisList adtRvHisList;
TextView ptName;
TextView ptPort;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
getSupportActionBar().setSubtitle("History");
Intent it = getIntent();
String patName = it.getStringExtra("nm");
String patID = it.getStringExtra("idpat");
String portNum = it.getStringExtra("pNum");
String regisDate = it.getStringExtra("rdate");
ptName = findViewById(R.id.txName);
ptPort = findViewById(R.id.portpassValue);
ptName.setText(patName);
ptPort.setText(portNum);
history = new ArrayList<>();
setupRecyclerView();
setupFireBase();
loadDataFromDatabase(portNum);
}
private void setupFireBase() {
mFirestore = FirebaseFirestore.getInstance();
firebaseAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
}
private void setupRecyclerView() {
mHisList = findViewById(R.id.rv_prev_lst);
mHisList.setHasFixedSize(true);
mHisList.setLayoutManager(new LinearLayoutManager(this));
mHisList.setAdapter(adtRvHisList);
}
public void loadDataFromDatabase(String portNum) {
if(history.size()>0)
history.clear();
DatabaseReference myRef;
DatabaseReference passref;
switch (portNum){
case "Huang-Yai0002":
String p2 = "NETEKG-Huang-Yai0002";
myRef = database.getReference("MACHINE");
passref = myRef.child(p2).child("value");
passref.addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
String keydate = postSnapshot.getKey();
Log.d(TAG, "Child are: " + keydate );
PreviousLst previousLst = new PreviousLst(keydate);
history.add(previousLst);
}
adtRvHisList = new adt_rv_HisList(HistoryActivity.this, history);
mHisList.setAdapter(adtRvHisList);
}
#Override
public void onCancelled(DatabaseError error) {
Log.w(TAG, "Failed to read value.", error.toException());
}
});
break;
case "Huang-Yai0003":
String p3 = "NETEKG-Huang-Yai0003";
myRef = database.getReference("MACHINE");
passref = myRef.child(p3).child("value");
passref.addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
String keydate = postSnapshot.getKey();
Log.d(TAG, "Child are: " + keydate );
PreviousLst previousLst = new PreviousLst(postSnapshot.getKey());
history.add(previousLst);
}
adtRvHisList = new adt_rv_HisList(HistoryActivity.this, history);
mHisList.setAdapter(adtRvHisList);
}
#Override
public void onCancelled(DatabaseError error) {
Log.w(TAG, "Failed to read value.", error.toException());
}
});
break;
default:
Log.d(TAG, "Value is: " + portNum);
Toast.makeText(getApplicationContext(),"Error...",Toast.LENGTH_LONG).show();
break;
}
}
}
adt_rv_HisList.java Adapter:
public class adt_rv_HisList extends RecyclerView.Adapter<adtrvHisListViewHolder> {
HistoryActivity historyActivity;
ArrayList<PreviousLst> history;
public adt_rv_HisList(HistoryActivity historyActivity, ArrayList<PreviousLst> history) {
this.history = history;
this.historyActivity = historyActivity;
}
#NonNull
#Override
public adtrvHisListViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(historyActivity.getBaseContext()).inflate(R.layout.hislist_item, viewGroup, false);
return new adtrvHisListViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull adtrvHisListViewHolder holder, int position) {
holder.hdate.setText(history.get(position).getHisDate());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialogView();
}
});
}
private void dialogView() {
final Dialog dia = new Dialog(historyActivity);
dia.setContentView(R.layout.dialog_ask_view);
dia.show();
Button pvgraph = (Button)dia.findViewById(R.id.bt_pvgraph);
Button pvhr = (Button)dia.findViewById(R.id.bt_pvhrate);
Button cc = (Button)dia.findViewById(R.id.btn_cancel);
cc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dia.dismiss();
}
});
pvgraph.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dia.dismiss();
Intent it = new Intent(historyActivity, ViewgraphActivity.class);
historyActivity.startActivity(it);
}
});
pvhr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dia.dismiss();
Intent it = new Intent(historyActivity, ViewHRActivity.class);
historyActivity.startActivity(it);
}
});
}
#Override
public int getItemCount() {
return 0;
}
}
adtrvHisListViewHolder.java Contains the ViewHolder :
public class adtrvHisListViewHolder extends RecyclerView.ViewHolder {
public TextView hdate;
public adtrvHisListViewHolder(View itemView) {
super(itemView);
hdate = itemView.findViewById(R.id.his_date);
}
}
PreviousLst.java is Model class for my recyclerView:
public class PreviousLst {
String HisDate;
public PreviousLst(String HisDate){
this.HisDate = HisDate;
}
public PreviousLst(){
}
public String getHisDate() {
return HisDate;
}
public void setHisDate(String hisDate) {
HisDate = hisDate;
}
}
This is my key that I get and show in Log.d
D/ContentValues: Child are: HEART RATE
D/ContentValues: Child are:LEAD 1
Child are: LEAD 2
Child are: LEAD 3
Child are: LEAD 4
Child are: LEAD 5
Child are: LEAD 6
but it don't shoe in App.
enter image description here
#Override
public int getItemCount() {
//return 0;
replace it with history.size();
}
the added lines tells the adapter how many items, the adapter has to bind the items to the recycler view. By default it is 0, means the adapter class will never call the binView method to show the items at view side
Problem:
I have a screen where it shows the schedules of a certain user.
But at the same time I need to check if any of the schedules is already occupied, and color your background a darker color.
Print 1: RecyclerView screen with schedules.
Print 2: It is the same screen, but after checking the available schedules.
Note: If we are on the Wi-Fi network, charging is fast, but if it is a mobile internet network, it is very slow.
I need some way, to add a ProgressDialog inside my Adapter, exactly in the moment where the check of the schedules is done.
On here:
/*Checar Horario disponivel*/
final FirebaseFirestore mDB = FirebaseFirestore.getInstance();
CollectionReference mDBHorarios = mDB.collection("Empresas").document(empresa).collection("Agendamentos");
mDBHorarios.whereEqualTo("profissional_id", ref.getId_Prof()).whereEqualTo("agenda_hora", ref.getHora())
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
Agendamentos doc = document.toObject(Agendamentos.class);
String horaAgenda = doc.getAgenda_hora();
/*Cor do fundo*/
if ( horaAgenda.equals(ref.getHora()) ){
fundoHora.setBackgroundColor(Color.parseColor("#E0E0E0"));
statusHoraAgenda = true;
}
}
} else {
}
}
});
Note: It may be that this is not a great way. I accept suggests if there is a better way to do this query in a RecyclerView.
Code Full - Adapter:
public class HorariosProfissionalAdapter extends FirestoreAdapter<HorariosProfissionalAdapter.ViewHolder>{
public interface OnHorariosProfissionaisListner {
void onHorarioProfissionaisSelected(DocumentSnapshot horariosProfissional);
}
private OnHorariosProfissionaisListner mListner;
public HorariosProfissionalAdapter(Query query, OnHorariosProfissionaisListner listner){
super(query);
mListner = listner;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
return new ViewHolder(inflater.inflate(R.layout.card_horarios_profissional, parent, false));
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.bind(getSnapshot(position), mListner);
}
static class ViewHolder extends RecyclerView.ViewHolder {
private Boolean statusHoraAgenda = false;
#BindView(R.id.tvHoraProf)
TextView hora;
#BindView(R.id.fundoHorario)
LinearLayout fundoHora;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
public void bind(final DocumentSnapshot snapshot,
final OnHorariosProfissionaisListner listener) {
final HorariosProfissionais ref = snapshot.toObject(HorariosProfissionais.class);
String empresa = ref.getId_Emp();
/*Checar Horario disponivel*/
final FirebaseFirestore mDB = FirebaseFirestore.getInstance();
CollectionReference mDBHorarios = mDB.collection("Empresas").document(empresa).collection("Agendamentos");
mDBHorarios.whereEqualTo("profissional_id", ref.getId_Prof()).whereEqualTo("agenda_hora", ref.getHora())
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
Agendamentos doc = document.toObject(Agendamentos.class);
String horaAgenda = doc.getAgenda_hora();
/*Cor do fundo*/
if ( horaAgenda.equals(ref.getHora()) ){
fundoHora.setBackgroundColor(Color.parseColor("#E0E0E0"));
statusHoraAgenda = true;
}
}
} else {
}
}
});
hora.setText(ref.getHora());
// Click listener
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null && !statusHoraAgenda) {
listener.onHorarioProfissionaisSelected(snapshot);
}
}
});
}
}
}
Code Full - Activity:
public class Agenda_profissionais extends AppCompatActivity implements HorariosProfissionalAdapter.OnHorariosProfissionaisListner {
private String mId_Empresa = null;
private String mId_Profissional = null;
private String mNome_Profissional = null;
private RecyclerView mCardHorarios;
private HorariosProfissionalAdapter mAdapter;
private FirebaseFirestore mFirestore;
private Query mQuery;
private ProgressDialog mProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_agenda_profissionais);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Horario");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
/* CONFIGURAÇÃO TOOLBAR*/
Bundle extra = getIntent().getExtras();
if ( extra != null ){
mId_Empresa = extra.getString("id_empresa");
mId_Profissional = extra.getString("id_profissional");
mNome_Profissional = extra.getString("nome_profissional");
}
/*Firebase*/
mFirestore = FirebaseFirestore.getInstance();
mQuery = mFirestore.collection("Empresas").document(mId_Empresa).collection("Profissionais").document(mId_Profissional).collection("Horarios");
mCardHorarios = (RecyclerView) findViewById(R.id.cardListaHorariosProf);
mAdapter = new HorariosProfissionalAdapter(mQuery, this){
#Override
protected void onDataChanged() {
if (getItemCount() == 0) {
mCardHorarios.setVisibility(View.GONE);
//mTxtVazio.setVisibility(View.VISIBLE);
} else {
mCardHorarios.setVisibility(View.VISIBLE);
}
}
};
mCardHorarios.setLayoutManager(new LinearLayoutManager(this));
mCardHorarios.setAdapter(mAdapter);
}
#Override
public void onStart() {
super.onStart();
// Start listening for Firestore updates
if (mAdapter != null) {
mAdapter.startListening();
}
}
#Override
public void onStop() {
super.onStop();
if (mAdapter != null) {
mAdapter.stopListening();
}
}
#Override
public void onHorarioProfissionaisSelected(DocumentSnapshot horario) {
HorariosProfissionais idHorario = horario.toObject(HorariosProfissionais.class);
Toast.makeText(Agenda_profissionais.this, "Horario selecionado: " +idHorario.getHora(), Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_agendamento, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
finish();
}
}
Solution
public void bind(final DocumentSnapshot snapshot,
final OnHorariosProfissionaisListner listener) {
final HorariosProfissionais ref = snapshot.toObject(HorariosProfissionais.class);
String empresa = ref.getId_Emp();
mProgress = new ProgressDialog(itemView.getContext());
mProgress.setMessage("testando....");
mProgress.show();
/*Checar Horario disponivel*/
final FirebaseFirestore mDB = FirebaseFirestore.getInstance();
CollectionReference mDBHorarios = mDB.collection("Empresas").document(empresa).collection("Agendamentos");
mDBHorarios.whereEqualTo("profissional_id", ref.getId_Prof()).whereEqualTo("agenda_hora", ref.getHora())
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
Agendamentos doc = document.toObject(Agendamentos.class);
String horaAgenda = doc.getAgenda_hora();
/*Cor do fundo*/
if ( horaAgenda.equals(ref.getHora()) ){
fundoHora.setBackgroundColor(Color.parseColor("#E0E0E0"));
statusHoraAgenda = true;
}
}
mProgress.dismiss();
} else {
}
}
});