firebase retrieve data not working - missing something simple? - java

I have a list of "Persons" profiles that contains some usual identifying information.
I'm able to add new entries programmatically without any issues.
I'm able to retrieve and display in a list the entries in firebase
The issue I am having is with retrieving the profile of the Person whose entry is clicked in the list mentioned above. The code for this is listed below. I have verified that thisPersonRef contains the correct path. As far as I can tell, the event listener is just skipped over/not triggered. I believe I am following the instructions and samples show at https://www.firebase.com/docs/android/guide/retrieving-data.html and https://firebase.google.com/docs/database/android/retrieve-data#attach_an_event_listener
The error I get is:
java.lang.NullPointerException: Attempt to read from field 'java.lang.String com.bcll_tech.ptapp.Persons.Person.barCodeText' on a null object reference
I've also tried using addListenerForSinglevalueEvent as well as ChildEventListener and I get the same results. This makes me think that I must be missing some other step in the process.
Any help is appreciated as I've scoured the list and haven't seen anything quite the same.
Thanks.
public void onPersonSelected(String listRecordId) {
Log.d(logtag, "Activity: List item recordId = " + listRecordId);
final Firebase thisPersonRef = mPersonRef.child("barCodeId").child(listRecordId);
thisPersonRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
Log.d(logtag, "PersonsListViewDetailsFragment: in listener. snapshot of " + thisPersonRef);
Person thisPerson = snapshot.getValue(Person.class);
Log.d(logtag, "From Get Data: Bar Code ID = " + thisPerson.barCodeText + "; Last name = " + thisPerson.lastName);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
Log.d(logtag, "Activity: Get Person: BarCodeId = " + thisPerson.barCodeText);
}

Try like this
final Firebase thisPersonRef = mPersonRef.child("barCodeId").setValue(listRecordId);
and
Person thisPerson = snapshot.getChildren().getValue(Person.class);

Related

Splunk JAVA SDK - Fetch FiredAlerts (i.e Alerts already triggered)

I am trying to fetch the fired alerts using the splunk java sdk. But i am not able to get any reference. Here is the code snippet i have and it is not fetching me any results.
FiredAlertGroupCollection firedAlertGroups = service.getFiredAlertGroups();
System.out.println("Fired Alert : " + firedAlertGroups.size());
for (FiredAlertGroup entity : firedAlertGroups.values()) {
EntityCollection<FiredAlert> alerts = entity.getAlerts();
for (FiredAlert alert : alerts.values()) {
System.out.println("alerts >>>> " +alert.getName() +": " + alert.getSavedSearchName()+": " + alert.getTitle());
}
}
Is there a way, i can filter the alerts fired in the last 24 hours etc.
Please help me on the same.

Chat message custom UI for each message

I've been stuck on this for months and I don't know what to do or where to look to solve it If you guys could point me in the right direction...
Basically, I have a simple chat room that will only ever involve two people and whenever a user sends a message I get two values: their username and their message.
At the moment this is my code for showing each message:
private void append_chat_conversation(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Log.e("Chat details: ", String.valueOf(ds));
chat_username = dataSnapshot.child("username").getValue(String.class);
chat_msg = dataSnapshot.child("message").getValue(String.class);
Log.e("Chat username: ", "" + chat_username);
Log.e("Chat message: ", "" + chat_msg);
}
messageView.append(chat_username + " - " + chat_msg + "\n");
}
As you can see when I get both values I append them into a simple textView in a scrollView in the chat window. However, I don't want that. I want to make it a bit nicer than just simple text. I just don't know how to show that layout below in the link with the relevant data in it (username + message).
Link to a picture that shows what layout I'd like.
Hope I explained it well enough, thanks for the help in advance.

Firebase OnChildAdded() event is producing doubles in the scrollview

I just started to learn Firebase for android a couple of weeks ago, and now I am creating a very basic chat application.
My problem occurs when I press the home button and then go back to the app. I think it calls the OnChildAdded() event again, and so it produces doubles. I don't know how to fix this. I'll be grateful if anyone could help me out.
This is the part where I am having trouble:
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//messageText.append(username + ": " + messageReceived + " \n");
Iterator iterator = dataSnapshot.getChildren().iterator();
String newmsg = null, theusername = null;
while (iterator.hasNext()){
newmsg = (String) ((DataSnapshot) iterator.next()).getValue();
theusername = (String) ((DataSnapshot) iterator.next()).getValue();
}
messageText.append(theusername + ": " + newmsg + " \n");
scrollView.postDelayed(new Runnable() {
#Override
public void run() {
scrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
},200);
}
Here is a picture of the emulator and the structure of my firebase console:
If onChildAdded() is being called multiple times for the same child, it is very likely that you have multiple listeners attached. You'll need to detach the listener when your activity becomes inactive.
// if you attach like this
var listener = ref.addChildEventListener(childEventListener);
// later detach the listener with
ref.removeEventListener(listener);
The best place to detach the listener depends on where you attached it. It is usually best to think of the pairs: onCreate()->onDestroy(), onStart()->onStop(), onResume()->onPause().

ParseQuery fails to get object that exists in backend

