Android JSONObject getString method check for null/NULL? - android

Hitting a brick wall in my code at the moment for fetching json objects from multiple pages(using a loop) in a AsyncTask. It reaches the last page, but getting the correct if statement to ensure that the loop DOESN'T run again and continues on is baffling me.
String data = //some correct json data with next element that holds a uri parseable string
JSONObject initial = new JSONObject(data);
String next = initial.getString(nextObjSTR);
//gonna start from the "last" page and recursively return to the 1st page
if(*The if condition I need help with*) {
//there is another page
makeConnection(Uri.parse(next));
}
Basically, the last page of json elements has a next element with a null or no element value, which triggers the IOException error caught in makeConnection method because my initial if statement has always been failing.
Can I get a reason or help as to the appropriate if check for Strings from json? I've tried String != null as NullPointerExceptions occur if I use any method from String to compare. Likewise, JsonObject.NULL comparison doesn't work for me either.

None of the other answers worked, and I ended up questioning whether the element was really null despite looking at the parsed json data via an online tool. In the end, JSONObject.IsNull(element mapping name) is the right approach.

If you're sure that the value is either null (empty) or a correct URI, and assuming that the nextObjSTR key is always present in the data JSON, then that will do:
if (next != null && !next.trim().isEmpty()) {
makeConnection(Uri.parse(next));
}
Or, since you're on Android, it's better use the more convenient method:
if (!TextUtils.isEmpty(next)) {
makeConnection(Uri.parse(next));
}

You can use the optString Method of the JSONObject. If the JSON key is not this method will return a empty string, so you can check it easily:
String next = initial.optString(nextObjSTR);
if ( ! next.isEmpty() ) {
makeConnection(Uri.parse(next));
}
Source: https://developer.android.com/reference/org/json/JSONObject.html#optString(java.lang.String)

you must check value with key is has in json object.
Try below code:
JSONObject initial = new JSONObject(data);
if(initial.has(nextObjSTR)) {
String next = initial.getString(nextObjSTR);
if (next != null && !next.isEmpty()) {
makeConnection(Uri.parse(next));
}
}

