How to search enter the edittext value from database - android

I want the Validation for the mobile number ,Am enter the edit text value search with database i want get the error already register your number for the validation setError Or Toast message,Add the Main class, Model class and AppUtil class kindly help me , Am attached code given below. Please tell what i set validation.
public class CreateRyotManagerFragment extends Fragment {
EditText mRyotName, mRyotFatherName, mAddress, mIdNo, mMobile1;
Spinner mDivision;
List<RyotMasterDb> mRyotList;
List<DivitionMasterDb> mDistrickarray;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.layout_new_ryot, container, false);
mMobile1 = view.findViewById(R.id.mobile);
mDivision = view.findViewById(R.id.divition);
mRyotList = AppUtils.getRyotMasterList();
mDistrickarray = AppUtils.getDistrictMasterLIst();
SpinnerAfdapterDistric divisionAdapter = new SpinnerAfdapterDistric(getActivity().getApplicationContext(), mDistrickarray);
mDivision.setAdapter(divisionAdapter);
}
}
#Table(name = "ryotMasterDB", database = AppDatabase.class)
RyotMasterDb extends Model implements Serializable {
#PrimaryKey
public Long id;
#Column(name = "mobile_1")
public String mobile_1;
#Column(name = "mobile_2")
public String mobile_2;
#Column(name = "zone_group_id")
public String zone_group_id;
#Column(name = "bank_id")
public String bank_id;
#Column(name = "branch_id")
public String branch_id;
#Column(name = "sb_ac_no")
public String sb_ac_no;
#Column(name = "state")
public String state;
#Column(name = "remoteID")
public String remoteID;
public RyotMasterDb() {
}
public RyotMasterDb(String remoteId, String imageData, String ryotNo, String catId, String name, String fatherName, String divId, String secID, String villID, String address, String address1, String add2, String add3, String iiSourceID, String irrType, String totalArea, String suitableArea, String pCode, String disID, String talukID, String firID, String factID, String pontentialRyot, String idProof, String idNo, String mobile1, String mobil2m,String passbook_image, String id_proof_image, String id_proof_back_side_image) {
this.remoteID = remoteId;
this.id = Long.getLong(remoteId);
this.mobile_1 = mobile1;
this.mobile_2 = mobil2m;
this.zone_group_id = zoneGroup;
this.bank_id = bankID;
this.branch_id = branchID;
this.sb_ac_no = sbAccNO;
this.state = state;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getMobile_1() {
return mobile_1;
}
public void setMobile_1(String mobile_1) {
this.mobile_1 = mobile_1;
}
public String getMobile_2() {
return mobile_2;
}
public void setMobile_2(String mobile_2) {
this.mobile_2 = mobile_2;
}
public String getZone_group_id() {
return zone_group_id;
}
public void setZone_group_id(String zone_group_id) {
this.zone_group_id = zone_group_id;
}
public String getBank_id() {
return bank_id;
}
public void setBank_id(String bank_id) {
this.bank_id = bank_id;
}
public String getBranch_id() {
return branch_id;
}
public void setBranch_id(String branch_id) {
this.branch_id = branch_id;
}
public String getSb_ac_no() {
return sb_ac_no;
}
public void setSb_ac_no(String sb_ac_no) {
this.sb_ac_no = sb_ac_no;
}
}
public class AppUtils {
static Fragment mFragment;
public static List<RyotMasterDb> getRyotMasterList() {
return Select.from(RyotMasterDb.class).fetch();
}
}

I suggest you use AutoCompleteTextView. An editable text view that shows completion suggestions automatically while the user is typing. The list of suggestions is displayed in a drop down menu from which the user can choose an item to replace the content of the edit box with.
The drop down can be dismissed at any time by pressing the back key or, if no item is selected in the drop down, by pressing the enter/dpad center key.
The list of suggestions is obtained from a data adapter and appears only after a given number of characters defined by the threshold.
Code Sample:
public class CountriesActivity extends Activity {
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.countries);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, COUNTRIES);
AutoCompleteTextView textView = (AutoCompleteTextView)
findViewById(R.id.countries_list);
textView.setAdapter(adapter);
}
private static final String[] COUNTRIES = new String[] {
"Belgium", "France", "Italy", "Germany", "Spain"
};
}
You can refer to this example for a detailed explanation.

