I'm trying to display another list inside my custom listview like in the image below. I have successfully display the first three child(name, sport and town). But when i add the coverage child i got this error 'failed to convert value of type arraylist to string' in main activity.
Error message
Failed to convert value of type java.util.ArrayList to String
This is the display im trying to achieve
This is what im trying to achieve
This is my firebase database structure
db structure
I got this code below for my main activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView)findViewById(R.id.cusListView);
mTextView = (TextView)findViewById(R.id.textV);
mRef = FirebaseDatabase.getInstance().getReference().child("Person");
mRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
showData(dataSnapshot);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void showData(DataSnapshot dataSnapshot){
ArrayList<PeopleGetSet> array = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
PeopleGetSet arr = ds.getValue(PeopleGetSet.class);
array.add(arr);
ViewDatabase adapter = new ViewDatabase(this, R.layout.adapter_view_layout, array);
mListView.setAdapter(adapter);
}
}
This it my code for Adapter
public class ViewDatabase extends ArrayAdapter<PeopleGetSet> {
private static final String TAG="ViewDatabase";
private Context mContext;
int mResource;
public ViewDatabase(#NonNull Context context, int resource, #NonNull List<PeopleGetSet> objects) {
super(context, resource, objects);
this.mContext=context;
mResource = resource;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
String name =getItem(position).getName();
String sport =getItem(position).getSport();
String town =getItem(position).getTown();
String Coverage =getItem(position).getCoverage();
PeopleGetSet person = new PeopleGetSet(name,sport, town, Coverage);
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView=inflater.inflate(mResource, parent, false);
TextView tvName = (TextView)convertView.findViewById(R.id.textView);
TextView tvSport = (TextView)convertView.findViewById(R.id.textView2);
TextView tvTown = (TextView)convertView.findViewById(R.id.textView3);
TextView tvCoverage = (TextView)convertView.findViewById(R.id.textView4);
tvName.setText(name);
tvSport.setText(sport);
tvTown.setText(town);
tvCoverage.setText(Coverage);
return convertView;
}
}
And this is my code for Getter and setter
public class PeopleGetSet {
private String name;
private String sport;
private String town;
private String Coverage;
public PeopleGetSet() {
}
public PeopleGetSet(String name, String sport, String town, String Coverage) {
this.name = name;
this.sport = sport;
this.town = town;
this.Coverage = Coverage;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSport() {
return sport;
}
public void setSport(String sport) {
this.sport = sport;
}
public String getTown() {
return town;
}
public void setTown(String town) {
this.town = town;
}
public String getCoverage() {
return Coverage;
}
public void setCoverage(String coverage) {
Coverage = coverage;
}
}
I mean like this:
public class PeopleGetSet {
private String name;
private String sport;
private String town;
private Coverage coverage;
... default code
}
public class Coverage {
private ArrayList<String> names;
... default code
}
Problem is in your Getter Setter class Add Coverage as Hashmap in your PeopleGetSet class. Coverage is not string its array so to read array from firebase you should use HashMap
public class PeopleGetSet {
private String name;
private String sport;
private String town;
private HashMap<String,String> Coverage ;
public PeopleGetSet() {
}
public PeopleGetSet(String name, String sport, String town, HashMap<String, String> Coverage) {
this.name = name;
this.sport = sport;
this.town = town;
this.Coverage = Coverage;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSport() {
return sport;
}
public void setSport(String sport) {
this.sport = sport;
}
public String getTown() {
return town;
}
public HashMap<String,String> getCoverage() {
return Coverage;
}
There is a simple way to inflate multiple views inside one ListView. Here's my example code.
public class MyExampleCode extends ArrayAdapter<Object> {
private static final int TYPE_1 = 0;
private static final int TYPE_2 = 1;
private Context context;
private List<Object> objectList;
public MyExampleCode(Context context, List<Object> objectList) {
super(context,layout,objectList);
this.context = context;
this.objectList = objectList;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
if (getItemViewType(position) == TYPE_1) {
PeopleGetSet peopleGetSet = (PeopleGetSet)objectList.get(position);
//handle code for first object, inflate layout and fill it
} else {
Coverage coverage = (Coverage)objectList.get(position);
//handle code for second object, inflate layout and fill it
}
}
#Override
public int getItemViewType(int position) {
if (getItem(position) instanceof PeopleGetSet) {
return TYPE_1;
} else {
return TYPE_2;
}
}
#Nullable
#Override
public Object getItem(int position) {
return objectList.get(position);
}
#Override
public int getCount() {
return objectList.size();
}
}
#Edit
Let update your code
private void showData(DataSnapshot dataSnapshot){
List<Object> array = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
PeopleGetSet arr = ds.getValue(PeopleGetSet.class);
Coverage arr2 = arr.getCoverage();
array.add(arr);
array.add(arr2);
}
ViewDatabase adapter = new ViewDatabase(this, array);
mListView.setAdapter(adapter);
}
Related
i have facing issue like only two items are displayed others two items are not displayed they are contact and flat no this items are not displaying...i tried also removing and adding others textview but through this only two items are displayed.... Now I want to display the data on a RecyclerView which doesn't seem to work, I'm pretty sure that my code is good but something doesn't seem to work and I can't find it.i also try all the things suggested by stackoverflow but nothing can happen so that i think i need to ask...
Here the file
public class RecieptFP extends AppCompatActivity {
private RecyclerView mFirestoreList;
private FirebaseFirestore firebasefirestore;
private FirestoreRecyclerAdapter adapter;
Button Back;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reciept_fp);
Back = findViewById(R.id.btndashboard);
firebasefirestore = FirebaseFirestore.getInstance();
mFirestoreList = findViewById(R.id.firestore_list);
//query
Query query = firebasefirestore.collection("UserDataR");
//RecyclerOptions
FirestoreRecyclerOptions<RecieptModel> options = new FirestoreRecyclerOptions.Builder<RecieptModel>()
.setQuery(query, RecieptModel.class)
.build();
adapter = new FirestoreRecyclerAdapter<RecieptModel, RecieptViewHolder>(options) {
#NonNull
#Override
public RecieptViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listsingleiteam, parent, false);
return new RecieptViewHolder(view);
}
#Override
protected void onBindViewHolder(RecieptViewHolder recieptViewHolder, int i, RecieptModel recieptModel) {
recieptViewHolder.list_name.setText(recieptModel.getName());
recieptViewHolder.list_amount.setText(recieptModel.getAmount());
recieptViewHolder.list_contact.setText(recieptModel.getContact());
recieptViewHolder.list_Flatno.setText(recieptModel.getFlatNo());
}
};
//viewholder
mFirestoreList.setHasFixedSize(false);
mFirestoreList.setLayoutManager(new LinearLayoutManager(this));
mFirestoreList.setAdapter(adapter);
Back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i1 = new Intent(RecieptFP.this, Dashboard.class);
startActivity(i1);
}
});
}
private class RecieptViewHolder extends RecyclerView.ViewHolder {
private TextView list_name;
private TextView list_amount;
private TextView list_contact;
private TextView list_Flatno;
public RecieptViewHolder(#NonNull View itemView) {
super(itemView);
list_name = itemView.findViewById(R.id.list_name);
list_amount = itemView.findViewById(R.id.list_amount);
list_contact = itemView.findViewById(R.id.list_contact);
list_Flatno = itemView.findViewById(R.id.list_Flatno);
}
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
Recipet Model
package com.societypay;
public class RecieptModel {
private String Name;
private String Amount;
private String Contact;
private String FlatNo;
private RecieptModel(){}
private RecieptModel(String Name,String Amount,String Contact,String FlatNo){
this.Name=Name;
this.Amount=Amount;
this.Contact=Contact;
this.FlatNo=FlatNo;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getAmount() {
return Amount;
}
public void setAmount(String amount) {
Amount = amount;
}
public String getContact() {
return Contact;
}
public void setContact(String contact) {
Contact = contact;
}
public String getFlatNo() {
return FlatNo;
}
public void setFlatNo(String flatNo) {
FlatNo = flatNo;
}
}
Please use following pojo and try.
public class RecieptModel
{
private String MobileNo;
private String Amount;
private String Flat_no;
private String Name;
public String getMobileNo ()
{
return MobileNo;
}
public void setMobileNo (String MobileNo)
{
this.MobileNo = MobileNo;
}
public String getAmount ()
{
return Amount;
}
public void setAmount (String Amount)
{
this.Amount = Amount;
}
public String getFlat_no ()
{
return Flat_no;
}
public void setFlat_no (String Flat_no)
{
this.Flat_no = Flat_no;
}
public String getName ()
{
return Name;
}
public void setName (String Name)
{
this.Name = Name;
}
#Override
public String toString()
{
return "ClassPojo [MobileNo = "+MobileNo+", Amount = "+Amount+", Flat_no = "+Flat_no+", Name = "+Name+"]";
}
}
I'm trying to apply the Indexable ListView that I found in Github: https://github.com/woozzu/IndexableListView. But my problem is how can I implement it in Custom ArrayAdapter?. I'm using firebase, and I want to show my data in a listview, but my problem is I also want to implement it with Indexable ListView but I can't because there's something error when I implement it because it says not compatible. Is there any method so that I can implement Indexable ListView in my program?
Here's the portion of my code :
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
bookList.clear();
for (DataSnapshot bookSnapshot : dataSnapshot.getChildren()) {
Book books = bookSnapshot.getValue(Book.class);
bookList.add(books);
}
BookList adapter = new BookList(getActivity(),bookList);
ViewBook.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
BookList.java - the Custom ArrayAdapter
public class BookList extends ArrayAdapter<Book> {
private Activity context;
private List<Book> bookList;
private List<Image> imageList;
private ImageView image;
public BookList(Activity context, List<Book> bookList){
super(context, R.layout.list_layout,bookList);
this.context=context;
this.bookList=bookList;
this.imageList=imageList;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem= inflater.inflate(R.layout.list_layout,null,true);
TextView textViewTitle = (TextView) listViewItem.findViewById(R.id.textViewTitle);
TextView textViewAuthor = (TextView) listViewItem.findViewById(R.id.textViewAuthor);
image = (ImageView) listViewItem.findViewById((R.id.ivUploadImage));
Book books = bookList.get(position);
textViewTitle.setText(books.getBookTitle());
textViewAuthor.setText(books.getAuthorName());
Picasso.with(context).load(books.getBookImageUrl()).into(image);
return listViewItem;
}
}
Book.java
public class Book {
String bookId;
String bookTitle;
String authorName;
String bookDescription;
String bookPublisher;
String bookPages;
String bookISBN;
String bookEdition;
String bookImageUrl;
public Book() {
}
public Book(String bookId, String bookTitle, String authorName, String
bookDescription,String bookPublisher, String bookPages, String bookISBN,
String bookEdition, String bookImageUrl) {
this.bookId = bookId;
this.bookTitle = bookTitle;
this.authorName = authorName;
this.bookDescription = bookDescription;
this.bookPublisher = bookPublisher;
this.bookPages = bookPages;
this.bookISBN = bookISBN;
this.bookEdition = bookEdition;
this.bookImageUrl = bookImageUrl;
}
public String getBookId() {
return bookId;
}
public String getBookTitle() {
return bookTitle;
}
public String getAuthorName() {
return authorName;
}
public String getBookDescription() {
return bookDescription;
}
public String getBookPublisher() {
return bookPublisher;
}
public String getBookPages() {
return bookPages;
}
public String getBookISBN() {
return bookISBN;
}
public String getBookEdition() {
return bookEdition;
}
public String getBookImageUrl() {
return bookImageUrl;
}
}
I am making an android app ,which is get order from customers,but i faced a problem . I am trying to Retrieve Data from Firebase and display in a list view. I can get the data back from Firebase but when it displays in the listview it just displays one data in many times. I want to be displayed on one line for each record. Can anyone see where i am going wrong??
Database Image
ListView Image
OrderHistory
public class OrderHistory
{
String ammount,photoId,trxId,name,copy,photoSize,date;
public OrderHistory(String name,String photoId,String trxId,String copy,String photoSize,String ammount,String date)
{
this.name = name;
this.ammount = ammount;
this.photoId = photoId;
this.copy = copy;
this.photoSize = photoSize;
this.trxId = trxId;
this.date = date;
}
public String getAmmount() {
return ammount;
}
public void setAmmount(String ammount) {
this.ammount = ammount;
}
public String getPhotoId() {
return photoId;
}
public void setPhotoId(String photoId) {
this.photoId = photoId;
}
public String getTrxId() {
return trxId;
}
public void setTrxId(String trxId) {
this.trxId = trxId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCopy() {
return copy;
}
public void setCopy(String copy) {
this.copy = copy;
}
public String getPhotoSize() {
return photoSize;
}
public void setPhotoSize(String photoSize) {
this.photoSize = photoSize;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
OrderHistoryAdapter
public class OrderHistoryAdapter extends BaseAdapter {
private List<OrderHistory> orderHistories;
Context context;
public OrderHistoryAdapter(Context context, List<OrderHistory> myOrderInformations) {
this.context = context;
this.orderHistories = myOrderInformations;
}
#Override
public int getCount() {
return orderHistories.size();
}
#Override
public Object getItem(int position) {
return orderHistories.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.show_my_order_history, parent, false);
final TextView txtName, txtdate, txtPhotoId, trxId,txtAmount,txtPhotoSize,txtCopy;
txtName = (TextView)view.findViewById(R.id.txtName);
txtdate = (TextView)view.findViewById(R.id.txtDate);
txtPhotoId = (TextView)view.findViewById(R.id.txtPhotoId);
trxId = (TextView)view.findViewById(R.id.txtTrx);
txtAmount = (TextView)view.findViewById(R.id.txtAmount);
txtPhotoSize = (TextView)view.findViewById(R.id.txtSize);
txtCopy = (TextView)view.findViewById(R.id.txtCopy);
txtName.setText(orderHistories.get(position).getName());
txtdate.setText(orderHistories.get(position).getDate());
txtPhotoId.setText(orderHistories.get(position).getPhotoId());
trxId.setText(orderHistories.get(position).getTrxId());
txtAmount.setText(orderHistories.get(position).getAmmount());
txtCopy.setText(orderHistories.get(position).getCopy());
txtPhotoSize.setText(orderHistories.get(position).getPhotoSize());
return view;
}
}
OrderHistoryList
public class OrderHistoryList extends AppCompatActivity
{
private DatabaseReference databaseReference;
private List<OrderHistory> orderHistories;
private static String phoneNumber;
private ListView listView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_my_order);
Firebase.setAndroidContext(this);
listView = (ListView)findViewById(R.id.listView);
getAllOrderFromFirebase();
}
private void getAllOrderFromFirebase()
{
orderHistories = new ArrayList<>();
databaseReference = FirebaseDatabase.getInstance().getReference("order");
String phone = getIntent().getExtras().getString("phone");
databaseReference.orderByChild("phone").equalTo(phone).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String amount, photoId, trxId, name, copy, photoSize, date;
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
name = snapshot.child("name").getValue(String.class);
photoId = snapshot.child("photoId").getValue(String.class);
amount = snapshot.child("totalAmount").getValue(String.class);
trxId = snapshot.child("trxId").getValue(String.class);
photoSize = snapshot.child("photoSize").getValue(String.class);
date = snapshot.child("date").getValue(String.class);
copy = snapshot.child("totalCopy").getValue(String.class);
orderHistories.add(new OrderHistory(name, photoId, trxId, copy, photoSize, amount, date));
}
OrderHistoryAdapter adapter;
adapter = new OrderHistoryAdapter(OrderHistoryList.this, orderHistories);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
I guess your problem is by the way you refer to your data so instead of this
databaseReference = FirebaseDatabase.getInstance().getReference("order");
use this
databaseReference = FirebaseDatabase.getInstance().getReference().child("order");
and you didn't use a query object to query your database reference
so now you don't query directly from databaseReference like the way you did it
instead you do this:
Query query=databaseReference.orderByChild("phone").equalTo(phone);
once you have a query that fits you now add on child listener and continue the rest of your code:
query.addChildEventListener(new ChildEventListener() {
//the rest of your code goes here(on child added/changed/......)
)};
I am trying to push an Object of a class to Firebase by defining the function in that class itself, but I am getting stackOverflow error. I am using native datatypes in the class and a Firebase reference object.
The database structure I am using is as follows:
I have created Model Class for Orders as follows:
public class Orders {
private String billNo;
private String custId;
private String dateAndTime;
private int personCount;
private int status;
private int table;
private String orderId;
private boolean AC=true;
public String getBillNo() {
return billNo;
}
public void setBillNo(String billNo) {
this.billNo = billNo;
}
public String getCustId() {
return custId;
}
public void setCustId(String custId) {
this.custId = custId;
}
public String getDateAndTime() {
return dateAndTime;
}
public void setDateAndTime(String dateAndTime) {
this.dateAndTime = dateAndTime;
}
public int getPersonCount() {
return personCount;
}
public void setPersonCount(int personCount) {
this.personCount = personCount;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public int getTable() {
return table;
}
public void setTable(int table) {
this.table = table;
}
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
private DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
public Orders(String orderId, String billNum, String customerId, String date, int personCnt, int status, int tableNo, boolean AC){
this.billNo = billNum;
this.custId = customerId;
this.dateAndTime = date;
this.personCount = personCnt;
this.status = status;
this.table = tableNo;
this.orderId= orderId;
Log.v("Orders","I am in Orders");
}
public Orders(){
}
public void pushOrder(){
Log.v("PushOrdersId",this.getOrderId());
String OId = this.getOrderId();
mDatabase.child("Orders").child(OId).setValue(Orders.this);
}
}
Then I have created its child class Items as follows:
public class Items extends Orders {
private String itemId;
private int qty;
DatabaseReference mRef = FirebaseDatabase.getInstance().getReference("Orders");
public Items(String orderId, String billNum, String customerId, String date, int personCnt, int status, int tableNo, boolean AC) {
super(orderId, billNum, customerId, date, personCnt, status, tableNo, AC);
// this.itemId = itemId;
// this.qty = qty;
Log.v("Items","I am in Items child");
}
public Items() {
}
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
// public void push(HashMap<String, Items> items){
// for (Items item: items.values()) {
// String itemKey = mRef.child(this.getOrderId()).child("items").push().getKey();
//
// mRef.child(this.getOrderId()).child("items").child(itemKey).setValue(item);
// }
// }
}
And then I am calling a function PushOrders from Class Orders in another class:
nm=name.getText().toString();
mob=mobile.getText().toString();
seat=seats.getText().toString();
email=emailID.getText().toString();
mDatabase = FirebaseDatabase.getInstance().getReference("Orders");
String orderTd = mDatabase.push().getKey();
custId = id;
itemsHashMap = new HashMap<>();
// itemsArrayMap.put("itemid","1");
// itemsArrayMap.put("quantity","2");
dateAndTime = new Date();
personCount=Integer.parseInt(seat);
//Toast.makeText(getApplicationContext(), orderTd, Toast.LENGTH_LONG).show();
Items item = new Items(orderTd,billNo, custId, dateAndTime.toString(), personCount, status, table, AC);
item.pushOrder();
// item.push(itemsHashMap);
}
I was able to figure out the following line in class Orders is giving the error, but couldn't figure out why? and how to resolve it.
mDatabase.child("Orders").child(OId).setValue(Orders.this);
Error log
10-05 09:37:34.239 28265-28265/dyncardview.abpss.com E/AndroidRuntime: FATAL EXCEPTION: main Process: dyncardview.abpss.com, PID: 28265 java.lang.StackOverflowError: stack size 8MB at java.lang.reflect.Method.invoke(Native Method) at com.google.android.gms.internal.zzbqi$zza.zzaF
Can anyone please help me out in this case?
I have made some changes in your code according to your firebase DB Structure,
//Set order data
Orders orders=new Orders();
orders.setBillNo("123");
orders.setCustId("12");
orders.setDateAndTime(new Date().toString());
orders.setPersonCount(13);
orders.setStatus(2);
orders.setTable(2);
orders.setOrderId("23");
orders.setAC(true);
//Add items to order
List<Items> itemsList=new ArrayList<Items>();
for(int i=0;i<2;i++){
Items items=new Items();
items.setItemId("55");
items.setQty(i);
itemsList.add(items);
}
orders.setItems(itemsList);
DatabaseReference mRef = FirebaseDatabase.getInstance().getReference("Orders");
mRef.push().setValue(orders);
Your Order class
public class Orders {
private String billNo;
private String custId;
private String dateAndTime;
private int personCount;
private int status;
private int table;
private String orderId;
private boolean AC = true;
private List<Items> items;
//Generate getter and setters other code
}
Item Class
public class Items {
private String itemId;
private int qty;
//Generate getter and setters other code
}
You can fetch order using order key with complete items (You will get complete item list inside your order)
DatabaseReference mRef = FirebaseDatabase.getInstance().getReference("Orders").child(yourOrderKey);
mRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot:dataSnapshot.getChildren()) {
Orders orders=postSnapshot.getValue(Orders.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
After creating an Instance of Firebase DB you just have to write the code snippet below:
User users = new User(userID, name, edtEmail.getText().toString().trim(), edtContactNumber.getText().toString().trim());
//saving data onto database
mDatabase.child("user").child(userID).setValue(users);
You can change the model and data as per requirement
I need to implement an endless pagination listview in my code, I've searched online and I saw a lot of examples, but none of them is using database, my app does the following:
it connects to an API and retrieves the data with json and show it in a listview, ok that works fine, but I want that listview to have an infinite scroll, like the facebook one.
I don't want anyone to write the code for me, I'm asking to someone guide me on wich is the better way to achieve that, I'll share some of my code, so you can understand:
try {
//Repositorio is my database
Repositorio mRepositorio = new Repositorio(getActivity());
List listaDeClientes = mRepositorio.getClientes();
System.out.println(listaDeClientes);
TextView total = (TextView) rootView.findViewById(R.id.totalClientes);
total.setText(getTotalClientes(mRepositorio.getTotalRegistros("clientes")));
final ArrayAdapter ad = new ClienteViewAdapter(this.getActivity(), R.layout.fragment_cliente_item, listaDeClientes);
ListView lv = (ListView) rootView.findViewById(R.id.listaClientes);
lv.setVerticalFadingEdgeEnabled(true);
lv.setVerticalScrollBarEnabled(true);
lv.setAdapter(ad);
} catch (Exception e) {
e.printStackTrace();
}
return rootView;
}
ClienteViewAdapter:
public class ClienteViewAdapter extends ArrayAdapter<ClienteModel> {
private final LayoutInflater inflater;
private final int resourceId;
public ClienteViewAdapter(Context context, int resource, List<ClienteModel> objects) {
super(context, resource, objects);
this.inflater = LayoutInflater.from(context);
this.resourceId = resource;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
ClienteModel mClienteModel = getItem(position);
view = inflater.inflate(resourceId, parent, false);
TextView tvId = (TextView) view.findViewById(R.id.clienteId);
TextView tvNome = (TextView) view.findViewById(R.id.clienteNome);
TextView tvTipo = (TextView) view.findViewById(R.id.clienteTipo);
tvId.setText(String.valueOf(mClienteModel.getClientes_id()));
tvNome.setText(mClienteModel.getNome());
tvTipo.setText(mClienteModel.getTipo());
return view;
}
}
Model:
public class ClienteModel implements Serializable {
private static final long serialVersionUID = 1L;
private Integer clientes_id;
private Integer id_rm;
private Integer credencial_id;
private String nome;
private String tipo;
private String informacao_adicional;
private String _criado;
private String _modificado;
private String _status;
public Integer getClientes_id() {
return clientes_id;
}
public void setClientes_id(Integer clientes_id) {
this.clientes_id = clientes_id;
}
public Integer getId_rm() {
return id_rm;
}
public void setId_rm(Integer id_rm) {
this.id_rm = id_rm;
}
public Integer getCredencial_id() {
return credencial_id;
}
public void setCredencial_id(Integer credencial_id) {
this.credencial_id = credencial_id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
public String getInformacao_adicional() {
return informacao_adicional;
}
public void setInformacao_adicional(String informacao_adicional) {
this.informacao_adicional = informacao_adicional;
}
public String get_criado() {
return _criado;
}
public void set_criado(String _criado) {
this._criado = _criado;
}
public String get_modificado() {
return _modificado;
}
public void set_modificado(String _modificado) {
this._modificado = _modificado;
}
public String get_status() {
return _status;
}
public void set_status(String _status) {
this._status = _status;
}
public static String[] getColunas() {
return Colunas;
}
public static void setColunas(String[] colunas) {
Colunas = colunas;
}
public static String[] Colunas = new String[]{
Coluna.CLIENTES_ID,
Coluna.ID_RM,
Coluna.CREDENCIAL_ID,
Coluna.NOME,
Coluna.TIPO,
Coluna.INFORMACAO_ADICIONAL,
Coluna._CRIADO,
Coluna._MODIFICADO,
Coluna._STATUS
};