How to search using an edit text in a recyclerview? - android

I am looking some help for my application. I've built an app and i've included a chat feature. Within the chat fragment I have 2 additional fragments, one for chats currently open and one for all users which can be messaged. I want to incorroprate a search bar into each of these fragements to allow the user to find a certain user to message. I am
users fragment XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/gold"
tools:context=".ChatFragments.UsersFragment">
<EditText
android:id="#+id/etSearch"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#android:color/white"
android:ems="20"
android:hint="#string/search"
android:layout_weight="0.5"
android:paddingLeft="15dp" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_below="#+id/etSearch"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
users fragment java class
package com.alicearmstrong.coffeysloyaltyprojectv1.ChatFragments;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import com.alicearmstrong.coffeysloyaltyprojectv1.Adapter.CustomerAdapter;
import com.alicearmstrong.coffeysloyaltyprojectv1.R;
import com.alicearmstrong.coffeysloyaltyprojectv1.database.Customers;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class UsersFragment extends Fragment {
private RecyclerView recyclerView;
private CustomerAdapter customerAdapter;
private List<Customers> customersList;
DatabaseReference databaseReference;
EditText etSearch;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Inflate the layout for this fragment
View view = inflater.inflate( R.layout.fragment_users , container, false);
etSearch = view.findViewById(R.id.etSearch);
recyclerView = view.findViewById( R.id.recycler_view );
recyclerView.setHasFixedSize( true );
recyclerView.setLayoutManager( new LinearLayoutManager( getContext() ) );
customersList = new ArrayList<>( );
readCustomers();
return view;
}
// Method for reading customers
private void readCustomers()
{
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
databaseReference = FirebaseDatabase.getInstance().getReference().child("Customers");
databaseReference.addValueEventListener( new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
customersList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren())
{
Customers customers = snapshot.getValue(Customers.class);
if (!customers.getId().equals(firebaseUser.getUid()))
{
customersList.add( customers );
}
}
customerAdapter = new CustomerAdapter( getContext(), customersList );
recyclerView.setAdapter( customerAdapter );
}
#Override
public void onCancelled( #NonNull DatabaseError databaseError) {
}
} );
}
}
customerAdapter.java
package com.alicearmstrong.coffeysloyaltyprojectv1.Adapter;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import com.alicearmstrong.coffeysloyaltyprojectv1.uiOwner.chatOwner.MessageActivityOwner;
import com.alicearmstrong.coffeysloyaltyprojectv1.R;
import com.alicearmstrong.coffeysloyaltyprojectv1.database.Customers;
import java.util.ArrayList;
import java.util.List;
public class CustomerAdapter extends RecyclerView.Adapter<CustomerAdapter.ViewHolder>
{
private Context context;
private List<Customers> customersList;
public CustomerAdapter (Context context, List<Customers> customersList)
{
this.customersList = customersList;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i)
{
// Set layout to user_item for displaying each user
View view = LayoutInflater.from(context).inflate( R.layout.user_item , viewGroup, false);
return new CustomerAdapter.ViewHolder( view );
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i)
{
final Customers customer = customersList.get( i );
// Set title to user's name
viewHolder.customerName.setText( customer.getFirstName() + " " + customer.getSurname() );
// Open Message Activity when user is selected
viewHolder.itemView.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent(context, MessageActivityOwner.class );
intent.putExtra( "userid", customer.getId() );
context.startActivity( intent );
}
} );
}
#Override
public int getItemCount()
{
return customersList.size();
}
/* #Override
public Filter getFilter() {
return exampleFilter;
}
private Filter exampleFilter = new Filter()
{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<Customers> filteredList = new ArrayList<>( );
if (constraint == null || constraint.length() == 0)
{
filteredList.addAll( customersList );
}
else
{
// allows search to be case sensitive
String filteredPattern = constraint.toString().toLowerCase().trim();
for(Customers customers : customersList )
{
}
}
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
}
};*/
public class ViewHolder extends RecyclerView.ViewHolder
{
public TextView customerName;
public ViewHolder(#NonNull View view)
{
super( view );
customerName = view.findViewById( R.id.customerName );
}
}
public void upToDate(List<Customers> newList){
customersList = new ArrayList<>();
customersList.addAll(newList);
notifyDataSetChanged();
}
}
customers database
package com.alicearmstrong.coffeysloyaltyprojectv1.database;
public class Customers
{
String id, firstName,surname, DOB, contactNumber, email, qrCode;
Integer loyaltyScore;
public Customers(String id, String firstName, String surname, String DOB, String contactNumber, String email, String qrCode, Integer loyaltyScore)
{
this.id = id;
this.firstName = firstName;
this.surname = surname;
this.DOB = DOB;
this.contactNumber = contactNumber;
this.email = email;
this.qrCode = qrCode;
this.loyaltyScore = loyaltyScore;
}
public String getId() {
return id;
}
public String getFirstName()
{
return firstName;
}
public String getSurname()
{
return surname;
}
public String getDOB()
{
return DOB;
}
public String getContactNumber()
{
return contactNumber;
}
public String getEmail()
{
return email;
}
public String getQrCode()
{
return qrCode;
}
public Integer getLoyaltyScore()
{
return loyaltyScore;
}
public Customers()
{
}
}
I read in to the addTextChangeListener method just not sure how to implement the method. Any help would be greatly appreciated.