You can set a keyListener for your EditText
editText.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN && keycode == KeyEvent.KEYCODE_ENTER){
// do your search in here
String mobileno=mmobile.getText().toString();
//search it
boolean isInList = checkIsPhoneNumberInList(mRyotList,mobileno);
Log.i("CheckResult","is my phone number "+mobileno+" in mRyotList: "+isInList);
if(isInList){
Toast.makeText(getActivity(),"your phone number is already registered",Toast.Toast.LENGTH_LONG).show();
}
}
return false;
}
});
for check whether phone which you input in your edittext is in your database by this method
private boolean checkIsPhoneNumberInList(List<RyotMasterDb> mRyotList,String phoneNumber){
if (mRyotList == null || phoneNumber == null) {
return false;
}
boolean isIn = false;
for (RyotMasterDb rm: mRyotList) {
if (phoneNumber.equals(rm.getMobile_1())||phoneNumber.equals(rm.getMobile_2())){
isIn = true;
}
}
return isIn;
}

Related

Multiple check item send params

I have set switch box in adapter when switch box is enable then open custom check box list item. I have select check box item multiple. This switch box design when select spinner item and then open fragment page. When select multiple check box item and send JSON param like this:
"attendees": [
{
"id": "1",
"person": "xza"
},
{
"id": "2",
"person": "cfd"
}
]
And send button applying in activity. Spinner and save button design in activity and select item design in fragment.
I have make model class like:
public class MeetingModel {
public String date;
public String time;
public boolean reminder;
public boolean assignTOther;
public boolean contactTo;
public boolean attendeesTo;
public String remark;
private MeetingReminder meetingReminder;
private int assignid;
private int contactid;
private List<Assigne> attendees = null;
private int attendeesid;
private String location;
private String purpose;
private String clientType;
private String id;
private String logSubType;
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;
}
public boolean isReminder() {
return reminder;
}
public void setReminder(boolean reminder) {
this.reminder = reminder;
}
public boolean isAssignTOther() {
return assignTOther;
}
public void setAssignTOther(boolean assignTOther) {
this.assignTOther = assignTOther;
}
public boolean isContactTo() {
return contactTo;
}
public void setContactTo(boolean contactTo) {
this.contactTo = contactTo;
}
public boolean isAttendeesTo() {
return attendeesTo;
}
public void setAttendeesTo(boolean attendeesTo) {
this.attendeesTo = attendeesTo;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public MeetingReminder getMeetingReminder() {
return meetingReminder;
}
public void setMeetingReminder(MeetingReminder meetingReminder) {
this.meetingReminder = meetingReminder;
}
public int getAssignid() {
return assignid;
}
public void setAssignid(int assignid) {
this.assignid = assignid;
}
public int getContactid() {
return contactid;
}
public void setContactid(int contactid) {
this.contactid = contactid;
}
public void setMeetingReminder(String date, String time) {
MeetingReminder meetingReminder = new MeetingReminder();
meetingReminder.setDate(date);
meetingReminder.setTime(time);
setMeetingReminder(meetingReminder);
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getPurpose() {
return purpose;
}
public void setPurpose(String purpose) {
this.purpose = purpose;
}
public String getClientType() {
return clientType;
}
public void setClientType(String clientType) {
this.clientType = clientType;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getLogSubType() {
return logSubType;
}
public void setLogSubType(String logSubType) {
this.logSubType = logSubType;
}
public List<Assigne> getAttendees() {
return attendees;
}
public void setAttendees(List<Assigne> attendees) {
this.attendees = attendees;
}
public JsonArray getCheckedItems(){
List<Assigne> tmpList=new ArrayList<>();
List<Assigne> attendees = new ArrayList<>();
JsonArray jsonArray = new JsonArray();
for(Assigne attendee:attendees){
if(attendee.isHeaderSelected()){
tmpList.add(attendee);
attendee.setHeaderSelected(true);
JsonObject obj = new JsonObject();
obj.addProperty("id", attendee.getId());
obj.addProperty("name", attendee.getName());
jsonArray.add(obj);
}
}
return jsonArray;
}
}
I expect the output is:
"attendees":[{"id":"1","person":"fff"},{"id":"2","person":"dfdf"}]
But the actual output is:
"attendees": []

cannot fetch values from firebase database

Main activity.java
public class activity_3 extends AppCompatActivity {
TextView question,option_1,option_2,option_3,description,winnner;
NumberProgressBar option_progress1, option_progress2,option_progress3;
int val_1;
int val_2;
int val_3;
DatabaseReference Polldata_3;
String optionOne;
String optionTwo;
String optionThree;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_3);
final String que = getIntent().getExtras().getString("que");
final String des = getIntent().getExtras().getString("des");
optionOne = getIntent().getExtras().getString("option1");
optionTwo = getIntent().getExtras().getString("option2");
optionThree = getIntent().getExtras().getString("option3");
final String id_user = getIntent().getExtras().getString("id");
val_1 = getIntent().getExtras().getInt("val1");
val_2 = getIntent().getExtras().getInt("val2");
val_2 = getIntent().getExtras().getInt("val3");
option_progress1 = (NumberProgressBar) findViewById(R.id.option1_progressbar);
option_progress2 = (NumberProgressBar) findViewById(R.id.option2_progressbar);
option_progress3 = (NumberProgressBar) findViewById(R.id.option3_progressbar);
Polldata_3 = FirebaseDatabase.getInstance().getReference("POll").child("poll_3");
final DatabaseReference answsersave = Polldata_3.child(id_user);
question = (TextView) findViewById(R.id.question_showpoll);
option_1 = (TextView) findViewById(R.id.option_1);
option_2 = (TextView) findViewById(R.id.option_2);
option_3 = (TextView) findViewById(R.id.option_3);
description = (TextView) findViewById(R.id.description_user_3);
winnner = (TextView) findViewById(R.id.winner);
option_1.setText(optionOne);
option_2.setText(optionTwo);
option_3.setText(optionThree);
question.setText(que);
description.setText(des);
option_progress1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
option_progress1.setProgress(val_1+1);
option_progress1.setEnabled(false);
option_progress2.setEnabled(false);
option_progress3.setEnabled(false);
val_1++;
answsersave.child("option_1_value").setValue(val_1);
//winnerdeclare();
}
});
option_progress2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
option_progress2.setProgress(val_2+1);
option_progress1.setEnabled(false);
option_progress2.setEnabled(false);
option_progress3.setEnabled(false);
val_2++;
answsersave.child("option_2_value").setValue(val_2);
// winnerdeclare();
}
});
option_progress3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
option_progress3.setProgress(val_3+1);
option_progress1.setEnabled(false);
option_progress2.setEnabled(false);
option_progress3.setEnabled(false);
val_3++;
// winnerdeclare();
answsersave.child("option_3_value").setValue(val_3);
}
});
}
}
ADAPTER CLASS
public class listview_3 extends AppCompatActivity {
ListView listviewpoll3;
private DatabaseReference Poll_data_3;
List<addpoll_3> addpoll_3List;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview_3);
listviewpoll3 = (ListView) findViewById(R.id.poll_listview_3);
Poll_data_3 = FirebaseDatabase.getInstance().getReference("POll").child("poll_3");
addpoll_3List = new ArrayList<>();
listviewpoll3.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
Intent intent = new Intent(listview_3.this, activity_3.class);
addpoll_3 poll = addpoll_3List.get(position);
final String optionone = poll.getOption_1();
final String optiontwo = poll.getOption_2();
final String optionthree = poll.getOption_3();
final String id_user = poll.getId();
final int value_1 = poll.getOption_1_value();
final int value_2 = poll.getOption_2_value();
final int value_3 = poll.getOption_3_value();
final String question = poll.getQuestion();
final String desp = poll.getDescription();
intent.putExtra("option1",optionone);
intent.putExtra("option2",optiontwo);
intent.putExtra("option3",optionthree);
intent.putExtra("id",id_user);
intent.putExtra("val1",value_1);
intent.putExtra("val2",value_2);
intent.putExtra("val3",value_3);
intent.putExtra("que",question);
intent.putExtra("descp",desp);
startActivity(intent);
}
});
}
#Override
protected void onStart() {
super.onStart();
Poll_data_3.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
addpoll_3List.clear();
for(DataSnapshot pollSnapshot: dataSnapshot.getChildren())
{
addpoll_3 poll = pollSnapshot.getValue(addpoll_3.class);
addpoll_3List.add(poll);
}
poll_list_3 adapter = new poll_list_3(listview_3.this,addpoll_3List);
listviewpoll3.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
list class
public class poll_list_3 extends ArrayAdapter<addpoll_3> {
private Activity context;
private List<addpoll_3> addpoll_3List;
public poll_list_3(Activity context, List<addpoll_3> addpoll_3List) {
super(context, R.layout.list_layout, addpoll_3List);
this.context = context;
this.addpoll_3List = addpoll_3List;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View viewitem = inflater.inflate(R.layout.list_layout,null);
TextView textViewName = (TextView) viewitem.findViewById(R.id.tv);
TextView textViewDesp = (TextView) viewitem.findViewById(R.id.tv1);
final addpoll_3 poll1 = addpoll_3List.get(position);
textViewName.setText(poll1.getQuestion());
textViewDesp.setText(poll1.getDescription());
return viewitem;
}
}
I am making a polling app where user can create a poll which is then stored in the firebase database and retrieved into listview of the app
when the user clicks on the list view he is directed to the the activity where there are number of progressbars
i have added a ON-click listener o the progress bar, So when user clicks on the progressbar the val of that option gets incremented in the database. so when a different user vote on the same poll the value from the database is fetched and value of the current user is added displaying the winner,but problem is the value of the progressbar1 gets the value from the database but the other two keep progress bar values start from 0 every time user clicks on the other two progress bar (ie 2 and 3).
please help
addpoll_3.java
public class addpoll_3 {
String id;
String question;
String description;
String option_1;
String option_2;
String option_3;
int option_1_value;
int option_2_value;
int option_3_value;
public addpoll_3(){}
public addpoll_3(String id, String question, String description, String option_1, String option_2, String option_3, int option_1_value, int option_2_value, int option_3_value) {
this.id = id;
this.question = question;
this.description = description;
this.option_1 = option_1;
this.option_2 = option_2;
this.option_3 = option_3;
this.option_1_value = option_1_value;
this.option_2_value = option_2_value;
this.option_3_value = option_3_value;
}
public String getId() {
return id;
}
public String getQuestion() {
return question;
}
public String getDescription() {
return description;
}
public String getOption_1() {
return option_1;
}
public String getOption_2() {
return option_2;
}
public String getOption_3() {
return option_3;
}
public int getOption_1_value() {
return option_1_value;
}
public int getOption_2_value() {
return option_2_value;
}
public int getOption_3_value() {
return option_3_value;
}
}
code:
Activity_3.java
val_1 = getIntent().getExtras().getInt("val1");
val_2 = getIntent().getExtras().getInt("val2");
val_3 = getIntent().getExtras().getInt("val3");
These were changes to be made
//Read from the database
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.
String value = dataSnapshot.getValue(String.class);
Log.d(TAG, "Value is: " + value);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});

