Add items to a List in Firebase in Android - android

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"
}
}
}

Related

android recyclerview load more item upon scrolling using volley

Please help me out to load more data from the server upon scrolling my RecyclerView . Here I have successfully created RecyclerView by loading data from my Mysql server by using volley string request.
Here is my code.
private void populateRecycleView() {
if (Utility.checkNetworkConnection(this)) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Searching...");
progressDialog.setMessage("Searching for the blood donor. Please wait a moment.");
progressDialog.setCancelable(false);
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.GET_DONORS_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONArray jsonArray = new JSONArray(response);
int count = 0;
while (count < jsonArray.length()) {
JSONObject jsonObject = jsonArray.getJSONObject(count);
String firstName = jsonObject.getString("fName");
String secondName = jsonObject.getString("sName");
String email = jsonObject.getString("emailid");
String password = jsonObject.getString("pass");
String mobile = jsonObject.getString("mobile");
String bloodRt = jsonObject.getString("blood");
String age = jsonObject.getString("age");
String gender = jsonObject.getString("gender");
String country = jsonObject.getString("country");
String location = jsonObject.getString("location");
String latitude = jsonObject.getString("latitude");
String longitude = jsonObject.getString("longitude");
String profilePicFIleName = jsonObject.getString("picname");
String profilePicURL = jsonObject.getString("pic");
Donor donor = new Donor(firstName, secondName, email, password, mobile, bloodRt, age, gender,
country, location, latitude, longitude, profilePicFIleName, profilePicURL);
donorsList.add(donor);
count++;
}
donorsAdapter = new DonorsAdapter(FindDonorResult.this, donorsList);
recyclerView = (RecyclerView) findViewById(R.id.rv_search_result_donor);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(FindDonorResult.this));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(donorsAdapter);
donorsAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(FindDonorResult.this, "Active data network is not available.", Toast.LENGTH_LONG).show();
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("bloodGroup", bloodGroup);
return params;
}
};
NetworkRequestSingleTon.getOurInstance(this).addToRequestQue(stringRequest);
} else {
Utility.checkNetworkConnectionFound(this);
}
}
And this is my RecyclerView adapter...
public class DonorsAdapter extends RecyclerView.Adapter<DonorsAdapter.CustomViewHolder> {
private Context context;
private ArrayList<Donor> donorList;
private String bloodGroup;
public DonorsAdapter(Context context, ArrayList<Donor> donorList) {
this.context = context;
this.donorList = donorList;
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_blood_donors_result,
parent, false);
return new CustomViewHolder(view);
}
#Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
final Donor donor = donorList.get(position);
String displayName = donor.getFirstName() + " " + donor.getSecondName();
holder.tvDisplayName.setText(displayName);
holder.tvEmailID.setText(donor.getEmail());
String userProfileURL = donor.getProfilePicURL();
if (!userProfileURL.equals("")) {
Picasso.with(context).load(userProfileURL).resize(80, 80).centerCrop().
into(holder.ivProfilePic);
} else {
holder.ivProfilePic.setImageResource(R.drawable.ic_person_white_24dp);
}
bloodGroup = donor.getBloodGroup();
if (bloodGroup.equals("A+"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.a_);
else if (bloodGroup.equals("A-"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.a_negative);
else if (bloodGroup.equals("B+"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.b_positive);
else if (bloodGroup.equals("B-"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.b_negative);
else if (bloodGroup.equals("O+"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.o_positive);
else if (bloodGroup.equals("O-"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.o_negative);
else if (bloodGroup.equals("AB+"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.ab_positive);
else if (bloodGroup.equals("AB-"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.ab_negative);
if(Utility.isNetworkEnabled){
holder.constraintLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, DisplayDonorDetails.class);
intent.putExtra("donor", donor);
context.startActivity(intent);
}
});
}else {
Toast.makeText(context, "Network not available.", Toast.LENGTH_SHORT).show();
}
}
#Override
public int getItemCount() {
if(donorList != null){
return donorList.size();
}else {
return 0;
}
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
ImageView ivProfilePic, ivBloodTypeDisplay, ivArrow;
TextView tvDisplayName;
TextView tvEmailID;
ConstraintLayout constraintLayout;
public CustomViewHolder(View itemView) {
super(itemView);
ivProfilePic = (ImageView) itemView.findViewById(R.id.civ_user_profile_picture);
ivBloodTypeDisplay = (ImageView) itemView.findViewById(R.id.civ_user_blood_type_display);
ivArrow = (ImageView) itemView.findViewById(R.id.civ_arrow);
tvDisplayName = (TextView) itemView.findViewById(R.id.tvUserNameOnRV);
tvEmailID = (TextView) itemView.findViewById(R.id.tvEmailDisplayOnRV);
constraintLayout = (ConstraintLayout) itemView.findViewById(R.id.recycle_view_item_container);
}
}
}
Populate your donorsAdapter only with the 50 first elements of your donorsList, create a function that save the position of the latest element displayed and add other 50 donors to your adapter starting from the latest position saved when you need it.
Hope it helps.
EDIT
First create an emptyList:
List<Donor> subElements = new ArrayList<>();
and pass it to your adapter:
donorsAdapter = new DonorsAdapter(FindDonorResult.this, subElements);
Now you can create a method like this (you can call in onClick event for example):
private int LAST_POSITION = 0;
private int DONORS_NUM_TOSHOW = 50;
public void showMoreDonors(){
if(donarsList.size() > Last_postion+50){
List<Donor> tempList = new ArrayList<Donor>(donorsList.subList(Last_postion,Last_postion+DONORS_NUM_TOSHOW));
for(Donor a : tempList){
subElements.add(a);
}
Last_postion += DONORS_NUM_TOSHOW;
donorsAdapter.notifyDataSetChanged();
}else{
List<Donor> tempList = new ArrayList<Donor>(donorsList.subList(Last_postion,donorsList.size()));
for(Donor a : tempList){
subElements.add(a);
}
donorsAdapter.notifyDataSetChanged();
}
}
Remember to check when donorsList is over.
I didn't test it, but i hope it is usefull to understand the idea.
Finally, I sort this out. I have got an awesome tutorial from this blog.
http://android-pratap.blogspot.in/2015/06/endless-recyclerview-with-progress-bar.html.
I made some changes to populate the list because my data is on a remote server and by using volley library I fetched the data into the list. Remaining things are same.

Multiple search view for single array list model class data

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);
}
}
}
}