why using textView when searchView is exsist. check this code below but let me see ur Customers java class then i can help u better. at the first set search view then find view by id it then ....
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
String userInput = newText.toLowerCase();
List<Customers> newList = new ArrayList<>();
for (Customers customersList : accounts) {
if (customersList.customerName.toLowerCase().contains(userInput)) {
newList.add(accountList);
}
}
accountAdapter.upToDate(newList);
return true;
}
});
then add upToDate function in ur adapter and call it at the above code.
public void upToDate(List<Customers> newList){
customersList = new ArrayList<>();
customersList.addAll(newList);
notifyDataSetChanged();
}

Related

How to update firebase data node from a new activity when child is random key generated by current date and current time

Please see my code and snapshot what I am looking for, I created a new activity from where I can update my product details (note:I will add image upload functionality later in my activity). but from my code I get the result like the snapshot I attached where I marked in red what I wanted. I add products as admin and trying to update as admin but from a different activity I wanted to update my data. Please help me
Here is activity code I am trying
package com.commerce.daily.dailycommerce;
import android.app.ProgressDialog;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import com.commerce.daily.dailycommerce.ViewHolder.ProductViewHolder;
import com.commerce.daily.dailycommerce.model.Products;
import com.commerce.daily.dailycommerce.prevalent.prevalent;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.HashMap;
public class AdminUpdatingProductsActivity extends AppCompatActivity {
private String UpdateDescription, updatePrice, updatePName;
private TextView updateTxtBtn, changeImageTxt, closeTxtBtn;
private EditText productUpdateName, productUpdateDescription, productUpdatePrice;
private DatabaseReference updateProductRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_updating_products);
updateProductRef = FirebaseDatabase.getInstance().getReference().child("Products");
updateTxtBtn = (TextView) findViewById(R.id.update_product_details_btn2);
changeImageTxt = (TextView) findViewById(R.id.product_image_update_txt);
closeTxtBtn = (TextView) findViewById(R.id.close_update_product_btn);
productUpdateName = (EditText) findViewById(R.id.update_product_name);
productUpdateDescription = (EditText) findViewById(R.id.update_product_description);
productUpdatePrice = (EditText) findViewById(R.id.update_product_price);
updateTxtBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
updateinformation();
}
});
}
private void updateinformation() {
updatePName = productUpdateName.getText().toString();
UpdateDescription = productUpdateDescription.getText().toString();
updatePrice = productUpdatePrice.getText().toString();
HashMap<String, Object> ProductMap = new HashMap<>();
ProductMap.put("pname", updatePName);
ProductMap.put("price", updatePrice);
ProductMap.put("description", UpdateDescription);
updateProductRef.updateChildren(ProductMap);
}
}
And here is xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.commerce.daily.dailycommerce.AdminUpdatingProductsActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar_update_product"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/colorPrimary">
<android.support.v7.widget.Toolbar
android:id="#+id/tollbar_update_product"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/close_update_product_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Close"
android:textColor="#android:color/white"
android:textSize="17sp"
android:textStyle="bold"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"/>
<TextView
android:id="#+id/update_product_details_btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Update"
android:textColor="#android:color/white"
android:textSize="17sp"
android:textStyle="bold"
android:layout_marginRight="10dp"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"/>
</RelativeLayout>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<ImageView
android:id="#+id/product_image_update"
android:layout_below="#+id/app_bar_update_product"
android:layout_width="250dp"
android:layout_height="150dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:src="#drawable/ic_menu_camera"/>
<TextView
android:id="#+id/product_image_update_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/product_image_update"
android:text="Change Image"
android:layout_marginTop="4dp"
android:textColor="#android:color/black"
android:textSize="17sp"
android:textStyle="bold"
android:layout_marginRight="10dp"
android:layout_centerHorizontal="true"/>
<EditText
android:id="#+id/update_product_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/product_image_update_txt"
android:inputType="textMultiLine"
android:layout_marginTop="30dp"
android:padding="20dp"
android:hint="Product Name..."
android:layout_marginLeft="45dp"
android:layout_marginRight="45dp"
android:background="#drawable/input_design"/>
<EditText
android:id="#+id/update_product_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/update_product_name"
android:inputType="textMultiLine"
android:layout_marginTop="6dp"
android:padding="20dp"
android:hint="Product Description..."
android:layout_marginLeft="45dp"
android:layout_marginRight="45dp"
android:background="#drawable/input_design"/>
<EditText
android:id="#+id/update_product_price"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/update_product_description"
android:inputType="textMultiLine"
android:layout_marginTop="6dp"
android:padding="20dp"
android:hint="Product Price..."
android:layout_marginLeft="45dp"
android:layout_marginRight="45dp"
android:background="#drawable/input_design"/>
</RelativeLayout>
package com.commerce.daily.dailycommerce;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;
import com.commerce.daily.dailycommerce.Interface.ItemClickListner;
import com.commerce.daily.dailycommerce.ViewHolder.ProductViewHolder;
import com.commerce.daily.dailycommerce.model.Products;
import com.commerce.daily.dailycommerce.prevalent.prevalent;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.squareup.picasso.Picasso;
import java.util.HashMap;
public class AdminListedProductActivity extends AppCompatActivity
{
private DatabaseReference AdminProductsRef;
private RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_listed_product);
AdminProductsRef = FirebaseDatabase.getInstance().getReference().child("Products");
recyclerView = findViewById(R.id.productlist_recycler);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerOptions<Products> options =
new FirebaseRecyclerOptions.Builder<Products>()
.setQuery(AdminProductsRef, Products.class)
.build();
final FirebaseRecyclerAdapter<Products, ProductViewHolder> adapter =
new FirebaseRecyclerAdapter<Products, ProductViewHolder>(options)
{
#Override
protected void onBindViewHolder(#NonNull ProductViewHolder holder, final int position, #NonNull final Products model)
{
holder.txtProductName.setText(model.getPname());
holder.txtProductDescription.setText(model.getDescription());
holder.txtProductPrice.setText("Price = "+ model.getPrice());
Picasso.get().load(model.getImage()).into(holder.imageView);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
CharSequence options[] = new CharSequence[]
{
"Edit",
"Remove"
};
AlertDialog.Builder builder = new AlertDialog.Builder(AdminListedProductActivity.this);
builder.setTitle("Edit/Delete");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which)
{
if(which == 0)
{
updateProducts();
}
if(which == 1)
{
FirebaseDatabase.getInstance().getReference().child("Products")
.child(model.getDate() + model.getTime())
.removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if(task.isSuccessful())
{
Toast.makeText(AdminListedProductActivity.this, "Item Removed Successfully.", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(AdminListedProductActivity.this, AdminCategoryActivity.class);
startActivity(intent);
}
}
});
}
}
});
builder.show();
}
});
}
#NonNull
#Override
public ProductViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_items_layout, parent, false);
ProductViewHolder holder = new ProductViewHolder(view);
return holder;
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
}
private void updateProducts()
{
finish();
}
#Override
public void onBackPressed()
{
super.onBackPressed();
}
}
and here is my Products Class under a package named model
package com.commerce.daily.dailycommerce.model;
/**
* Created by Romen on 2/10/2019.
*/
public class Products
{
private String pname, description, price,image, category, pid, date, time;
public Products()
{
}
public Products(String pname, String description, String price, String image, String category, String pid, String date, String time)
{
this.pname = pname;
this.description = description;
this.price = price;
this.image = image;
this.category = category;
this.pid = pid;
this.date = date;
this.time = time;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
You can't update the specific node which you want in this way, Because you didn't specify which node you want to update its data.
in this line updateProductRef.updateChildren(ProductMap); you specify the "product" node then add data inside it, instead of that you should specify the node that you want to update it.
to achieve this you should put a unique id for each node (like "pid" attribute in your database), then compare it with the "pid" in your current activity.
in your class "products" put getter and setter methods for the "pid" attribute.
when clicking on the special product from your list that contains all "products" get the position of the item and get "pid" from it, like this:
after getting the current item of "pid" send it with the intent by using the putExtra() method on the intent object to the new activity.
catch the string that sent from previous activity and comare it with all pid attributes that in the database, then get key to the product and set as a child.
Edit
actually, I don't understand your code correctly or it is a mistake so, I build another code totally different.
create an adapter class for display products:
public class AdapterProducts extends RecyclerView.Adapter<AdapterProducts.HolderProuducts> {
Context context;
List<products> listProuducts;
private AdapterProducts.OnItemClickListener mListener;
//This interface for handle clicked on an item in recyclerview
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(AdapterProducts.OnItemClickListener listener) {
mListener = listener;
}
//constrouctor
public AdapterProducts(Context context,List<products> listProuducts)
{
this.listProuducts = listProuducts;
this.context = context;
}
#Override
public AdapterProducts.HolderProuducts onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View row = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.row_item_products, viewGroup, false);
AdapterProducts.HolderProuducts holder = new AdapterProducts.HolderProuducts(row, mListener);
return holder;
}
#Override
public void onBindViewHolder(#NonNull AdapterProducts.HolderProuducts holderProuducts, int i) {
holderProuducts.txtProductName.setText(model.getPname());
holderProuducts.txtProductDescription.setText(model.getDescription());
holderProuducts.txtProductPrice.setText("Price = "+ model.getPrice());
Picasso.get().load(model.getImage()).into(holderProuducts.imageView);
}
#Override
public int getItemCount() {
return listProuducts.size();
}
public class HolderProuducts extends RecyclerView.ViewHolder{
TextView txtProductName,txtProductDescription,txtProductPrice;
ImageView imageView;
public HolderProuducts(#NonNull View itemView, final AdapterProducts.OnItemClickListener listener) {
super(itemView);
txtProductName = (TextView) itemView.findViewById(R.id.name_product);
txtProductDescription = (TextView) itemView.findViewById(R.id.description_product);
txtProductPrice = (TextView) itemView.findViewById(R.id.price_product);
imageView = (ImageView) itemView.findViewById(R.id.image_view);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position);
}
}
}
});
}
}
}
in your AdminListedProductActivity:
`
public class AdminListedProductActivity extends AppCompatActivity {
RecyclerView mRecyclerProducts;
List<Products> listProducts;
LinearLayoutManager layoutManager;
AdapterProducts mAdapterProducts;
DatabaseReference AdminProductsRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_listed_product);
AdminProductsRef = FirebaseDatabase.getInstance().getReference().child("Products");
listProducts = new ArrayList();
mRecyclerProducts = findViewById(R.id.productlist_recycler);
mRecyclerProducts.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
mRecyclerProducts.setLayoutManager(layoutManager);
listProducts = displayProuductsInList();
mAdapterProducts.setOnItemClickListener(new AdapterProducts.OnItemClickListener() {
#Override
public void onItemClick(int position) {
Products productsClicked = listProducts.get(position);
//This pid for the item that clicked on it
String pid = productsClicked.getPid();
Intent intent = new Intent(AdminListedProductActivity .this,AdminUpdatingProductsActivity.class);
//send it with intent to activity update
intent.putExtra("pid",pid);
startActivity(intent);
}
});
}
//This method for get all products from database
private List<Products> displayProuductsInList() {
List<Products> list = new ArrayList();
AdminProductsRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
Products products = data.getValue(Products.class);
list.add(products);
}
mRecyclerProducts.setLayoutManager(new LinearLayoutManager(AdminListedProductActivity .this));
mAdapterProducts.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
`
in your AdminUpdatingProductsActivity:
public class AdminUpdatingProductsActivity extends AppCompatActivity {
private String UpdateDescription, updatePrice, updatePName;
private TextView updateTxtBtn, changeImageTxt, closeTxtBtn;
private EditText productUpdateName, productUpdateDescription, productUpdatePrice;
DatabaseReference updateProductRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_listed_product);
updateProductRef = FirebaseDatabase.getInstance().getReference().child("Products");
updateTxtBtn = (TextView) findViewById(R.id.update_product_details_btn2);
changeImageTxt = (TextView) findViewById(R.id.product_image_update_txt);
closeTxtBtn = (TextView) findViewById(R.id.close_update_product_btn);
productUpdateName = (EditText) findViewById(R.id.update_product_name);
productUpdateDescription = (EditText) findViewById(R.id.update_product_description);
productUpdatePrice = (EditText) findViewById(R.id.update_product_price);
updateTxtBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
updateinformation();
}
});
}
private void updateinformation() {
Intent intent = getIntent();
String pidFromPriveosActivity = intent.getStringExtra("pid");
updatePName = productUpdateName.getText().toString();
UpdateDescription = productUpdateDescription.getText().toString();
updatePrice = productUpdatePrice.getText().toString();
HashMap<String, Object> ProductMap = new HashMap<>();
ProductMap.put("pname", updatePName);
ProductMap.put("price", updatePrice);
ProductMap.put("description", UpdateDescription);
updateProductRef.addListenerForSingleValueEvent(new ValueEventListener() {
String currentKey;
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren())
{
//get each "pid" in database for all products
String pidsInDataBase = data.child("pid").getValue(String.class);
//compare "pid" from previous activity with each "pid" in database
if (pidFromPriveosActivity.equals(pidsInDataBase)){
//get key for product that clicke on it in recyclerview
currentKey = data.getKey();
}
}
//update data for this item
updateProductRef.child(currentKey).updateChildren(ProductMap);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}}