Update an EditText of an Intent from a variable of an object

I will try to be brief and precise:
I have a user object that contains a chat, and this is updated every time I receive a message:
public class Usuarios implements Serializable {
private static final long serialVersionUID = 1113799434508676095L;
private int id;
private String nombre;
private String ip;
private boolean isSInicial;
//HERE WILL GO THE VARIABLE THAT STORMS THE CHAT, BUT I DO NOT KNOW HOW TO IMPLEMENT IT
public Usuarios(int id, String nombre, String ip, boolean isSInicial){
this.id = id;
this.nombre = nombre;
this.ip = ip;
this.isSInicial = isSInicial;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public boolean isSInicial() {
return isSInicial;
}
public void setSInicial(boolean SInicial) {
isSInicial = SInicial;
}}
I have an activity, that by clicking on a list, loads a new activity for the specific user:
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long id) {
Usuarios e = (Usuarios) listview.getItemAtPosition(pos);
Intent visorDetalles = new Intent(view.getContext(),Chat.class);
if(Contactos.listaDeContactos.indexOf(e) >= 0) {
visorDetalles.putExtra("indice", Contactos.listaDeContactos.indexOf(e));
startActivity(visorDetalles);
}
else{
Toast.makeText(contexto,"Usuario fuera de linea",Toast.LENGTH_LONG);
}
}
});
I need the EditText that contains the Intent to be updated automatically every time I click on a user of a ListView.
I do not know what kind of variable I should use in the user object and how to implement it.
In your Usuarios class add the variable:
public ArrayList<String> currentChat;
Instead of passing the index, pass the Object himself maybe.
if(Contactos.listaDeContactos.indexOf(e) >= 0) {
visorDetalles.putExtra("usuario",e);
startActivity(visorDetalles);
}
else{
Toast.makeText(contexto,"Usuario fuera de linea",Toast.LENGTH_LONG);
}
And in your onCreate Chat Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Intent intent = getIntent();
Usuario usuario = (Usuario) intent.getSerializableExtra("usuario");
EditText myEditText = (EditText)findViewById(R.id.myEditText1));
String allChat;
for(String chatLine : usuario.currentChat) {
allChat += chatLine + '\n';
}
myEditText.setText(allChat);
Did I got your problem right ?