reposting this question since I didn't get any responses the first time around. Parse doesn't appear to have any simple means of contacting them about this (which is frustrating), so I really hope someone here can help.
I am currently using Parse to create a messaging app. I have two fundamental ParseObjects in addition to the standard ParseUser, a Chatroom and a Message. A Chatroom contains pointers to the two users in the Chatroom. A Message contains the content of the Message, a pointer to the user who posted it, and a pointer to the Chatroom.
First, I create a list of all the Chatrooms that the current user is in. Then, I'm trying to create a second list of the most recent message in all of these Chatrooms (I have made it impossible to make a Chatroom without sending at least one Message first).
My code looks like this:
TextView mostRecent = (TextView) row.findViewById(R.id.mostRecent);
Date dt1 = null;
ParseQuery lastMessage = ParseQuery.getQuery("Message");
ParseObject chatroom = (ParseObject) roomList.get(position);
Log.w("Chatroom ObjectID...", room.getObjectId());
try {
lastMessage.whereEqualTo("chatroom", chatroom.fetchIfNeeded());
List<ParseObject> allMessages = lastMessage.find();
Log.w("# of Messages...", "Size of the list: " + allMessages.size() + ", Count of query: " + allMessages.count());
if (allMessages.size() > 0) {
mostRecent.setText((String) theList.get(theList.size() - 1).get("content"));
dt1 = allMessages.get(allMessages.size() - 1).getCreatedAt();
}
} catch (ParseException err) {
err.printStackTrace();
Log.w("PARSE ERROR", err.getMessage());
}
This code works for every Chatroom where the current user is the one who created the Chatroom and the Message in that Chatroom. However, whenever I have a different user attempt to start a Chatroom and send a Message to the original user, the code fails.
To be clear, the second user successfully creates both a Chatroom and a Message. I've verified that the Chatroom gets successfully added to the original user's list of Chatrooms, and that the Message contains a pointer to the correct Chatroom. However, for whatever reason, the Logs reveal a list size of 0 and a count of 0. I've even tried querying for the second user's exact message on the original user's account, and it claims the thing doesn't exist.
Any ideas? Could this have something to do with ACL? Thanks in advance!
NOTE: I've confirmed that both users are correctly included in the Message's ACL. What gives? Why isn't this working?
You need to wait for the query to fetch the data.
lastMessage.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> allMessages, ParseException e) {
if (e == null) {
Log.w("# of Messages...", "Size of the list: " + allMessages.size() + ", Count of query: " + allMessages.count());
} else {
Log.w("Exception thrown", e.getMessage());
}
}
}

OneToOne relationship doesn't always fetch

I have a OneToOne relationship between two tables, as shown below:
PreRecordLoad.java:
#OneToOne(mappedBy="preRecordLoadId",cascade = CascadeType.ALL)
private PreRecordLoadAux preRecordLoadAux;
PreRecordLoadAux.java:
#JoinColumn(name = "PRE_RECORD_LOAD_ID", referencedColumnName = "PRE_RECORD_LOAD_ID")
#OneToOne
private PreRecordLoad preRecordLoadId;
I'm using this method to pull back the PreRecordLoad object:
public PreRecordLoad FindPreRecordLoad(Long ID)
{
print("Finding " + ID + "f");
Query query;
PreRecordLoad result = null;
try
{
query = em.createNamedQuery("PreRecordLoad.findByPreRecordLoadId");
query.setParameter("preRecordLoadId", ID);
result = (PreRecordLoad)query.getSingleResult();
//result = em.find(PreRecordLoad.class, ID);
}
catch(Exception e)
{
print(e.getLocalizedMessage());
}
return result;
}
The '+ "f"' is to see if the passed value somehow had something at the end. It didn't.
I originally used em.find, but the same issue occurred no matter which method I used.
I used to use a BigDecimal for the ID because it was the default, and noticed I was getting a precision difference when it worked, and when it didn't work. Specifically the precision was 4 when it didn't work, but 0 when it did. I couldn't work out why this was, so I changed the BigDecimal to a Long, as I never really needed it to be a BigDecimal anyway.
When I save the new PreRecordLoad and PreRecordLoadAux objects to the database (inserting them for the first time), and then try and run this method to recall the objects, it retrieves the PreRecordLoad, but the PreRecordLoadAux is null. This is despite the entry being in the database and what looks to be full committed, as I can access it from SQLDeveloper, which is a separate session.
However, if I stop and re-run the application, then it successfully pulls back both objects. The ID being passed is the same both times, or at least appears to be.
Anyway suggestions would be greatly appreciated, thankyou.
Edit:
Here is the code for when I am persisting the objects into the DB:
if(existingPreAux==null) {
try {
preLoad.setAuditSubLoadId(auditLoad);
em.persist(preLoad);
print("Pre Record Load entry Created");
preAux.setPreRecordLoadId(preLoad);
em.persist(preAux);
print("Pre Record Load Aux entry Created");
}
catch(ConstraintViolationException e) {
for(ConstraintViolation c : e.getConstraintViolations()) {
System.out.println (c.getPropertyPath() + " " + c.getMessage());
}
}
}
else {
try {
preLoad.setPreRecordLoadId(existingPreLoad.getPreRecordLoadId());
preLoad.setAuditSubLoadId(auditLoad);
em.merge(preLoad);
print("Pre Record Load entry found and updated");
preAux.setPreRecordLoadAuxId(existingPreAux.getPreRecordLoadAuxId());
preAux.setPreRecordLoadId(preLoad);
em.merge(preAux);
print("Pre Record Load Aux entry found and updated");
}
catch(ConstraintViolationException e) {
for(ConstraintViolation c : e.getConstraintViolations()) {
System.out.println (c.getPropertyPath() + " " + c.getMessage());
}
}
}
That's in a method, and after that code, the method ends.
It's your responsibility to maintain the coherence of the object graph. So, when you do preAux.setPreRecordLoadId(preLoad);, yo must also do preLoad.setPreRecordLoadAux(preAux);.
If you don't, then every time you'll load the preAux from the same session, it will be retrieved from the first-level cache, and will thus return your incorrectly initialized instance of the entity.

Categories