Error retrieving data from firebase using recycler view: E/RecyclerView: No adapter attached; skipping layout [duplicate]

This question already has answers here:
recyclerview No adapter attached; skipping layout
(38 answers)
Closed 2 years ago.
I am on a project now and am trying to obtain data from my firebase using recycler view and viewholder, but using my helper class, immediately when the app launches and I try retrieving data through my helper class it crashes, and when i look through my logcat, I get this error
E/RecyclerView: No adapter attached; skipping layout....
I have searched for a lot o answers and i see some but they are not related to my code...
Here is my mainactivity code
package com.example.android.journalapp;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.example.android.journalapp.users.LogInActivity;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
private static final String DATE_FORMAT = "dd/MM/yyy";
private SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT,
Locale.getDefault());
private FirebaseAuth mFirebaseAuth;
private FirebaseUser mFirebaseUser;
private DatabaseReference mDatabase;
String mUserId;
private RecyclerView mRecyclerView;
private FirebaseHelper helper;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseUser = mFirebaseAuth.getCurrentUser();
mRecyclerView = (RecyclerView) findViewById(R.id.journal_recycler);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setHasFixedSize(true);
if (mFirebaseUser == null) {
// Not logged in, launch the Log In activity
loadLogInView();
} else {
mDatabase = FirebaseDatabase.getInstance().getReference();
mUserId = mFirebaseUser.getUid();
helper = new FirebaseHelper(context, mDatabase, mRecyclerView,
mUserId);
helper.refreshData();
}
FloatingActionButton fab = (FloatingActionButton)
findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent addJournalIntent = new Intent(MainActivity.this,
AddJournalActivity.class);
addJournalIntent.putExtra("USER_ID", mUserId);
startActivity(addJournalIntent);
}
});
}
private void loadLogInView() {
Intent intent = new Intent(this, LogInActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_logout) {
mFirebaseAuth.signOut();
loadLogInView();
}
return super.onOptionsItemSelected(item);
}
}
here is my firebase helper class
package com.example.android.journalapp;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import com.example.android.journalapp.model.Journal;
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 java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
public class FirebaseHelper {
private String mUserId;
private Context context;
private DatabaseReference mDb;
RecyclerView mRecyclerView;
ArrayList<Journal> journals = new ArrayList<>();
public JournalAdapter mJournalAdapter;
private static final String DATE_FORMAT = "dd/MM/yyy";
private SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.getDefault());
public FirebaseHelper(Context context, DatabaseReference mDb, RecyclerView mRecyclerView, String mUserId) {
this.context = context;
this.mDb = mDb;
this.mRecyclerView = mRecyclerView;
this.mUserId = mUserId;
}
public void saveData(String journal, String date) {
Journal journalEntry = new Journal(journal, date);
mDb.child("users").child(mUserId).child("journals").push().setValue(journalEntry) ;
// .child("journal")
}
public void recieveData(DataSnapshot ds) {
journals.clear();
for (DataSnapshot dataSnapshot : ds.getChildren()) {
Journal journal = dataSnapshot.getValue(Journal.class);
journals.add(journal);
}
mJournalAdapter = new JournalAdapter(context, journals);
mRecyclerView.setAdapter(mJournalAdapter);
// if (journals.size() > 0) {
//
// mJournalAdapter = new JournalAdapter(context, journals);
// mRecyclerView.setAdapter(mJournalAdapter);
// } else {
// Toast.makeText(context, "No data", Toast.LENGTH_SHORT).show();
// }
}
public void refreshData() {
mDb.child("users").child(mUserId).child("journals").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
recieveData(dataSnapshot);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
recieveData(dataSnapshot);
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
here is my model class
package com.example.android.journalapp.model;
import java.util.Date;
public class Journal {
private String journalContent;
private String date;
public Journal(String journalContent, String date) {
this.journalContent = journalContent;
this.date = date;
}
public String getJournalContent() {
return journalContent;
}
public void setJournalContent(String journalContent) {
this.journalContent = journalContent;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
///
here is my adapter class
package com.example.android.journalapp;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.android.journalapp.model.Journal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Locale;
public class JournalAdapter extends RecyclerView.Adapter<JournalHolder> {
Context context;
private ArrayList<Journal> journals;
private static final String DATE_FORMAT = "dd/MM/yyy";
private SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.getDefault());
public JournalAdapter(Context context, ArrayList<Journal> journals) {
this.context = context;
this.journals = journals;
}
#NonNull
#Override
public JournalHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.journal_layout, parent, false);
JournalHolder holder = new JournalHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull JournalHolder holder, int position) {
holder.mJournalTextView.setText(journals.get(position).getJournalContent());
String date = journals.get(position).getDate();
holder.mDateTextView.setText(date);
}
#Override
public int getItemCount() {
if (journals == null) {
return 0;
}
return journals.size();
}
}
//
here is my viewholder class
package com.example.android.journalapp;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
public class JournalHolder extends RecyclerView.ViewHolder {
TextView mJournalTextView;
TextView mDateTextView;
public JournalHolder(View itemView) {
super(itemView);
mJournalTextView = itemView.findViewById(R.id.journal_text_view);
mDateTextView = itemView.findViewById(R.id.journal_date_text_view);
}
}
i am able to push into the data base, but to retrieve data gives me the error E/RecyclerView: No adapter attached; skipping layout
Try this code..
display_data.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/rvData"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
<TextView
android:id="#+id/dlTvEmpty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No Found"
android:textSize="16dp"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
DisplayActivity.java..
public class DisplayActivity extends AppCompatActivity {
private RecyclerView mRvData;
private DisplayAllData allDataAdapter;
private DatabaseReference mDatabase;
private TextView mTvEmpty;
private FirebaseDatabase mFirebaseInstance;
private List<User> mUserList = new ArrayList<>();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_data);
initView();
}
private void initView() {
mFirebaseInstance = FirebaseDatabase.getInstance();
mDatabase = mFirebaseInstance.getReference("usersDb/UserTable");
mRvData = findViewById(R.id.rvData);
mTvEmpty = findViewById(R.id.dlTvEmpty);
mRvData.setLayoutManager(new LinearLayoutManager(this));
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mUserList.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
User user = dataSnapshot1.getValue(User.class);
mUserList.add(user);
}
allDataAdapter = new DisplayAllData(DisplayActivity.this, mUserList);
mRvData.setAdapter(allDataAdapter);
allDataAdapter.notifyDataSetChanged();
if (mUserList.isEmpty())
mTvEmpty.setVisibility(View.VISIBLE);
else
mTvEmpty.setVisibility(View.GONE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
DisplayAdapter.java..
public class DisplayAllData extends RecyclerView.Adapter<DisplayAllData.ItemViewHolder> {
private List<User> mUserLsit = new ArrayList<>();
private Context mContext;
#Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout, parent, false);
return new ItemViewHolder(view);
}
public DisplayAllData(Context mContext, List<User> mUserLsit) {
this.mContext = mContext;
this.mUserLsit = mUserLsit;
}
#Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
User user = mUserLsit.get(position);
holder.mTvName.setText(user.name);
holder.mTvEmail.setText(user.email);
holder.mTvPwd.setText(user.pwd);
}
#Override
public int getItemCount() {
return mUserLsit.size();
}
public class ItemViewHolder extends RecyclerView.ViewHolder {
TextView mTvName, mTvEmail, mTvPwd;
public ItemViewHolder(View itemView) {
super(itemView);
mTvEmail = itemView.findViewById(R.id.rlTvEmail);
mTvName = itemView.findViewById(R.id.rlTvName);
mTvPwd = itemView.findViewById(R.id.rlTvPwd);
}
}
}
row_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp">
<TextView
android:id="#+id/rlTvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:textSize="20dp" />
<TextView
android:id="#+id/rlTvEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Email"
android:textSize="20dp"
app:layout_constraintTop_toBottomOf="#+id/rlTvName" />
<TextView
android:id="#+id/rlTvPwd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
android:textSize="20dp"
app:layout_constraintTop_toBottomOf="#+id/rlTvEmail" />
</android.support.constraint.ConstraintLayout>
and i hope you add internet permission into android manifest file..
<uses-permission android:name="android.permission.INTERNET"/>
more information refer this link
https://www.simplifiedcoding.net/firebase-realtime-database-crud/