I do like this...
String value;
if(jsonObject.get("name").toString.equals("null")){
value = "";
else{
value = jsonObject.getString("name");
}

Related

multiple check or,and in if statement

hi i'm wonder why my if always Toast me : "names Successfully saved!"
i'm try every thing.
public void btnSave_Clicked(View view) {
TextView txtOname = (TextView)findViewById(R.id.txtOname);
TextView txtXname = (TextView)findViewById(R.id.txtXname);
String X = txtXname.getText().toString();
String O = txtOname.getText().toString();
if((X!="") && (O!="")){
DatabaseHelper.insertName(getBaseContext(),((TextView)findViewById(R.id.txtOname))
.getText().toString());
DatabaseHelper.insertName(getBaseContext(),((TextView)findViewById(R.id.txtXname))
.getText().toString());
Toast.makeText(this,"names Successfully saved!",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this,"E",Toast.LENGTH_SHORT).show();
}
}
}
Strings are reference types in Java, and thus the reference of a dynamically created empty string will be different from your variables. Another option to isEmpty is equals.
if (!x.equals("") && !o.equals(")) {
//code
}
Though I'd probably go with isEmpty
Replace your if statement with:
if (!x.isEmpty() && !o.isEmpty()) {
//code
}
operator == compares Object reference.
.equals() compares String value.
.isEmpty() return true if String length is 0.
Strings are objects. Object instances (the value behind them) have to be compared manually with a method to assure that the content is the same.
The == operator just compares the string references ("adresses"). So when you create 2 object instances at runtime, they have different adresses even if the content is the same. Compile-time strings on the other hand are internalized, they are put into special memory and duplicates are sorted out.
System.out.println(new String("test") == new String("test"));
This will print false, because those 2 objects get created at runtime. The new keyword in the first example mandates that a new object with a new adress is created.
System.out.println("test" == "test");
This will print true, because they are String literals, which are known at runtime, you are not explicitly stating the new keyword here either. You are simply specifying that you want those literals represented in the code somehow, so the compiler internalizes them.

How can I get the value in android sugar, I'm only getting the object reference

I'm using for first time sugar and all seems that work fine. I can save the data and seems that I'm getting the data when I try to do a find. My problem is that I'm getting the object and not the value that I have store and I'm not really sure why, because I'm doing the same that I can see in the official documentation
This is that I'm doing to get the data:
Select name= Select.from(MyClass.class).where(Condition.prop("name").lt("Bob"));
String data = name.toString();
Log.e("aaaaa", data.toString());
This is that I'm gettin in the log:
com.orm.query.Select#3ce7ff7b
With that Select statement, you are querying for the MyClass object by name, and that returns you a Select object.
To get the name from it you should fetch results from the Select (here I do it with .first()) and put that in a MyClass object. Then you can get the name from that.
MyClass myClass = Select.from(MyClass.class)
.where(Condition.prop("name").lt("Bob"))
.first();
String name = myClass.getName();
provided your MyClass has a method getName()
I'm doing the same that I can see in the official documentation
I don't thnk you are.
In the documentation here, it shows this piece of code:
Select.from(TestRecord.class)
.where(Condition.prop("test").eq("satya"),
Condition.prop("prop").eq(2))
.list();
When you compare it with your code, you see that you missed the call to list.
If you don't call list, the where method will return a Select object. And that's all you get.
list will return all of the results that the query has found. So the correct way to do this would be:
List<MyClass> results =
Select.from(MyClass.class).
where(Condition.prop("name").
lt("Bob")).list();
for (MyClass obj: results) {
Log.i("aaaa", obj.toString());
// or you can write
// Log.i("aaaa", obj.name);
}
The above would print all the results. If you only need the first result, you can call results.get(0).

Android Parse finding a result using a Pointer Id

I'm trying to get a query using as condition the Pointer Id of the object, for example I'm saving all the id's of an object in an array, then I want to get from another class (related by pointer), all the objects that uses that Id, so I already have this:
for (i = 0; i < num; i++) {
//restaurant.setObjectId(restId[i]);
ParseQuery<ParseObject> resultsitems = ParseQuery.getQuery("Item").whereEqualTo ("restaurant", restId[i]);
try {
objects=resultsitems.find();
} catch (ParseException e) {
e.printStackTrace();
}
(.......)
}
In my first try I tried to set the id into the restaurant object, then tried to use the query as:
ParseQuery<ParseObject> resultsitems = ParseQuery.getQuery("Item").whereEqualTo ("restaurant",restaurant );
But it didn't work, then I tried to search as shown in the code above, it doesn't crash but brings me nothing, how can I do this?
This is what really worked for me:
ParseObject obj = ParseObject.creatWithoutData("classNameThatPointedTo","fieldValue");
query.whereEqualTo("fieldName", obj);
Use: .findInBackground(new FindCallBack<Item>... (this will auto-complete in Android Studio), then put objects=resultsitems.find(); in the curly braces of the done() function.
The callback waits for the query to return before moving on with the script. Otherwise, the main thread will keep moving on without waiting for the data to come back from the server.

android - jackson get null fields value as empty string

My JSON stream can be different each time. For example sometime it can include a "Song" field and sometime not.
I am getting this fields value asText ? How to tell Jackson to get this value as an Empty String if it is not defined ?
Example
"Content": "MusicContent",
"Song": "Track_1",
if try node.get("Song").asText() it will give "Track_1"
"Content": "MusicContent",
Now , if i try to get node.get("Song") it gives null pointer exception. I want to get an empty string when calling asText().
How can i do that ?
Thanks
You could check for null before calling the asText() on the node. i would probably do it like this :
if (node.get("Song") != null){
myString = node.get("Song").asText();
} else {
myString = "";
}
Or in a fancy way like this :
myString = ((node.get("Song")!=null) ? node.get("Song").asText() : "");

how to check whether jsonobject contains boolean or null value?

I am working on json parser. In json response some values contains boolean or null values, then how to check whether it is boolean or null? For example : user = false or user = null . At the time of parsing it gives exception as "user is not jsonobject".
JSONObject json = new JSONObject(query);
JSONObject info = json.getJSONObject("info");
JSONObject user = info.getJSONObject("user");
Thanks,
Vishakha.
Have you tried ingo.optBoolean("user")?
From the SDK documentation for optBoolean:
Returns the value mapped by name if it exists and is a boolean or can be coerced to a boolean. Returns false otherwise.
Note that null will be treated as a false value in this example.
isNull() you can use if(json.isNull("user")||your conditions)
I think the problem might be that you are trying to get a JSONArray with getJSONObject(). try json.getJSONArray("info"). I had the same problem that i was trying to do if(object.getJSONObject("string") == null) but it threw an exception when trying to get the object to check for its value, and .optBoolean worked perfectly
JSONObject json = new JSONObject(data);
String user = json.getString("user");
variable.setUser(courses_icon_file_name == null ? "": user);

Categories

Resources