How to get data from a parse object? - java

I have a class in parse.com called Messages. I have created a column called sent of type string which stores the object-id of the user to whom the message has to be sent.
In my android app I want to retrieve the messages of the current user.
But my app does not show any messages.
This is how I'm implementing it-
public void done(List<ParseObject> postList, ParseException e) {
setProgressBarIndeterminateVisibility(false);
if (e == null) {
// If there are results, update the list of posts
// and notify the adapter
posts.clear(); //posts is a list of <TextMessage>
//TextMessage is a class which holds the details of Messages (parse object)
for (ParseObject msg : postList) {
if(msg.getParseUser("sent")==ParseUser.getCurrentUser())
{
TextMessage note = new TextMessage(msg.getObjectId());
posts.add(note);
}
}
((ArrayAdapter<TextMessage>) getListAdapter()).notifyDataSetChanged();
}
I can't understand why the if conditions are not being implemented, what am I doing wrong.
How else can I retrieve the string in the sent column?
Feel free to ask for any more information required.

I am not android expert but I think your issue is :
If you care comparing two strings, you must use equals() not ==
Change == to equals() everything works
Note: == checks the reference to the object are equal .
Note: equals() This method compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object
read about equals()

Related

Get a string list of values from a generic object

So I have an Object that comes in that can be any of 100 different specific objects, with different elements inside it, from other objects, lists, sequences, primitives etc.
I want to strip the values in a depth first fashion to make a string of simple values with a delimiter between them. I have mapped the fields and stored them elsewhere using recursion/reflection that only happens once a new Object type comes in for the first time.
An example of how I'm storing the data in the database for a few simple example objects:
Object A layout table: Timestamp = 12345 Fields = Length|Width|Depth
Object B layout table: Timestamp = 12345 Fields = Height|Weight|Name
Object A layout table: Timestamp = 12350 Fields = Length|Width|Depth|Label
Object A sample: Timestamp = 12348 Values = 5|7|2
Object A sample: Timestamp = 12349 Values = 4|3|1
Object B sample: Timestamp = 12346 Values = 75|185|Steve Irwin
Object A sample: Timestamp = 12352 Values = 7|2|8|HelloWorld
Below is my current solution. I'm seeking improvements or alternatives to the design to accomplish the goal stated above.
Currently I get the object in and translate it to JSON using gson.toJson(); From that, I cycle through the JSON to get values using the code below. Issue is, this code is very CPU intensive on the low end CPU I am developing for due to the fact that there are many samples coming in per second. Overall purpose of the application is a data recorder that records real time samples into a SQLite database. I have also attempted to store the unmodified JSON into a SQLite BLOB column, but this is terribly inefficient with regards to DB size. Is there a better/more efficient method for getting values out of an object?
I don't have an issue storing the field mapping since it only needs to be done once, but the value stripping needs to be done for every sample. I know you can do it via reflection as well, but that is also processing heavy. Anyone have a better method?
public static List<String> stripValuesFromJson(JsonElement json)
{
// Static array list that will have the values added to it. This will
// be the return object
List<String> dataList = new ArrayList<String>();
// Iterate through the JSONElement and start parsing out values
for (Entry<String, JsonElement> entry : ((JsonObject) json).entrySet())
{
// Call the recursive processor that will parse out items based on their individual type: primitive, array, seq etc
dataList.addAll(dataParser(entry.getValue()));
}
return dataList;
}
/**
* The actual data processor that parses out individual values and deals with every possible type of data that can come in.
*
* #param json - The json object being recursed through
* #return - return the list of values
*/
public static List<String> dataParser(JsonElement json)
{
List<String> dataList = new ArrayList<String>();
// Deal with primitives
if (json instanceof JsonPrimitive)
{
// Deal with items that come up as true/false.
if (json.getAsString().equals("false"))
{
dataList.add("0");
} else if (json.getAsString().equals("true"))
{
dataList.add("1");
} else
{
dataList.add(json.getAsString());
}
// Send through recursion to get the primitives or objects out of this object
} else if (json instanceof JsonObject)
{
dataList.addAll(stripValuesFromJson(json));
} else if (json instanceof JsonArray)
{
// Send through recursion for each element in this array/sequence
for (JsonElement a : (JsonArray) json)
{
dataList.addAll(dataParser(a));
}
} else if (json instanceof JsonNull)
{
dataList.add(null);
} else
{
errorLog.error("Unknown JSON type: " + json.getClass());
}
return dataList;
}
One thing you could try out is writing your own JSON parser which simply emits values. I have more experience in JavaCC so I'd take one of existing JSON grammars and modify it so that it only outputs values. This should not be too complicated.
Take for example the booleanValue production from the mentioned grammar:
Boolean booleanValue(): {
Boolean b;
}{
(
(
<TRUE>
{ b = Boolean.TRUE; }
) | (
<FALSE>
{ b = Boolean.FALSE; }
)
)
{ return b; }
}
Basically you will need to replace returning the boolean value with appending "1" or "0" to the target list.
ANTLR is another option.

Checking if Parse.com class is (undefined)

I'm trying to catch an exception. I thought that checking whether the String is empty would help, but it doesn't seem to work. The value in the actual column for the object in my class is "(undefined)". It seems to be that by default. How can I explicitly check to see if it is undefined?
notifications.getString(ParseConstants.KEY_FEED_TYPE).isEmpty()
Heads up. The following doesn't work either:
notifications.getString(ParseConstants.KEY_FEED_TYPE).equals("(undefined)");
it's checking using Android default function like
if (!TextUtils.isEmpty(notifications.get(ParseConstants.KEY_FEED_TYPE))) {
// its not null value success
} else {
// here getting to null value Fail
}
I did the following. Instead of looking for a String (in which case the field entry would be truly empty, and not (undefined)), I checked to see if the object was null after dropping the String from getString.
if (notifications.get(ParseConstants.KEY_FEED_TYPE) != null) {
// Do something.
} else {
// Do something else.
}

s ParseUser.CurrentUser() different on Parses servers from Client Side

While working with objects, I am trying to compare one field of a queried object to the current user using the app
I was using an IF loop
if( ParseUser.CurrentUser() == object.getString("User"))
{
Do this
}
However, ParseUser.CurrentUser does not return in string format. So I declared a varible and tried that
String parseUser = ParseUser.CurrentUser.toString();
However, the string contains a completely different value then what the parse user for that particular user is called on the Parse server. Does something different happen on the server? Is there a correct way to return the ParseUser.CurrentUser in a string form?
ParseUser.getCurrentUser() returns a ParseUser Object, not a String. So what you want to do is compare the ObjectId of the current user object to your user String.
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser != null && currentUser.getObjectId().equals(object.getString("User")){
//do stuff
}
Hope that helps..

Finding and showing element in arraylist

Is there any easy way to search through an arraylist?
i see there are many things to do with collections like removeAll() and add() is there anything like this for searching through the list
Add a method to your UserArchive class that loops through the list and compares each user id to the one passed in.
public User findById(int id) {
for (User u : list) {
if (u.getCustomerID() == id) {
return u;
}
}
return null; // or empty User
}
You have the option of do a if in your loop and look the id for each instance of User in the loop:
for (User user : list) {
if (user.getCustomerID == [The id to lookup]) {
// Whatever you want to do
}
}
Or you could override the equals() method for your User class and unlock the
List.contains function if you compare another instance of User instead of the CustomerID.
The equals' functions header say:
Returns true if this list contains the specified element. More
formally, returns true if and only if this list contains at least one
element e such that (o==null ? e==null : o.equals(e)).
This is why you got to override equals for you object. A lot of functions use equals() for object and if you care the result to be good, you have to override the function.
// Or whatever instance of User you want to compare
User custToLookup = new User(idToLookup, "", "", "");
// You could stop here if you only want to know if the instance exist in the list
if (list.contains(custToLookup)){
for (User user : list) {
if (user.equals(custToLookup) {
// Whatever you want to do
}
}
}
*Edit : Forgot some words

How to check if List<obj> is null?

I have a list that takes a list from my server. this list will hold whatever the server finds at the database ex.
List<OBJ> lstObj = new Arraylist<OBJ>;
Service.getOBJ(new AsyncCallback<List<OBJ>>(){
#Override
public void onFailure(Throwable caught) {
caught.printStackTrace();
}
#Override
public void onSuccess(List<OBJ> result) {
//line to check if result is null
}
});
I have tried
if(result==null){
}
and also tried
if(result.isempty(){
}
but it didnt work. the list will be null if the server doesnt find any record from the database. all i need to do is check if the list is empty.
Checking if the list is empty and checking if result is null are very different things.
if (result == null)
will see if the value of result is a null reference, i.e. it doesn't refer to any list.
if (result.isEmpty())
will see if the value of result is a reference to an empty list... the list exists, it just doesn't have any elements.
And of course, in cases where you don't know if result could be null or empty, just use:
if (result == null || result.isEmpty())
Check number of elements in resulting List:
if (0==result.size()) {
// Your code
}
You will do like this:
if (test != null && !test.isEmpty()) { }
This will check for both null and empty, meaning if it is not null and not empty do your processing.
You're obviously new at this programming thing if you didn't already validate your server, so I'm trying to aim a guess at what might be going on with your server. Depending on what your "" objects are, you could have valid objects that represent data that is meaningless in different ways. For example, you may have String objects with various kinds of white space.
This happens a lot on servers that provide answers using PHP and JSP, where pages are assembled using various include mechanisms and there is white space between them.
The below should do for your code. If you want a negation logic just modify accordingly.
As also suggested by someone CollectionUtils provide just utility methods which removes such null check LOC.
result == null || result.isEmpty()
Hope this helps!

Categories

Resources