Need Help Sorting ListView with Custom Adapter

I have a Main Activity that holds a viewpager that contains three fragments. In each fragment is a listview populated by a custom adapter. I need the ability to sort by date, name and quantity (the fields that the listview shows)
Here is my Main Activity
package com.bkbeesites.bkbeesalessheet;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.preference.PreferenceManager;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.text.Collator;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private SectionsPageAdapter mSectionsPageAdapter;
private ViewPager viewPager;
private String TAG = "MainActivity";
public ArrayList<Customer> packageData;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("BK Bee Sales - Pending Sales");
setSupportActionBar(toolbar);
mSectionsPageAdapter = new SectionsPageAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.container);
setupViewPager(viewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String dft = preferences.getString("default", "");
if(!dft.equalsIgnoreCase(""))
{
if (dft.equals("package")){
viewPager.setCurrentItem(0);
}else if (dft.equals("nuc")){
viewPager.setCurrentItem(1);
}else if (dft.equals("queen")){
viewPager.setCurrentItem(2);
} else {
viewPager.setCurrentItem(0);
}
}
}
public void showAddCustomer(View view){
Intent intent = new Intent(this, AddCustomer.class);
startActivity(intent);
}
public void sortDate (View view){
Tab1 tab1 = new Tab1();
Tab2 tab2 = new Tab2();
Tab3 tab3 = new Tab3();
if (viewPager.getCurrentItem()==0){
tab1.sortDate();
}
}
private void setupViewPager(ViewPager viewPager){
SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
adapter.addFragment(new Tab1(), "Packages");
adapter.addFragment(new Tab2(), "Nucs");
adapter.addFragment(new Tab3(), "Queens");
viewPager.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(this, Preferences.class);
startActivity(intent);
return true;
} else if (id==R.id.action_viewList){
Intent intent = new Intent(this,SalesRecord.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
}
Here is my Tab1 Class
package com.bkbeesites.bkbeesalessheet;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Tab1 extends Fragment {
private CustomerAdapter customerAdapter;
private static final String TAG = "fragment_tab1";
private ListView tab1ListView;
private ArrayList<Customer> packageData = new ArrayList<>();
TextView totalPackages;
TextView totalGross;
View rootView;
public Tab1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_tab1, container, false);
tab1ListView = (ListView) rootView.findViewById(R.id.tab1ListView);
totalPackages = (TextView)rootView.findViewById(R.id.totalPackages);
totalGross = (TextView)rootView.findViewById(R.id.totalGross);
return rootView;
}
#Override
public void onResume(){
super.onResume();
updatePackageList();
}
public void updatePackageList() {
packageData.clear();
tab1ListView.setAdapter(null);
int totalPackagesInt = 0;
try {
DatabaseHelper dbHelper = DatabaseHelper.getInstance(getActivity().getApplicationContext());
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c = db.rawQuery("SELECT * FROM packageCustomers", null);
if (c != null) {
if (c.moveToFirst()) {
while (!c.isAfterLast()){
Customer cus = new Customer();
cus.setDate(c.getString(c.getColumnIndex("date")));
cus.setName(c.getString(c.getColumnIndex("name")));
cus.setPhone(c.getString(c.getColumnIndex("phone")));
cus.setEmail(c.getString(c.getColumnIndex("email")));
cus.setQuantity(c.getInt(c.getColumnIndex("quantity")));
cus.setNotes(c.getString(c.getColumnIndex("notes")));
cus.setId(c.getInt(c.getColumnIndex("id")));
packageData.add(cus);
totalPackagesInt = totalPackagesInt + cus.getQuantity();
c.moveToNext();
}
}
}
customerAdapter = new CustomerAdapter(this.getContext(), packageData);
tab1ListView.setAdapter(customerAdapter);
db.close();
c.close();
String totalPackagesText = totalPackagesInt + " Total Packages Reserved";
totalPackages.setText(totalPackagesText);
packageMath(totalPackagesInt);
tab1ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Customer cus = new Customer();
cus = customerAdapter.getItem(position);
int sqlId = cus.getId();
Intent intent = new Intent(getContext(), CustomerModel.class);
intent.putExtra("table", "packageCustomers");
intent.putExtra("id", sqlId);
startActivity(intent);
}
});
} catch (SQLiteException se) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
}
}
public void packageMath(int i){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(rootView.getContext());
String p = preferences.getString("packagePrice","");
if(!p.equals("")) {
int price = Integer.parseInt(p);
int totalGrossInt = i * price;
String grossText = "Projected Earnings: $" + String.valueOf(totalGrossInt);
totalGross.setText(grossText);
} else {
totalGross.setText("Edit Price Preferences");
}
}
public void sortDate(){
Collections.sort(packageData);
tab1ListView.setAdapter(customerAdapter);
updatePackageList();
}
}
Here is my Customer Class
package com.bkbeesites.bkbeesalessheet;
import android.support.annotation.NonNull;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/**
* Created by Brett on 12/6/2017.
*/
public class Customer implements Comparable<Customer>{
public String name;
private String email;
private String phone;
private int quantity;
private String notes;
private String date;
private int id;
private Date dateTime;
public Customer (){
this.name = "";
this.email="";
this.phone="";
this.quantity=0;
this.notes="";
this.date="";
}
public Customer (int id, String name, String phone, String email, int quantity, String notes, String date) {
this.name = name;
this.email = email;
this.phone = phone;
this.quantity = quantity;
this.notes = notes;
this.date = date;
}
public Date getDateTime() throws ParseException {
String myFormat = "MM/dd/yy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
Date convertedDate = new Date();
convertedDate = sdf.parse(date);
return convertedDate;
}
public void setDateTime(Date dateTime) {
this.dateTime = dateTime;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Override
public int compareTo(#NonNull Customer o) {
try {
return getDateTime().compareTo(o.getDateTime());
} catch (ParseException e) {
e.printStackTrace();
return 0;
}
}
}
And Lastly, here is my CustomerAdapter
package com.bkbeesites.bkbeesalessheet;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Brett on 12/6/2017.
*/
public class CustomerAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mInflater;
private ArrayList<Customer> mDataSource;
public CustomerAdapter(Context context, ArrayList<Customer> items) {
super();
mContext = context;
mDataSource = items;
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return mDataSource.size();
}
//2
#Override
public Customer getItem(int position) {
return mDataSource.get(position);
}
//3
#Override
public long getItemId(int position) {
return position;
}
//4
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get view for row item
View rowView = mInflater.inflate(R.layout.list_item, parent, false);
// Get title element
TextView nameTextView =
(TextView) rowView.findViewById(R.id.nameTextView);
TextView quantityTextView =
(TextView) rowView.findViewById(R.id.quantityTextView);
TextView dateTextView =
(TextView) rowView.findViewById(R.id.dateTextView);
Customer cus = mDataSource.get(position);
nameTextView.setText(cus.getName());
quantityTextView.setText(String.valueOf(cus.getQuantity()));
dateTextView.setText(cus.getDate());
return rowView;
}
}
Sorry if that was a lot of unnecessary code but I'm a beginner here and did not know what you would want to see.
I'm trying to call Collections.sort when the Column Title Textview "Order Date" is clicked. The Data that contains the Customer objects is stored in an SQLite database (not sure if that's pertinent).
You need to write a method in adapter class that should look like this;
public void sort(){
Collections.sort(list, new Comparator<Customer>() {
#Override
public int compare(Customer o1, Customer o2) {
return o1.compareTo(o2);
}
});
notifyDataSetChanged();
}
if you don't want to create comparator every method call you can create variable of comparator.
private Comparator comp = new Comparator<Customer>() {
#Override
public int compare(Customer o1, Customer o2) {
return o1.compareTo(o2);
}
});
in this case you need to change sort method like;
public void sort(){
Collections.sort(list, comp);
notifyDataSetChanged();
}
whenever you want to sort in your activity class you need to call this sort method it will sort your list and update listview.
In your activity class you need to call method like below
adapter.sort();
Also if you want to compare according to other fields. You can create variable as
private int sortType;
You should pass parameter to adapter class.
public void sort(int sortType){
this.sortType = sortType;
Collections.sort(list, comp);
notifyDataSetChanged();
}
and change the comparator field as below
private Comparator comp = new Comparator<Customer>() {
#Override
public int compare(Customer o1, Customer o2) {
switch(sortType){
case 0: //By Name
return o1.getName().compareTo(o2.getName);
break;
case 1:
return o1.getQuantitiy() - o2.getQuantitiy();
break;
case 2:
return o1.compareTo(o2);
break;
default:
return 0;
}
}
});

