I need to look for the subject that matches the current time. For example, current time is 1:30. So if I'll run a query with Firebase, it should return the subject Math.
Here's my JSON where "2012123458" is a faculty_id.
schedule:{
"2012123458" : {
"Saturday" : {
"-K8j0EkwmWjj3vMqB2d3" : {
"classroom" : "Lab 3",
"subject" : "Science",
"time_end" : "2:00",
"time_start" : "0:00"
},
"asdasdasd" : {
"classroom" : "Lab 6",
"subject" : "PE",
"time_end" : "18:00",
"time_start" : "17:00"
},
"qweqweqweqwe" : {
"classroom" : "Lab 5",
"subject" : "PE",
"time_end" : "11:00",
"time_start" : "9:00"
}
}
}
}
I've tried this but returns a NullPointerException
gridView.setAdapter(listFaculty);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
FacultyList faculty = (FacultyList) parent.getItemAtPosition(position);
String faculty_id = faculty.getID();
//Display schedule in a Dialog box
final Dialog dialog = new Dialog(Faculty.this);
dialog.setContentView(R.layout.dialog_sched);
Firebase ref = new Firebase("https://infotrack.firebaseio.com/schedule/"+faculty_id+"/Saturday");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot: dataSnapshot.getChildren()){
schedule sched = postSnapshot.getValue(schedule.class);
TextView subject = (TextView) dialog.findViewById(R.id.txtSubject);
TextView time = (TextView) dialog.findViewById(R.id.txtTime);
TextView classroom = (TextView) dialog.findViewById(R.id.txtClassroom);
if(sched != null) {
if (checkTime(sched.getTime_start(), sched.getTime_end())){
Log.e("test", "x");
Log.e("test", "" + dataSnapshot.getChildrenCount());
Log.e("test", postSnapshot.getValue().toString());
Log.e("test", "0");
subject.setText(sched.getSubject());
Log.e("test", sched.getSubject());
time.setText(sched.getTime_start() + " - " + sched.getTime_end());
Log.e("test", "2");
classroom.setText(sched.getClassroom());
}
}
else {
Log.e("test", "null");
}
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.d("sched", firebaseError.getMessage());
}
});
dialog.show();
}
});
schedule class:
public class schedule {
private String subject;
private String time_end;
private String time_start;
public schedule(){ }
public schedule(String subject, String time_end, String time_start){
this.subject = subject;
this.time_end = time_end;
this.time_start = time_start;
}
public String getSubject(){
return subject;
}
public String getTime_end(){
return time_end;
}
public String getTime_start(){
return time_start;
}
}
UPDATE:
The problem now is it does not work for some items on the grid view. It brings me back to my app's home screen after clicking on them. An empty dialog box appears for a short period then returns to the home screen.
Related
Hi in the below code implemented autocomplete textview dynamically and saving the response locally.Now If am search for letter 'a' then from that is it displaying and settext to autocomplete textview.setext is working fine when I am selected the text want to get the Id
Onitemclick Toast message is not displaying.
Can any one help me where I did the mistake
private void fetchProductnameJSON(){
autoproduct_name.setHint(Html.fromHtml ( "Item Name"+""));
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Write code for your refresh logic
sessionId = getActivity().getIntent().getStringExtra("sessionId");
String operation = "syncModuleRecords";
String module = "Products";
String syncToken = "";
String mode = "public";
final GetNoticeDataService service = RetrofitInstance.getRetrofitInstance().create(GetNoticeDataService.class);
/** Call the method with parameter in the interface to get the notice data*/
Call<SyncModule> call = service.GetSyncModuleList(operation, sessionId, module, syncToken, mode);
/**Log the URL called*/
Log.i("URL Called", call.request().url() + "");
call.enqueue(new Callback<SyncModule>() {
#Override
public void onResponse(Call<SyncModule> call, Response<SyncModule> response) {
Log.e("response", new Gson().toJson(response.body()));
if (response.isSuccessful()) {
Log.e("response", new Gson().toJson(response.body()));
SyncModule syncModule = response.body();
Gson g = new Gson();
String jsonAllProducts = g.toJson(syncModule);
tinydb.putString("jsonAllProducts",jsonAllProducts);
workingOnResponseProduct(syncModule);
}
}
#Override
public void onFailure(Call<SyncModule> call, Throwable t) {
}
// progressDialog.dismiss();
});
}
}, 0);
return ;
}
private void workingOnResponseProduct(SyncModule syncModule) {
autoproduct_name.setHint(Html.fromHtml ( "Item Name"+""));
String success = syncModule.getSuccess();
if (success.equals("true")) {
SyncResults results = syncModule.getResult();
Sync sync = results.getSync();
ArrayList<SyncUpdated> syncUpdateds = sync.getUpdated();
for (SyncUpdated syncUpdated : syncUpdateds) {
String unitprice="";
product_id = syncUpdated.getId();
ArrayList<SyncBlocks> syncBlocks = syncUpdated.getBlocks();
for (SyncBlocks syncBlocks1 : syncBlocks) {
String label = syncBlocks1.getLabel();
//Basic Information
if (label.equals("Product Details")) {
ArrayList<SynFields> synFields = syncBlocks1.getFields();
for (SynFields synFields1 : synFields) {
String name = synFields1.getName();
values = synFields1.getValue();
if (name.equals("productname")) {
productname = String.valueOf(values);
product_name.add(productname);
Log.d("products",String.valueOf(product_name.size()));
RecordsProducts records = new RecordsProducts(product_id,productname);
recordsListProduct.add(records);
}
}
}
//pricing information
else if (label.equals("Pricing Information")) {
ArrayList<SynFields> synFields = syncBlocks1.getFields();
for (SynFields synFields1 : synFields) {
String name = synFields1.getName();
values = synFields1.getValue();
if (name.equals("unit_price")) {
unitprice = String.valueOf(values);
Log.d("unitprice",unitprice);
//
}
}
}
}
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(),android.R.layout.simple_list_item_1, product_name);
autoproduct_name.setAdapter(adapter);
autoproduct_name.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(position+1 > 0) {
RecordsProducts recordsProducts=recordsListProduct.get(position);
String product_id=recordsProducts.getId();
Log.d("productid",product_id);
String productnames=recordsProducts.getProductname();
autoproduct_name.setText(productnames);
Toast.makeText(getContext(),"selected"+product_id,Toast.LENGTH_LONG).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
TableRow tbrow0 = new TableRow(getContext());
Resources resource = getContext().getResources();
tbrow0.setLayoutParams(getLayoutParams());
tbrow0.addView(getTextView(0, "Product Name", Color.WHITE, Typeface.NORMAL, resource.getColor(R.color.tabs1)));
tbrow0.addView(getTextView(0, "Quantity", Color.WHITE, Typeface.NORMAL,resource.getColor(R.color.tabs1)));
tbrow0.addView(getTextView(0, "Unit Price", Color.WHITE, Typeface.NORMAL, resource.getColor(R.color.tabs1)));
tbrow0.addView(getTextView(0, "Total", Color.WHITE, Typeface.NORMAL, resource.getColor(R.color.tabs1)));
stk.addView(tbrow0,getLayoutParams());
//String[] namesList = p.split(",");
//String[] priceList = listprices.split(",");
}
Here is the solution from this answer
https://stackoverflow.com/a/4752309/3811162
autoproduct_name.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(position+1 > 0) {
RecordsProducts recordsProducts=recordsListProduct.get(position);
String product_id=recordsProducts.getId();
Log.d("productid",product_id);
String productnames=recordsProducts.getProductname();
autoproduct_name.setText(productnames);
Toast.makeText(getContext(),"selected"+product_id,Toast.LENGTH_LONG).show();
}
}
});
I want to get selected data from firebase. Actually I used listview for getting values. On selected item I need more info from data. But unfortunately am not be able to get selected data.
That's relevant code.
New_Deal_List.java
lvDealList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
NewDeal_Database newDeal_database = dealList.get(i);
Intent intent = new Intent(getApplicationContext(), Deal_Detail_one.class);
mEditor.putString(getString(R.string.COOKER_ID), newDeal_database.getuId());
mEditor.commit();
passingtoDealDaysCheckValues(newDeal_database.getDealId());
startActivity(intent);
}
});
}
Passing deal id to this function.
dealDaysRefrence.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dealSnapshot : dataSnapshot.getChildren())
{
NewDeal_Database newDeal_database = dealSnapshot.child(DealId).getValue(NewDeal_Database.class);
try{
Toast.makeText(New_Deal_List.this,dealSnapshot.child(DealId).getValue(NewDeal_Database.class).toString(),Toast.LENGTH_SHORT).show();
if(newDeal_database.getMonday()== true ){
Toast.makeText(getApplicationContext(),DEAL_DAYS_MONDAY,Toast.LENGTH_SHORT).show();
DEAL_DAYS_MONDAY = "Available";
}else{
Toast.makeText(getApplicationContext(),DEAL_DAYS_MONDAY,Toast.LENGTH_SHORT).show();
DEAL_DAYS_MONDAY = "Not-Available";
}
if(dealSnapshot.child(DealId).getValue(NewDeal_Database.class).getTuesday() == true){
DEAL_DAYS_TUESDAY = "Available";
Toast.makeText(getApplicationContext(),DEAL_DAYS_TUESDAY,Toast.LENGTH_SHORT).show();
}else{
DEAL_DAYS_TUESDAY = "Not-Available";
Toast.makeText(getApplicationContext(),DEAL_DAYS_TUESDAY,Toast.LENGTH_SHORT).show();
}
if(dealSnapshot.child(DealId).getValue(NewDeal_Database.class).getWednesday() == true){
DEAL_DAYS_WEDNESDAY = "Available";
}else{
DEAL_DAYS_WEDNESDAY = "Not-Available";
}
if(dealSnapshot.child(DealId).getValue(NewDeal_Database.class).getThursday() == true){
DEAL_DAYS_THURSDAY = "Available";
}else{
DEAL_DAYS_THURSDAY = "Not-Available";
}
if(dealSnapshot.child(DealId).getValue(NewDeal_Database.class).getFriday() == true){
DEAL_DAYS_FRIDAY = "Available";
}else{
DEAL_DAYS_FRIDAY = "Not-Available";
}
}catch (Exception e){
e.printStackTrace();
}finally {
mEditor.putString(getString(R.string.DEAL_DAYS_MONDAY), DEAL_DAYS_MONDAY);
mEditor.commit();
mEditor.putString(getString(R.string.DEAL_DAYS_TUESDAY), DEAL_DAYS_TUESDAY);
mEditor.commit();
mEditor.putString(getString(R.string.DEAL_DAYS_WEDNESDAY), DEAL_DAYS_WEDNESDAY);
mEditor.commit();
mEditor.putString(getString(R.string.DEAL_DAYS_THURSDAY), DEAL_DAYS_THURSDAY);
mEditor.commit();
mEditor.putString(getString(R.string.DEAL_DAYS_FRIDAY), DEAL_DAYS_THURSDAY);
mEditor.commit();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
In above code, if and else condition not getting desired values.
Also android studio give me suggetion. Check suggetion snapshot
This is NewDeal_Database.java class, where i set the values.
public NewDeal_Database(Boolean Monday, Boolean Tuesday, Boolean Wednesday, Boolean Thursday, Boolean Friday){
this.Monday = Monday;
this.Tuesday = Tuesday;
this.Wednesday = Wednesday;
this.Thursday = Thursday;
this.Friday = Friday;
public Boolean getMonday() {
return Monday;
}
public Boolean getTuesday() {
return Tuesday;
}
public Boolean getWednesday() {
return Wednesday;
}
public Boolean getThursday() {
return Thursday;
}
public Boolean getFriday() {
return Friday;
}
I am inserting data from into firebase in New_Deal_Time.java
using this codeNew_Deal_Time.java
dealDaysRefrence.child(id).child(DealId).setValue(dealdays);
firebase snapshot
suggsetion snapshot
First, your NewDeal_Database.java class should look like this:
public class NewDeal_Database {
public NewDeal_Database(Boolean monday, Boolean tuesday, Boolean wednesday, Boolean thursday, Boolean friday){
this.monday = monday;
this.tuesday = tuesday;
this.wednesday = wednesday;
this.thursday = thursday;
this.friday = friday;
public NewDeal_Database {} //Needed for Firebase
public Boolean getMonday() {
return monday;
}
public Boolean getTuesday() {
return tuesday;
}
public Boolean getWednesday() {
return wednesday;
}
public Boolean getThursday() {
return thursday;
}
public Boolean getFriday() {
return friday;
}
}
To get that data, please use the following code:
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String eightToten = ds.child("eightToten").getValue(Boolean.class);
String nineToeleven = ds.child("nineToeleven").getValue(Boolean.class);
String sixToeight = ds.child("sixToeight").getValue(Boolean.class);
String twelveTotwo = ds.child("twelveTotwo").getValue(Boolean.class);
Log.d("TAG", eightToten + " / " + nineToeleven + " / " + sixToeight + " / " + twelveTotwo);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
dealDaysRefrence.child(id).addListenerForSingleValueEvent(eventListener);
I have a model class array list with field name, code and mobile. I want to use search view for all. For example, if I write in name search view xyz and in mobile search view 9768 then it gives all the match of xyz and 9768.
searchMasterList2.add(new SearchItemMaster("111", "222", "333"));
searchMasterList2.add(new SearchItemMaster("555", "333", "444"));
searchMasterList2.add(new SearchItemMaster("222", "444", "555"));
searchMasterList2.add(new SearchItemMaster("333", "111", "222"));
searchMasterList2.add(new SearchItemMaster("444", "555", "111"));
final android.support.v7.widget.SearchView searchView1 = (android.support.v7.widget.SearchView) getView().findViewById(R.id.item_name_edtv);
searchView1.setOnSearchClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
is_click_search_item=true;
is_click_search_group=false;
}
});
searchView1.setOnQueryTextListener(this);
searchView1.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
is_click_search_item=true;
is_click_search_group=false;
}
});
final android.support.v7.widget.SearchView searchView2 = (android.support.v7.widget.SearchView) getView().findViewById(R.id.group_edtv);
searchView2.setOnSearchClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
is_click_search_item=false;
is_click_search_group=true;
}
});
searchView2.setOnQueryTextListener(this);
searchView2.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
is_click_search_item=false;
is_click_search_group=true;
}
});
#Override
public boolean onQueryTextChange(String newText) {
final List<SearchItemMaster> filteredModelList = filter(searchMasterList2, newText);
Log.v("App", newText + ", " + searchMasterList2.size() + ", " + filteredModelList.size());
adapter.animateTo(filteredModelList);
recyclerView.scrollToPosition(0);
return false;
}
private List<SearchItemMaster> filter(List<SearchItemMaster> numbers, String input_text) {
input_text = input_text.toLowerCase();
ArrayList<SearchItemMaster> filteredCompanyList = new ArrayList<>();
for (SearchItemMaster searchItemMaster : numbers) {
if (is_click_search_group) {
final String moblieNo = searchItemMaster.getMoblieNo();
if (moblieNo.contains(input_text)) {
filteredCompanyList.add(searchItemMaster);
}
}
if (is_click_search_item) {
final String code = searchItemMaster.getCode().toLowerCase();
if (code.contains(input_text)) {
filteredCompanyList.add(searchItemMaster);
}
}
}
return filteredCompanyList;
}
You can do it using loop and comparing each item values.
For Ex. if you enter Xyz in name search and 9876 in number then loop like:-
ArrayList<SearchItemMaster> resultArrayList = new ArrayList<>();
for(SearchItemMaster searchItemMasterObj : searchItemMasterList) {
if(searchItemMasterObj.getName().contains("Xyz") && searchItemMasterObj.getNumber().contains("9876")) {
resultArrayList.add(searchItemMasterObj);
}
}
and then you can use resultArrayList to show the result.
hope this will help you. :)
** i changed following code and working fine for me **
ArrayList<SearchItemMaster> searchMasterList2 = new ArrayList<>();
ArrayList<SearchItemMaster> filteredCompanyList1 = new ArrayList<>();
ArrayList<SearchItemMaster> filteredCompanyList2 = new ArrayList<>();
#Override
public boolean onQueryTextChange(String newText) {
if(is_click_search_item){
filteredCompanyList1.clear();
}
if(is_click_search_group){
filteredCompanyList2.clear();
}
final List<SearchItemMaster> filteredModelList = filter(searchMasterList2, newText);
Log.v("App", newText + ", " + searchMasterList2.size() + ", " + filteredModelList.size());
adapter.animateTo(filteredModelList);
recyclerView.scrollToPosition(0);
return false;
}
for (SearchItemMaster searchItemMaster : numbers) {
if (is_click_search_group) {
final String moblieNo = searchItemMaster.getMoblieNo().toLowerCase();;
if (moblieNo.contains(input_text)) {
filteredCompanyList2.add(searchItemMaster);
if(filteredCompanyList1.size()!=0) {
filteredCompanyList.add(searchItemMaster);
filteredCompanyList.retainAll(filteredCompanyList1);
}
else{
filteredCompanyList.add(searchItemMaster);
filteredCompanyList.retainAll(searchMasterList2);
}
}
}
if (is_click_search_item) {
final String code = searchItemMaster.getCode().toLowerCase();
if (code.contains(input_text)) {
filteredCompanyList1.add(searchItemMaster);
if(filteredCompanyList2.size()!=0){
filteredCompanyList.add(searchItemMaster);
filteredCompanyList.retainAll(filteredCompanyList2);
}
else{
filteredCompanyList.add(searchItemMaster);
filteredCompanyList.retainAll(searchMasterList2);
}
}
}
}
in my android application I create an activity which contains a ListView which is populated with data from Firebase Database.
The JSON Tree of the structure of the database is the following:
{
"companies" : {
"companyX" : {
"address" : "50th avenue, NY",
"name" : "Spare-Tools Ltd."
},
"companyZ" : {
"address" : "50th Broadway, NY",
"name" : "Burgers and Burgers"
}
},
"company-requests" : {
"companyX" : {
"req1" : true
"req2" : true
}
},
"requests" : {
"req1" : {
"destination" : "Upper Tooting 122, Bronx",
"origin" : "Philadelphia",
"time" : "1473593287",
...
}
"req2" : {
...
}
}
}
I want to populate the ListView with the list of requests from the requests node. But I first need to know all requests that belong to a specific company so I first go to the company-requests node and retrieve all the request-keys belonging to the specific company.
The problem I am facing is that the ListView is created before the final data from the database arrived:
public class RequestsListActivity extends AppCompatActivity {
private ListView rListView;
DatabaseReference rootNode = FirebaseDatabase.getInstance().getReference();
#Override
protected void onCreate(Bundle savedInstanceState) {
...
rListView = (ListView) findViewById(R.id.result_list_view);
//First I retrieve all the requests of a specific company
DatabaseReference companyRequests = rootNode.child("company-requests/companyX");
companyRequests.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Then I retrieve all the keys of these requests
...
while (iterator.hasNext()) {
String key = iterator.next().getKey();
//For each key I retrieve its details from the requests node
DatabaseReference currRequest = rootNode.child("requests/" + key);
currRequest.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String time;
time = (String) dataSnapshot.child("time").getValue();
Request request = new Request(time);
allRequests.add(request);
}
...onCancelled...
});
}
//THIS CODE IS EXECUTED TO EARLY: BEFORE WE HAVE ANY DATA FROM FIREBASE
RequestAdapter adapter = new RequestAdapter(RequestsListActivity.this, allRequests);
rListView.setAdapter(adapter);
}
...onCancelled...
});
}
}
How can I insert a wait (spinner?) that waits until the values are loaded from Firebase?
You can use a simple counter to keep track of the number of pending loads:
companyRequests.addValueEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
// at the start we need to still load all children
final long[] pendingLoadCount = { dataSnapshot.getChildrenCount() };
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
//For each key I retrieve its details from the requests node
DatabaseReference currRequest = rootNode.child("requests/" + childSnapshot.getKey());
currRequest.addListenerForSingleValueEvent(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
String time;
time = (String) dataSnapshot.child("time").getValue();
Request request = new Request(time);
allRequests.add(request);
// we loaded a child, check if we're done
pendingLoadCount[0] = pendingLoadCount[0] - 1;
if (pendingLoadCount[0] == 0) {
RequestAdapter adapter = new RequestAdapter(RequestsListActivity.this, allRequests);
rListView.setAdapter(adapter);
}
}
...onCancelled...
});
}
}
});
I solved this using a java.util.concurrent.CountDownLatch:
In this example, replace EquityTotalListener with your implementation of ValueEventListener.
private void recalculate() {
final AtomicLong sumUpAll = new AtomicLong();
final CountDownLatch cnt = new CountDownLatch(mapUid2GeoLocation.keySet().size());
for (final String uid : mapUid2GeoLocation.keySet()) {
EquityTotalListener el = mapUid2EquityListener.get(uid);
if (el != null) {
if (logger.isDebugEnabled()) {
logger.debug("Listener for " + uid + " already set up");
cnt.countDown();
}
} else {
el = new EquityTotalListener(database.getDatabase(), uid) {
#Override
public void onCancelled(final DatabaseError databaseError) {
super.onCancelled(databaseError);
cnt.countDown();
}
#Override
protected void valueChanged(final String key, final Object value) {
if (value != null) {
sumUpAll.getAndAdd(Long.parseLong(value.toString()));
cnt.countDown();
}
};
}.attach();
mapUid2EquityListener.put(uid, el);
}
}
if (logger.isDebugEnabled()) {
logger.debug("Waitung for countdown..");
}
try {
final boolean allGood = cnt.await(10, TimeUnit.SECONDS);
if (allGood) {
if (logger.isDebugEnabled()) {
logger.debug("Done waiting, " + uid + " owns " + sumUpAll.get() + " equity");
}
} else {
if (logger.isWarnEnabled()) {
logger.warn("Waiting for read operations ran into timeout");
}
}
} catch (final InterruptedException e) {
if (logger.isErrorEnabled()) {
logger.error(e.getLocalizedMessage(), e);
}
}
}
I am having a hard time trying to figure out how to add more items dynamically to a List in Firebase. As of now I am able to add just one item at the correct firebase location. The user needs to be able to add more items to the list. I am using a custom model class for the data. I would greatly appreciate any help, Thanks.
FloatingActionButton floatSave = (FloatingActionButton) rootView.findViewById(R.id.fabSave);
floatSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myFirebaseRef = new Firebase("https://you.firebaseio.com/");
myFirebaseRef = new Firebase("https://you.firebaseio.com/" + "/users/" + myFirebaseRef.getAuth().getUid());
String partyname = partyName.getText().toString();
String when = fromDateEtxt.getText().toString();
String timeOf = fromTimeEtxt.getText().toString();
String userItems1 = addThisItem.getText().toString();
userItems.add(userItems1);
Map<String,Object> values = new HashMap<>();
values.put("partyname", partyname);
values.put("When", when);
values.put("timeOf", timeOf);
values.put("userItems", userItems);
myFirebaseRef.push().setValue(values);
}
});
//Here is how I try to add additional items to the "userItems" List
final Button addItem = (Button) rootView.findViewById(R.id.buttonAddItem);
addItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences pref = getActivity().getSharedPreferences("MyPref", 0);
SharedPreferences.Editor editor = pref.edit();
String savedParty = pref.getString("thisPostKey", null);
myFirebaseRef = new Firebase("https://you.firebaseio.com/users/8d5d9915-54d8-4fc1-b92f-b45569e8089b/"+ savedParty + "/userItems");
String additem = addThisItem.getText().toString();
userItems.add(additem);
myFirebaseRef.push().setValue(additem);
System.out.println("There are " + thisKey + savedParty);
}
});
public class PartyPost {
private String partyname;
private String timeOf;
private String when;
private List userItems;
public PartyPost(String partyname, String timeOf, String when, List userItems) {
// empty default constructor, necessary for Firebase to be able to deserialize blog posts
this.partyname = partyname;
this.timeOf = timeOf;
this.when = when;
this.userItems = userItems;
}
public void setPartyname(String partyname) {
this.partyname = partyname;
}
public void setTimeOf(String timeOf) {
this.timeOf = timeOf;
}
public void setWhen(String when) {
this.when = when;
}
public void setUserItems(List<String> userItems) {
this.userItems = userItems;
}
public String getPartyname() {
return partyname;
}
public String getTimeOf() {
return timeOf;
}
public String getWhen() {
return when;
}
public List getUserItems() {
return userItems;
}
}
{
"users" : {
"8d5d9915-54d8-4fc1-b92f-b45569e8089b" : {
"-KDcHcfvc3CM-d8TWPE9" : {
"When" : "2-2-2017",
"partyname" : "Super Bowl",
"timeOf" : "5:00PM",
"userItems" : [ "Beer" ]
},
"-KDcHcjRbxXzCvRFa-No" : {
"userItems" : {
"-KDcLXIJ7I9TUFEDyyrA" : "Chips"
}
}
}
}
}
Your /userItems node has child node and per the question it has one child.
"userItems" : {
"-KDcLXIJ7I9TUFEDyyrA" : "Chips"
}
It appears you want to add additional children to that node. To add another child, you will need the path to that specific userItems node, here is pseudo-code
thisUsersUserItemsRef = /users/8d5d9915-54d8-4fc1-b92f-b45569e8089b/-KDcHcjRbxXzCvRFa-No/userItems
then push() the values
values.put("another_user_item", "docs ftw");
thisUsersUserItemsRef.push().setValue(values);
This will result in
"-KDcHcjRbxXzCvRFa-No" : {
"userItems" : {
"-KDcLXIJ7I9TUFEDyyrA" : "Chips",
"-JHoijoiqjodj8jkadiQ" {
"another_user_item": "docs ftw"
}
}
}