How to swipe to delete on RecyclerView? - android

What I have here a History page that displays the requests the user have accepted or posted. I was able to successfully put a button for the user to delete all of the history the user has. Now I want the user to be able to delete a history one at a time by swiping it.
HistoryFragment.java
RecyclerView rView;
Button clear;
DatabaseReference dRef;
LinearLayoutManager llm;
String id;
View myView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.history, container, false);
FirebaseUser fu = FirebaseAuth.getInstance().getCurrentUser();
id = fu.getUid();
dRef = FirebaseDatabase.getInstance().getReference().child("History"+id);
clear = (Button) myView.findViewById(R.id.clear);
rView = (RecyclerView) myView.findViewById(R.id.history_list);
rView.setHasFixedSize(true);
llm = new LinearLayoutManager(getActivity());
llm.setReverseLayout(true);
llm.setStackFromEnd(true);
rView.setLayoutManager(llm);
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dRef.removeValue();
}
});
return myView;
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<HistoryData, HistoryFragment.RequestViewHolder> fra = new FirebaseRecyclerAdapter<HistoryData, HistoryFragment.RequestViewHolder>(
HistoryData.class,
R.layout.historylistview,
HistoryFragment.RequestViewHolder.class,
dRef
) {
#Override
protected void populateViewHolder(final HistoryFragment.RequestViewHolder viewHolder, HistoryData model, final int position) {
viewHolder.setTrans(model.getTrans());
viewHolder.setRequestDeadline(model.getRequestDeadline());
viewHolder.setRequestDescription(model.getRequestDescription());
viewHolder.setDateTimeAccepted(model.getDateTimeAccepted());
viewHolder.setRequestLocation(model.getRequestLocation());
viewHolder.setProfile(getApplicationContext() ,model.getProfile());
}
};
rView.setAdapter(fra);
}
public static class RequestViewHolder extends RecyclerView.ViewHolder{
View myView;
public RequestViewHolder(View itemView) {
super(itemView);
myView = itemView;
}
public void setTrans(String profile){
TextView trans = (TextView) myView.findViewById(R.id.transaction);
trans.setText(profile);
}
public void setRequestDeadline(String dead){
TextView rdead = (TextView) myView.findViewById(R.id.rDead);
rdead.setText(dead);
}
public void setRequestDescription(String desc){
TextView rdesc = (TextView) myView.findViewById(R.id.rDesc);
rdesc.setText(desc);
}
public void setDateTimeAccepted(String date){
TextView dta = (TextView) myView.findViewById(R.id.rAccept);
dta.setText(date);
}
public void setRequestLocation(String loc){
TextView rloc = (TextView) myView.findViewById(R.id.rLoc);
rloc.setText(loc);
}
public void setProfile(Context c, String profile){
ImageView rprofile = (ImageView) myView.findViewById(R.id.HPicture);
Picasso.with(c).load(profile).into(rprofile);
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
I haven't really tried anything because the other questions I've seen here so far doesn't seem to be similar to my codes.

You will have to use an existing library / widget unless you want to create the functionality from scratch.
For instance:
https://android-arsenal.com/details/1/4897
You have full instructions there but basically:
mRecyclerView = new CdsRecyclerView(this);
mRecyclerView = (CdsRecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
// Adapter:
mRecyclerViewAdapter = new RecyclerViewAdapter(this, getData());
mRecyclerView.setAdapter(mRecyclerViewAdapter);
// Enable swipe:
mRecyclerView.enableItemSwipe();
// Listener:
mRecyclerView.setItemSwipeCompleteListener(new CdsItemTouchCallback.ItemSwipeCompleteListener() {
#Override
public void onItemSwipeComplete(int position) {
Toast.makeText(MainActivity.this, "Item was swiped:" + position,
Toast.LENGTH_SHORT).show();
}
});

Related

android recyclerview scroll making mess in chat using firebase

I'm simply implementing a RecyclerView for showing chat between two. Everything is working fine but there is one problem when I am scrolling up and again scrolling down the direction of sender message goes left(GRAVITY) which I have set only for the received ones. Please look the code below hope u will understand.
Screenshot before scrolling.
Screenshot after scrolling.
Here's my RecycleActivity.java
public class RecycleActivity extends AppCompatActivity {
RecyclerView recyclerView;
DatabaseReference databaseReference,temp;
EditText editText;
Button btnSend;
public static String nameOFUser = "";
LinearLayoutManager linearLayoutManager;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainer);
sharedPreferences = getSharedPreferences("MyLoginPref",MODE_PRIVATE);
nameOFUser = sharedPreferences.getString("name","");
Log.e("name",nameOFUser);
recyclerView = (RecyclerView) findViewById(R.id.recyclerid);
recyclerView.setHasFixedSize(true);
linearLayoutManager= new LinearLayoutManager(this);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
databaseReference = FirebaseDatabase.getInstance().getReference().child("msg");
editText = (EditText) findViewById(R.id.edittextmessagetosend);
btnSend = (Button) findViewById(R.id.button41);
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
temp=databaseReference.push();
temp.child("name").setValue(nameOFUser);
temp.child("message").setValue(editText.getText().toString().trim());
editText.setText("");
recyclerView.setLayoutManager(linearLayoutManager);
}
});
}
#Override
protected void onStart() {
super.onStart();
final FirebaseRecyclerAdapter<MessageBlog,MessageHolder> firebaseRecyclerAdapter
= new FirebaseRecyclerAdapter<MessageBlog, MessageHolder>(
MessageBlog.class,R.layout.message_row,MessageHolder.class,databaseReference
) {
#Override
protected void populateViewHolder(MessageHolder viewHolder, MessageBlog model, int position) {
String name = model.getName();
viewHolder.setSender(name);
viewHolder.SetMessage(model.getMessage());
viewHolder.setDirection(name);
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
recyclerView.smoothScrollToPosition(firebaseRecyclerAdapter.getItemCount());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
The ViewHolder.java
public static class MessageHolder extends RecyclerView.ViewHolder{
View view;
LinearLayout lay,linearLayoutback;
CardView cardViewreal;
DatabaseReference mdatabase;
public MessageHolder(View itemView) {
super(itemView);
view = itemView;
linearLayoutback = (LinearLayout)
itemView.findViewById(R.id.linearlayoutback);
mdatabase=FirebaseDatabase.getInstance().getReference().child("msg");
lay = (LinearLayout) itemView.findViewById(R.id.idcardview);
cardViewreal = (CardView) itemView.findViewById(R.id.idrealcard);
}
void setDirection(final String name){
if(!name.equalsIgnoreCase(nameOFUser)) {
lay.setGravity(Gravity.LEFT);
cardViewreal.setCardBackgroundColor(Color.parseColor("#ffffff"));
} else {
lay.setGravity(Gravity.LEFT);
cardViewreal.setCardBackgroundColor(Color.parseColor("#f5f4f5"));
}
}
void setSender(String sender){
TextView tvsender = (TextView) view.findViewById(R.id.senderidtv);
tvsender.setText(sender);
}
void SetMessage(String message){
TextView tvmessage = (TextView) view.findViewById(R.id.messageidtv);
tvmessage.setText(message);
}
}
Check your set direction method. It always sets direction to the left
void setDirection(final String name){
if(!name.equalsIgnoreCase(nameOFUser)) {
lay.setGravity(Gravity.LEFT);
cardViewreal.setCardBackgroundColor(Color.parseColor("#ffffff"));
//linearLayoutback.setBackgroundResource(R.drawable.white);
}
else{
lay.setGravity(Gravity.LEFT);
cardViewreal.setCardBackgroundColor(Color.parseColor("#f5f4f5"));
// linearLayoutback.setBackgroundResource(R.drawable.white);
}

Passing values from recyclerview cardview to deatilactivity onitemclick

I'm new to android development, I have been trying to pass values from recyclerview cardview to detailActivity, after searching for couple of hours I came up with this code, before implementing this code I was able to view all the cardview on MainActivity, Now when I implemented this code app is crashing when I start the app, event log.
This is my Fragment which contain Firebaserecycler Adapter and viewholder class:
public class MakingFragment extends Fragment {
private FloatingActionButton fab;
ScaleAnimation shrinkAnim;
private RecyclerView mRecyclerView;
private LinearLayoutManager mLayoutManager;
private TextView tvNoMovies;
Context c;
ArrayList<Food> spacecrafts;
//Getting reference to Firebase Database
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mDatabaseReference = database.getReference();
private static final String userId = "53";
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.making,container,false);
//Initializing our Recyclerview
mRecyclerView = (RecyclerView) v.findViewById(R.id.my_recycler_view);
tvNoMovies = (TextView) v.findViewById(R.id.tv_no_movies);
//scale animation to shrink floating actionbar
shrinkAnim = new ScaleAnimation(1.15f, 0f, 1.15f, 0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
if (mRecyclerView != null) {
//to enable optimization of recyclerview
mRecyclerView.setHasFixedSize(true);
}
//using staggered grid pattern in recyclerview
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
mLayoutManager.setReverseLayout(true); // to reverse the items updating on recycleview
mLayoutManager.setStackFromEnd(true); // to scroll from top when layout is reversed
//Say Hello to our new FirebaseUI android Element, i.e., FirebaseRecyclerAdapter
FirebaseRecyclerAdapter<Food,FoodViewHolder> adapter = new FirebaseRecyclerAdapter<Food, FoodViewHolder>(
Food.class,
R.layout.food_item,
FoodViewHolder.class,
//referencing the node where we want the database to store the data from our Object
mDatabaseReference.child("users").child(userId).child("food").getRef()
) {
#Override
protected void populateViewHolder(FoodViewHolder viewHolder, final Food model, int position) {
if(tvNoMovies.getVisibility()== View.VISIBLE){
tvNoMovies.setVisibility(View.GONE);
}
viewHolder.tvFoodName.setText(model.getFoodName());
viewHolder.ratingBar.setRating(model.getFoodRating());
viewHolder.tvFoodCategory.setText(model.getFoodCategory());
viewHolder.tvFoodAvailableUpto.setText(model.getFoodAvailableUpto());
viewHolder.tvFoodPrice.setText(model.getFoodPrice());
Picasso.with(getActivity().getApplicationContext()).load(model.getFoodPoster()).into(viewHolder.ivFoodPoster);
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(int pos) {
//OPEN DETAI ACTIVITY
openDetailActivity(model.getFoodName(),model.getFoodCategory(),model.getFoodAvailableUpto(),model.getFoodPrice());
}
});
}
#Override
public int getItemCount() {
return spacecrafts.size();
}
//OPEN DETAIL ACTIVITY
private void openDetailActivity(String...details)
{
Intent i=new Intent(c,DetailActivity.class);
i.putExtra("TITLE_KEY",details[0]);
i.putExtra("CAT_KEY",details[1]);
i.putExtra("AVAIL_KEY",details[2]);
i.putExtra("PRI_KEY",details[3]);
c.startActivity(i);
}
};
mRecyclerView.setAdapter(adapter);
fab = (FloatingActionButton) v.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent launchactivity=new Intent(getActivity().getApplicationContext(),AddFoodDetailsActivity.class);
startActivity(launchactivity);
//animation being used to make floating actionbar disappear
shrinkAnim.setDuration(400);
fab.setAnimation(shrinkAnim);
shrinkAnim.start();
shrinkAnim.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
//changing floating actionbar visibility to gone on animation end
fab.setVisibility(View.GONE);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
}
});
return v;
}
public void onBackPressed() {
getActivity().onBackPressed();
if (fab.getVisibility() == View.GONE)
fab.setVisibility(View.VISIBLE);
}
//ViewHolder for our Firebase UI
public static class FoodViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView tvFoodName;
RatingBar ratingBar;
ImageView ivFoodPoster;
TextView tvFoodCategory;
TextView tvFoodAvailableUpto;
TextView tvFoodPrice;
ImageView ivNextArrow;
ItemClickListener itemClickListener;
public FoodViewHolder(View v) {
super(v);
tvFoodName = (TextView) v.findViewById(R.id.tvName);
ratingBar = (RatingBar) v.findViewById(R.id.rating_bar);
ivFoodPoster = (ImageView) v.findViewById(R.id.imgThumb);
tvFoodCategory = (TextView) v.findViewById(R.id.tvCategory);
tvFoodAvailableUpto= (TextView) v.findViewById(R.id.tvavailable);
tvFoodPrice = (TextView) v.findViewById(R.id.tvprice);
ivNextArrow = (ImageView) v.findViewById(R.id.NextArrow);
v.setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener itemClickListener)
{
this.itemClickListener=itemClickListener;
}
#Override
public void onClick(View view) {
this.itemClickListener.onItemClick(this.getLayoutPosition());
}
}
}
This is my DetailActivity
public class DetailActivity extends AppCompatActivity {
TextView nameTxt,catTxt,availTxt,priceTxt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
nameTxt = (TextView) findViewById(R.id.titleTxt);
catTxt= (TextView) findViewById(R.id.catTxt);
availTxt = (TextView) findViewById(R.id.availTxt);
priceTxt = (TextView) findViewById(R.id.pricesTxt);
//GET INTENT
Intent i=this.getIntent();
//RECEIVE DATA
String title=i.getExtras().getString("TITLE_KEY");
String cat=i.getExtras().getString("CAT_KEY");
String avail=i.getExtras().getString("AVAIL_KEY");
String price=i.getExtras().getString("PRI_KEY");
//BIND DATA
nameTxt.setText(title);
catTxt.setText(cat);
availTxt.setText(avail);
priceTxt.setText(price);
}
}
Please help me out, thank you.
Initialize the arraylist in oncreate()
spacecrafts= new ArrayList<>();
also these in oncreate()
database = FirebaseDatabase.getInstance();
mDatabaseReference = database.getReference();
and check spacecrafts is null or not