Adding listener to firebase having List like data

I have this structure in Firebase
"shared_items" : {
"-KgGHdgE3L_m6ppVgn99" : {
"_id" : 14,
"added_date" : "08/Mar/2017",
"shared_with_emails" : "{\"abc#abc*com\":{\"name\":\"Customer Care\"},\"xyz#xyz*com\":{\"name\":\"Customercare\"}}",
"user_display_name" : "Logged in user",
"users_email" : "loggedinUser#gmail.com"
}
}
My questions:
When I am saving JSON data in "shared_with_emails" key then my data is automatically appended with "\" slash. Is this normal or I am doing something wrong here?
How can I get entire node based on email Ids present in this JSON object.
Function to create JSON objects from provided contacts..
public class JsonUtils {
final private static String TAG = JsonUtils.class.getSimpleName();
public String ContactsToJson() {
ArrayList<ContactsModel> listOfContacts = new ArrayList<>();
listOfContacts.add(new ContactsModel("abc#gmail.com", "abc"));
listOfContacts.add(new ContactsModel("xyz#gmail.com", "xyz"));
listOfContacts.add(new ContactsModel("mnop#yahoo.com", "mnop"));
JSONObject jsonObjectChild;
JSONObject jsonObjectRoot = new JSONObject();
for (int i = 0; i < listOfContacts.size(); i++) {
ContactsModel model = (ContactsModel) listOfContacts.get(i);
try {
jsonObjectChild = new JSONObject();
jsonObjectChild.put("name", model.getContactName());
jsonObjectRoot.put(model.getContactMail(), jsonObjectChild);
} catch (JSONException e){
e.printStackTrace();
}
}
System.out.println(jsonObjectRoot.toString());
return jsonObjectRoot.toString();
}
public class ContactsModel {
private int id;
private String mContactName;
private String mContactMail;
public ContactsModel(String contactMail, String contactName) {
this.mContactName = contactName;
this.mContactMail = contactMail;
}
public String getContactName() {
return mContactName;
}
public String getContactMail() {
return mContactMail;
}
}
}
Json data on Firebase
You can use ArrayList<String> to have multiple emails saved under shared_with_email. When you retrieve your data, save it inside an object and search whether the object contains the email.
ArrayList<String> keys = new ArrayList<>;
rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(Datasnapshot snap:datasnapshot.getChildren()){
ArrayList<yourObject> current = snap.getValue();
if (current.shared_with_email.contains(someEmail)){
keys.add = snap.getKey(); //Check this, all we need is the key of our object. kd47qjB.... in this case
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Once you have all the keys. Add listeners.
for(String key: keys){
rootRef.child(key).addValueEventListener(new ValueEventListener(){
#override
public void onDataChange(Datasnapshot datasnapshot){
//You successfully added listener to the key where user has its email.
//Do your work here.
}
});
}
You will have to create a class yourObject which resembles the data in your firebase database.

Android Firebase wait for data

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);
}
}
}

Firebase query by time range [android]

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.

Categories

Resources