Firebase Android How to push data from Model class itself

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

How do I populate a spinner with a list of objects and not just strings?

Hello I'm new at Android. I want to populate a Spinner with a list of objects. I have googled how to do it but I just find examples with an array of strings.
Can any one help me?
This is my code:
Categories class:
public class Categories
{
#com.google.gson.annotations.SerializedName("id")
private String mId;
#com.google.gson.annotations.SerializedName("name")
private String mName;
public Categories()
{}
public Categories(String id, String name)
{
this.setId(id);
this.setName(name);
}
#Override
public String toString()
{
return mName;
}
// ******** GET *************
public String getId()
{
return mId;
}
public String getName()
{
return mName;
}
// ******** SET *************
public final void setId(String id)
{
mId = id;
}
public final void setName(String name)
{
mName = name;
}
}
This is my Activity code:
public class AgregarActividadActivity extends ActionBarActivity
{
private MobileServiceClient mClient;
private MobileServiceTable<Activities> mActivitiesTable;
private MobileServiceTable<Categories> mCategoriesTable;
private MobileServiceTable<Projects> mProjectsTable;
private EditText mTxtTitulo;
private EditText mTxtDescr;
String categryId = null;
List<Categories> catList = new ArrayList<Categories>();
Spinner spEstado;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_agregar_actividad);
try
{
mClient = new MobileServiceClient(
"https://site.azure-mobile.net/",
"AppKey",
this);
mActivitiesTable = mClient.getTable(Activities.class);
mCategoriesTable = mClient.getTable(Categories.class);
}
catch (MalformedURLException e)
{
createAndShowDialogExc(new Exception("There was an error creating the Mobile Service. Verify the URL"), "Error");
}
mTxtTitulo = (EditText) findViewById(R.id.txtTitulo);
mTxtDescr = (EditText) findViewById(R.id.txtDescripcion);
getCategories();
spEstado = (Spinner)this.findViewById(R.id.spEstado);
ArrayAdapter<Categories> Adapter = new ArrayAdapter<Categories>(this,
android.R.layout.simple_spinner_item, catList);
Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spEstado.setAdapter(Adapter);
spEstado.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
public void onItemSelected(
AdapterView<?> parent,
View view,
int position,
long id) {
Categories item = (Categories) parent.getItemAtPosition(position);
}
public void onNothingSelected(AdapterView<?> parent) {
}
}
);
spProjects = (Spinner)this.findViewById(R.id.spProyecto);
ArrayAdapter<Projects> proAdapter = new ArrayAdapter<Projects>(this,
android.R.layout.simple_spinner_item, proList);
proAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spProjects.setAdapter(proAdapter);
}
private void getCategories()
{
mCategoriesTable.execute(new TableQueryCallback<Categories>()
{
public void onCompleted(List<Categories> result, int count, Exception exception, ServiceFilterResponse response)
{
if (exception == null)
{
for (Categories item : result)
{
catList.add(item);
}
}
else
{
createAndShowDialog(exception, "Error");
}
}
});
}
}
I get the dropdownlist with the objects, but when I select one item, it is not displayed as the selected item, when the dropdownlist is hidden.
Any idea will help me! Thank you!!
You need to write a CustomAdapter for this. It is similar to writing a CustomAdapter for a ListView. You can look at Custom Adapter for List View for an idea

Categories

Resources