Removing recyclerview items from the Adapter

I have two tabs (fragments), NewOrders and FinishedOrders, I'm populating the orders via Volley requests, now each item inside the New Orders tab has a SwipeLayout which show a clickable textview that makes the order finished, and move it to the other tab (backend stuff..), and I got this working perfectly,
The problem is when I click to finish, the recyclerview isn't updated once the request sent successfully, I have to do pull-to-refresh so it would update..! it seems easy to solve, but the issue is handling the swipelayout listener done inside onBindView method inside the adapter..!! that's only place to access it according to the library I'm using (I guess)..! on the other hand refreshing and populating the list happens in the NewOrder tab fragment..!
So how can I make the item to be removed from the list after the click and becomes updated..?!
Any thoughts..!?
My Adapter Class + ViewHolder
Note: the implemented methods in the adapter are required because of the interface of SwipeLayout library
public class OrdersDataAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
implements SwipeAdapterInterface, SwipeItemMangerInterface {
protected SwipeItemRecyclerMangerImpl mItemManger = new SwipeItemRecyclerMangerImpl(this);
public Context context;
ArrayList<OrderPresenter> orders;
public OrdersDataAdapter(ArrayList<OrderPresenter> orders, Context context) {
this.orders = orders;
this.context = context;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.order_card, parent, false);
return new NewOrderVH(v);
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
final OrderPresenter order = this.orders.get(position);
final NewOrderVH vh1 = (NewOrderVH) holder;
vh1.setData(orders.get(position));
mItemManger.bindView(vh1.itemView, position);
vh1.swipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);
vh1.swipeLayout.addDrag(SwipeLayout.DragEdge.Left,
vh1.swipeLayout.findViewById(R.id.bottom_wrapper));
if (order.isFinished()) {
vh1.swipeLayout.setSwipeEnabled(false);
vh1.setBadge("DONE");
vh1.setBadgeColor(order.getBadgeColor());
} else {
vh1.finish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// get the clicked item position?
final int position = vh1.getAdapterPosition();
// these responsible for the request which make the order finished
OrderPresenter order = orders.get(position);
OrderRepository.setOrderFinURL(order.getID());
OrderRepository.FinishOrder(order.getID(), context);
/*the commented three lines below didn't help with the problem*/
// notifyItemChanged(position);
// notifyItemRemoved(position);
// notifyDataSetChanged();*/
order.setStatus(order.getStatusText(Order.FINISHED));
}
});
}
}
#Override
public int getItemCount() {
return orders.size();
}
public class NewOrderVH extends RecyclerView.ViewHolder {
SwipeLayout swipeLayout;
private TextView finish;
private CardView orderCard;
TextView Badge;
private ImageView cusPic;
private TextView cusName;
private TextView CusAdress;
private TextView vendorsNum;
private TextView itemsNum;
private TextView time;
private TextView emptyView;
public NewOrderVH(View itemView) {
super(itemView);
Badge = (TextView) itemView.findViewById(R.id.badge);
swipeLayout = (SwipeLayout) itemView.findViewById(R.id.swipe);
finish = (TextView) itemView.findViewById(R.id.finish);
orderCard = (CardView) itemView.findViewById(R.id.OrderCard);
cusPic = (ImageView) itemView.findViewById(R.id.cusPic);
cusName = (TextView) itemView.findViewById(R.id.cusName);
CusAdress = (TextView) itemView.findViewById(R.id.CusAdress);
vendorsNum = (TextView) itemView.findViewById(R.id.vendorsNum);
itemsNum = (TextView) itemView.findViewById(R.id.itemsNum);
time = (TextView) itemView.findViewById(R.id.time);
emptyView = (TextView) itemView.findViewById(R.id.empty_view);
orderCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), OrderDetails.class);
v.getContext().startActivity(intent);
}
});
}
public void setData(final OrderPresenter data) {
time.setText(data.getOrderTime());
cusName.setText(data.getFullName());
vendorsNum.setText(data.getVendorsCount());
itemsNum.setText(data.getItemsCount());
CusAdress.setText(data.getFullAddress());
Picasso.with(context).load(data.getCustomerPicture()).into(cusPic);
}
public void setBadgeColor(int drawable) {
this.Badge.setBackgroundResource(drawable);
}
public void setBadge(String badge) {
this.Badge.setText(badge);
}
}
#Override
public int getSwipeLayoutResourceId(int position) {
return R.id.swipe;
}
#Override
public void openItem(int position) {
}
#Override
public void closeItem(int position) {
}
#Override
public void closeAllExcept(SwipeLayout layout) {
}
#Override
public void closeAllItems() {
}
#Override
public List<Integer> getOpenItems() {
return null;
}
#Override
public List<SwipeLayout> getOpenLayouts() {
return null;
}
#Override
public void removeShownLayouts(SwipeLayout layout) {
}
#Override
public boolean isOpen(int position) {
return false;
}
#Override
public Attributes.Mode getMode() {
return null;
}
#Override
public void setMode(Attributes.Mode mode) {
}
}
My NewOrder Fragment
Note: the FinishedOrders tab (fragment) does the same thing as new order but filters the current the Finished status.
public class NewOrdersTab extends Fragment {
RecyclerView recyclerView;
OrdersDataAdapter adapter;
private SwipeRefreshLayout swiperefresh;
private TextView emptyView;
ArrayList<OrderPresenter> modelData;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.new_orders_tab_frag, container, false);
modelData = new ArrayList<>();
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
swiperefresh = (SwipeRefreshLayout) rootView.findViewById(R.id.swiperefresh);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
swiperefresh.setColorSchemeResources(R.color.colorPrimary, R.color.color_error, R.color.colorInfo);
adapter = new OrdersDataAdapter(modelData, getActivity());
emptyView = (TextView) rootView.findViewById(R.id.empty_view);
recyclerView.setAdapter(adapter);
adapter.setMode(Attributes.Mode.Single);
OrderRepository.fetchOrders("awaiting-shipment", getActivity(), new DataFetch() {
#Override
public void onResponse(ArrayList<OrderPresenter> data) {
swiperefresh.setRefreshing(true);
if (data.size() != 0) {
swiperefresh.setRefreshing(true);
emptyView.setVisibility(View.GONE);
modelData.clear();
modelData.addAll(data);
adapter.notifyDataSetChanged();
} else {
emptyView.setVisibility(View.VISIBLE);
emptyView.setText(getString(R.string.No_New_Orders));
}
swiperefresh.setRefreshing(false);
}
});
return rootView;
}
}
I figured it out, I just added these two lines after I make the request..!
orders.remove(position);
notifyItemRemoved(position);
//notifyDataSetChanged(position);