com.google.firebase.database.databaseexception:firebase database error: Permission denied

im retrieving data in my database from firebase. and shoscription herew up this error can anyone help me? this is my mainactivity.java:
package com.example.infamouslegend.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
FirebaseDatabase database;
DatabaseReference myRef ;
List<FireModel> list;
RecyclerView recycle;
Button view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view = (Button) findViewById(R.id.view);
recycle = (RecyclerView) findViewById(R.id.recycle);
database = FirebaseDatabase.getInstance();
myRef = database.getReference("Complaints");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
list = new ArrayList<FireModel>();
for(DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){
FireModel value = dataSnapshot.getValue(FireModel.class);
FireModel fire = new FireModel();
String Description = value.getDescription();
String Date = value.getDate();
String MediaURL = value.getMediaURL();
fire.setDescription(Description);
fire.setDate(Date);
fire.setMediaURL(MediaURL);
list.add(fire);
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w("Hello", "Failed to read value.", error.toException());
Toast.makeText(MainActivity.this, "Failed to read value !" + error.toException(), Toast.LENGTH_SHORT).show();
}
});
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RecyclerAdapter recyclerAdapter = new RecyclerAdapter(list,MainActivity.this);
RecyclerView.LayoutManager recyce = new GridLayoutManager(MainActivity.this,2);
/// RecyclerView.LayoutManager recyce = new LinearLayoutManager(MainActivity.this);
// recycle.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));
recycle.setLayoutManager(recyce);
recycle.setItemAnimator( new DefaultItemAnimator());
recycle.setAdapter(recyclerAdapter);
}
});
}
}
and this is my firemodel.java:
package com.example.infamouslegend.myapplication;
/**
* Created by Infamous Legend on 10/15/2017.
*/
public class FireModel {
public String Description;
public String Date;
public String MediaURL;
public String getDescription() {
return Description;
}
public void setDescription(String description) {
this.Description = description;
}
public String getDate() {
return Date;
}
public void setDate(String date) {
this.Date = date;
}
public String getMediaURL() {
return MediaURL;
}
public void setMediaURL(String MediaURL) {
this.MediaURL = MediaURL;
}
}
and my recycleradapter.java:
package com.example.infamouslegend.myapplication;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
/**
* Created by Infamous Legend on 10/15/2017.
*/
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyHoder>{
List<FireModel> list;
Context context;
public RecyclerAdapter(List<FireModel> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public MyHoder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.card,parent,false);
MyHoder myHoder = new MyHoder(view);
return myHoder;
}
#Override
public void onBindViewHolder(MyHoder holder, int position) {
FireModel mylist = list.get(position);
holder.Description.setText(mylist.getDescription());
holder.Date.setText(mylist.getDate());
//holder.MediaURL.setText(mylist.getMediaURL());
//Picasso.with(context).load(MediaURL.get(position).getMediaURL()).resize(120, 60).into(MyHoder.MediaURL);
}
#Override
public int getItemCount() {
int arr = 0;
try{
if(list.size()==0){
arr = 0;
}
else{
arr=list.size();
}
}catch (Exception e){
}
return arr;
}
class MyHoder extends RecyclerView.ViewHolder{
TextView Description,Date;
//ImageView MediaURL;
public MyHoder(View itemView) {
super(itemView);
Description = (TextView) itemView.findViewById(R.id.vname);
Date= (TextView) itemView.findViewById(R.id.vemail);
//MediaURL= (ImageView) itemView.findViewById(R.id.thumbnail);
}
}
}
Can anyone help me this? Im trying to retrieve data from firebase database to recyclerview with cardview. Thanks in advance
this is my firebase realtime database rule:
{
"rules": {
".read": true,
".write":true
}
}
If you have configured the app to connect with firebase correctly i would redownload the google-service.json and replace with an existing one.
check this solution