Data retrieval parse.com

I am developing an android app. for that I have created table product
with columns title, Image1,Image2 , etc
I want to display it in a recycler view or card view. including images. how can i do that...?
public class Productfragment extends Fragment {
private static BUser user = (BUser) ParseUser.getCurrentUser();
private enter code here
static BStore store = user.getCurrentStore();
List<BProduct> pets = new ArrayList<BProduct>();
public String [] ii;
public Productfragment(){
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
RecyclerView recyclerView = (RecyclerView) inflater.inflate(
R.layout.recycler_view, container, false);
ContentAdapter adapter = new ContentAdapter(recyclerView.getContext());
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return recyclerView;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.search_menu, menu);
//super.onCreateOptionsMenu(menu, inflater);
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public SimpleDraweeView picture;
public TextView name;
public TextView description;
public ViewHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.productfragment, parent, false));
picture = (SimpleDraweeView) itemView.findViewById(R.id.card_image);
name = (TextView) itemView.findViewById(R.id.card_title);
// Adding Snackbar to Action Button inside card
Button button = (Button)itemView.findViewById(R.id.action_button);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Snackbar.make(v, "Action is pressed",
Snackbar.LENGTH_LONG).show();
}
});
ImageButton favoriteImageButton =
(ImageButton) itemView.findViewById(R.id.favorite_button);
favoriteImageButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Snackbar.make(v, "Added to Favorite",
Snackbar.LENGTH_LONG).show();
}
});
ImageButton shareImageButton = (ImageButton) itemView.findViewById(R.id.share_button);
shareImageButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Snackbar.make(v, "Share article",
Snackbar.LENGTH_LONG).show();
}
});
}
}
/**
* Adapter to display recycler view.
*/
public class ContentAdapter extends RecyclerView.Adapter<ViewHolder> {
// Set numbers of Card in RecyclerView.
private static final int LENGTH = 4;
String [] mylist ;
public ContentAdapter(Context context) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Product");
// query.whereEqualTo("storeI", store.getObjectId());
query.findInBackground(new FindCallback<ParseObject>() {
// ArrayList<ParseFile>myImage = new ArrayList<ParseFile>();
public void done(List<ParseObject> scoreList, ParseException e) {
if (e == null) {
for (int i=0; i<scoreList.size(); ++i) {
mylist[i] = scoreList.get(i).getString("description");
// mylist.add(name);
}
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()), parent);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
//holder.picture.setImageURI(mPlacePictures[position % mPlacePictures.length]);
holder.name.setText(mylist[position]);
}
#Override
public int getItemCount() {
return LENGTH;
}
}
}