Loading Data from Firebase into Recycleview using Fragments

Can anyone help me with this firebase recycler view using fragments issue? I am having a problem with retrieving the data from firebase to my recycler view. I am using fragments and the app crashes everytime I run it.
Here's my code:
SubjecList.java
package com.google.myeclassrecordapp.mye_classrecord;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import org.w3c.dom.Text;
public class SubjectsList extends Fragment {
private View view;
private Context c;
private RecyclerView myTimeline;
private FirebaseDatabase databaseReference;
private DatabaseReference mFireDatabasaeRef;
private LinearLayoutManager mananger;
private RecyclerView mRecyclerView;
FirebaseRecyclerAdapter<ScheduleListAdapter, ViewHolder> firebaseRecyclerAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = LayoutInflater.from(container.getContext())
.inflate(R.layout.schedule_model, container, false);
mFireDatabasaeRef = FirebaseDatabase.getInstance().getReference().child("SubjectsList");
c = getContext();
mRecyclerView = (RecyclerView) view.findViewById(R.id.rcsched);
mananger = new LinearLayoutManager(c);
mRecyclerView.setHasFixedSize(true);
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<ScheduleListAdapter, ViewHolder>(
ScheduleListAdapter.class,
R.layout.schedule_model,
ViewHolder.class,
mFireDatabasaeRef
)
{
#Override
protected void populateViewHolder(ViewHolder viewHolder, ScheduleListAdapter model, int position) {
viewHolder.setSubjectCode(model.getSubjectCode());
viewHolder.setSection(model.getSection());
viewHolder.setTime(model.getTime());
viewHolder.setDay(model.getDay());
viewHolder.setRoom(model.getRoom());
}
};
mRecyclerView.setAdapter(firebaseRecyclerAdapter);
firebaseRecyclerAdapter.notifyDataSetChanged();
//mRecyclerView.setLayoutManager(mananger);
return view;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
View mView;
public ViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setSubjectCode(String subjectcode){
TextView txtSubjectCode = (TextView) itemView.findViewById(R.id.txtsubjectcode);
txtSubjectCode.setText(subjectcode);
}
public void setSection(String section){
TextView txtSection = (TextView) itemView.findViewById(R.id.txtsection);
txtSection.setText(section);
}
public void setTime(String time){
TextView txtTime = (TextView) itemView.findViewById(R.id.txttime);
txtTime.setText(time);
}
public void setDay(String day){
TextView txtDay = (TextView) itemView.findViewById(R.id.txtday);
txtDay.setText(day);
}
public void setRoom(String room){
TextView txtRoom = (TextView) itemView.findViewById(R.id.txtroom);
txtRoom.setText(room);
}
}
}
ScheduleListAdapater.java
package com.google.myeclassrecordapp.mye_classrecord;
/**
* Created by Pau-Le on 5/12/17.
*/
public class ScheduleListAdapter {
private String SubjectCode;
private String Section;
private String Time;
private String Day;
private String Room;
public ScheduleListAdapter() {
}
public ScheduleListAdapter(String subjectCode, String section, String time, String day, String room) {
SubjectCode = subjectCode;
Section = section;
Time = time;
Day = day;
Room = room;
}
public String getSubjectCode() {
return SubjectCode;
}
public void setSubjectCode(String subjectCode) {
SubjectCode = subjectCode;
}
public String getSection() {
return Section;
}
public void setSection(String section) {
Section = section;
}
public String getTime() {
return Time;
}
public void setTime(String time) {
Time = time;
}
public String getDay() {
return Day;
}
public void setDay(String day) {
Day = day;
}
public String getRoom() {
return Room;
}
public void setRoom(String room) {
Room = room;
}
}

Categories

Resources