Data from backend not showing up in recyclerview

I am trying to get data that I put into a Backendless console and show it in my android application but the data is not showing up. It just shows a blank activity/screen. It's not crashing either. Frankly, I'd be more pleased if it was. Any help would be greatly appreciated!
Heres my code:
private List<Cake> list;
private Context context;
public CakeAdapter(Context context, List<Cake> list) {
this.context = context;
this.list = list;
}
#Override
public CakeHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_cake, parent, false);
return new CakeHolder(view);
}
#Override
public void onBindViewHolder(CakeHolder holder, int position) {
final Cake cake = list.get(position);
holder.type.setText(cake.getType());
holder.description.setText(cake.getDescription());
// holder.type.setText("I dont know.");
// holder.description.setText("Just some random text. I am in the mood for pizza.");
}
#Override
public int getItemCount() {
return list.size();
}
public class CakeHolder extends RecyclerView.ViewHolder {
//Setup Views
CardView card;
TextView type;
TextView description;
public CakeHolder(View itemView) {
super(itemView);
//Assign views by ID
card = (CardView) itemView.findViewById(R.id.cakecard);
type = (TextView) itemView.findViewById(R.id.type);
description = (TextView) itemView.findViewById(R.id.description);
}
}
}
public class CakeActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, FloatingActionButton.OnClickListener {
//Setup Views
private Toolbar toolbar;
private SwipeRefreshLayout swipe;
private FloatingActionButton fab;
private RecyclerView recycler;
//Setup adapter
private CakeAdapter adapter;
//Setup Cake
private List<Cake> Cake = new ArrayList<>();
//Setup backend call
private BackendlessCollection<Cake> cakes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_Cake);
//Setup toolbar
toolbar = (Toolbar) findViewById(R.id.bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
//Setup SwipeView
swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
swipe.setOnRefreshListener(this);
swipe.setColorSchemeResources(R.color.colorPrimaryDark,
R.color.blade,
android.R.color.holo_orange_light,
R.color.fruit);
//Setup Recyclerview
recycler = (RecyclerView) findViewById(R.id.recycler);
recycler.setItemAnimator(new DefaultItemAnimator());
recycler.setLayoutManager(new LinearLayoutManager(this));
recycler.setHasFixedSize(true);
adapter = new CakeAdapter(this, cake);
recycler.setAdapter(adapter);
//Setup FAB and attach to recycler
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.attachToRecyclerView(recycler);
fab.setOnClickListener(this);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
supportFinishAfterTransition();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
//do something later
}
#Override
public void onRefresh() {
refreshCakes();
if (swipe.isRefreshing()) {
swipe.setRefreshing(false);
}
}
private void refreshCakes() {
QueryOptions query = new QueryOptions();
query.setPageSize(20);
BackendlessDataQuery queries = new BackendlessDataQuery(query);
Backendless.Data.of(Cake.class).find(queries, new AsyncCallback<BackendlessCollection<Cake>>() {
#Override
public void handleResponse(BackendlessCollection<Cake> cakeBackendlessCollection) {
cakes = cakeBackendlessCollection;
addMore(cakeBackendlessCollection);
}
#Override
public void handleFault(BackendlessFault backendlessFault) {
Log.d("Cake", "Error: " + backendlessFault.getMessage());
}
});
}
private void addMore(BackendlessCollection<Cake> next) {
cake.addAll(next.getCurrentPage());
adapter.notifyDataSetChanged();
}
}
Well, I'm gonna duplicate an answer from the support topic: the name of the table on Backendless should match exactly the name of your class.
Or otherwise, you must call Backendless.Data.mapTableToClass("YourTableName", YourClassName.class) somewhere at the start of your program.

Categories

Resources