Getting a JSONException: end of input at character 0 - android

I have an API in php, that sends data in JSON format.
I made the following code, that works fine when I am on wifi.
But when I want to download the data from the API when I am on 3g, I receive the following exception:
JSONException: End of input at character 0 of
I have no idea why it does work on wifi, but it doesn't on mobile internet.
My code:
JSONObject json = getJSONfromURL("http://api.myurl.com/users.json");
JSONArray objects = json.getJSONArray("objects");
db.setLockingEnabled(false);
db.beginTransaction();
for (int i = 0; i < objects.length(); i++) {
JSONObject e = objects.getJSONObject(i);
if(e.getString("UID") != "-1"){
ContentValues values = new ContentValues();
//DO DATABASE INSERT. REMOVED THIS CODE FOR READABILITY
alldata_mProgressDialog.incrementProgressBy(1);
}
}
Anyone that can help me out?

You are probably getting a blank response. Its not null but the response is empty. So you are getting this error and not a Nullpointer exception

Check if you are asking for permissions to use the Internet.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
in the Android Manifest
Check out others at Permissions overview # https://developer.android.com.

May be you are getting default response with default values. This kind of error comes up when you are not sending your requests properly or sending with wrong parameters. Check This

Sometimes this error is caused as json encode function requires all incoming data to be UTF-8 encoded.
Try adding mysqli_set_charset($con, 'utf8'); into your php.

This kind of error comes up when response is null.Print Json respone in logcat
Log.e ( "response", "" + response ), or you can check response on postman also.

I got this error while debugging an android app on Android Studio via USB. Connection attempts failed with one tablet but not with my regular test tablet. It turned out that the failure was due to the fact that I hadn't enabled WIFI settings on the failing machine. So I enabled WIFI on it and it connected to server OK.

Related

org.json.JSONException: Unterminated object at character 18 of [] in my mobile

i checked almost all solution on this error on stackoverflow but i can't find right solution
i am fetching data from third party service it returns JSON Array
it gives org.json.JSONException: Unterminated object at character 18 of [JsonArray] in my mobile phone but it gives desired result in emulator my mobile have android 8.1
and my emulator have android 12
my code
val queue = Volley.newRequestQueue(context)
val jsonArrayobj=JsonArrayRequest(Request.Method.GET,finalurl,null,{ response->
//process on data
},{
Log.d("vollyError",it.message.toString())
// Toast.makeText(context, "Erroroccured",Toast.LENGTH_LONG).show()
})
queue.add(jsonArrayobj)
Now my app working fine I think there was an error in data which I got from api.

Realm: can't parse 110k objects on real android device

Essentially the question was in title. In detail: I am using Realm for storing
users in device storage. I am doing one request to server which returns list with 110k objects, gson parses this, all actions from out of memory were done. On emulator this operation continues for about 3 minutes and all saved to db successfully. All json data is valid, if it wasn't, on emulator it would crashed too. But, when I checked on real android device I got this
com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Expected ':' at line 2 column 3 path $[70816].info2000
when gson was trying to parse 70816 object it couldn't, because it's not valid. I re-checked this user in database. All was good. I ran again and got this exception on another object
com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Expected name at line 2 column 1091 path $[56000].accountCrm
So it's randomly.
I got confused and began researching, and I couldn't find anything. These objects come in response body(okhttp), I parse it like this:
Gson gson = GsonBase.getGlobalGson();
JsonReader reader = new JsonReader(responseBody.charStream()); //these are my 110k objects
reader.setLenient(true);
reader.beginArray();
List<ContactCRMRealm> contactCRMRBuffer = new ArrayList<>();
int counter = 0;
while (reader.hasNext()) {
if (counter < BUFFER_SIZE) {
contactCRMRBuffer.add(gson.fromJson(reader, ContactCRMRealm.class));
counter++;
} else {
defaultInstance.executeTransaction(realm1 -> realm1.insertOrUpdate(contactCRMRBuffer));
counter = 0;
contactCRMRBuffer.clear();
}
}
defaultInstance.executeTransaction(realm1 -> realm1.insertOrUpdate(contactCRMRBuffer));
contactCRMRBuffer.clear();
reader.endArray();
Exceptions are thrown in this line:
contactCRMRBuffer.add(gson.fromJson(reader, ContactCRMRealm.class));
I can't figure out but It seems like response body is being broken unexpectedly. Why It works on emulator and doesn't on android device? Few things that I can say: when I comment this line in else block:
defaultInstance.executeTransaction(realm1 -> realm1.insertOrUpdate(contactCRMRBuffer));
all parsing side was performed without exceptions. I think it's because of realm. But what exactly? I re-wrote this parsing using createOrUpdateAllFromJson() realm method:
defaultInstance.beginTransaction();
try {
defaultInstance.createOrUpdateAllFromJson(ContactCRMRealm.class, responseBody.byteStream());
defaultInstance.commitTransaction();
} catch (IOException e) {
defaultInstance.close();
} finally {
defaultInstance.close();
}
On emulator was out of memory(wtf), on real device nothing happened for 10 minutes and login exception was thrown(read timeout 10 minutes).Also I was trying to make offset, by 10 thousands users on one request, nothing changed. Please help.
Ok, after a day of investigation, the problem was solved. Realm was 2.3.0 version in the app(yes, really old), so I was thinking maybe need to upgrade to newer verison. I did it, I upgraded realm to 3.7.0(not the last one because rxjava1 is using in the app). That's it. There are a lot of improvements, especially speed improvements, so now all is fine.

Parse for Android: ParseInstallation.getCurrentInstallation().get(KEY_DEVICE_TOKEN) returns null

Parse for Android: Trying to get a device token in Parse but it keeps returning null. This code was working about 6 months back but lately have noticed this issue. Using the device token to subscribe to Parse later on. It just gets stuck in the while loop.I am using Parse 1.7.1 version. Even if I update the parse will this be the right way to get the device token?
private static final String KEY_DEVICE_TOKEN = "deviceToken";
boolean isTokenReady = false;
while (!isTokenReady) {
String deviceToken = (String) ParseInstallation.getCurrentInstallation().get(KEY_DEVICE_TOKEN);
if (!StringHelper.isNullOrEmpty(deviceToken)) {
isTokenReady = true;
} else {
sleep(1000);
}
}
ParsePush.subscribeInBackground("pushtoken_" + deviceToken);
You can use this, if you are retrieving a String:
ParseInstallation.getQuery().get(objectId).getString(KEY_DEVICE_TOKEN)
If you need to get the objectId from the default installation class:
ParseInstallation.getCurrentInstallation().getObjectId();
I'm using version 1.9.2. Hope this helps!
There's been 11 updates of the Android parse sdk. I would definitely update since there's lots of fixes.
Also, you shouldn't have to block your thread to wait for the device token. Did you forgot to save the installation before trying to get the deviceToken?
Like this:
ParseInstallation.getCurrentInstallation().save();
String deviceToken = (String) ParseInstallation.getCurrentInstallation().get( "deviceToken" );
Lastly, Im not sure why you would use a unique device token as push channels. You can use the deviceToken directly. So I would suggest not to subscribe to any channels and push notifications to selected devices using their deviceTokens.
I spent a lot of time on this problem too...
getInstallationId() seems to work. I use installationId to query installations and now it works OK

Nest ETA update not working: No write permission(s) for field(s): eta

I'm building an Application that integrates with your Nest devices (both the thermostat and the Nest Protect, but this issue is about the thermostat).
What I'm trying to do is set my thermostat's ETA to be in x minutes (2 hours for example so 120 minutes).
This is my code that I'm executing:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ");
final String path = buildStructureFieldPath(structureID, Keys.STRUCTURE.ETA);
Structure.ETA eta = new Structure.ETA.Builder()
.setTripID(tripId)
.setEstimatedArrivalWindowBegin(sdf.format(estimatedArrivalBegin))
.setEstimatedArrivalWindowEnd(sdf.format(estimatedArrivalEnd))
.build();
sendRequest(path, eta.toJSON().toString(), listener);
The path is /structures/MY_STRUCTURE_ID/eta
Unfortunately that's not working. I'm always getting an error code -2 and error message: No write permission(s) for field(s): eta
And that's were it gets strange. No permission, but I did request the permission and I did an authenticate, which is successful, before launching the update call.
In the two attached screenshots you can see first my Nest Developer Account where you can find the ETA write permission and in the second you can see the logging from within my app (using the NestAPI as can be found on GitHub, just added the ETA feature myself).
Anyone have any idea on how to solve this issue?
Can you print out the exact JSON blob you're sending and post it here? (the value of eta.toJSON().toString())
Best guess is that it isn't formatted exactly correctly and as such is maybe attempting to write in such a way that doesn't adhere to the api-reference.
This is the format that it needs to match:
"eta": {
"trip_id": "myTripHome1024" ,
"estimated_arrival_window_begin": "2015-10-31T22:42:59.000Z" ,
"estimated_arrival_window_end": "2015-10-31T23:59:59.000Z"
}
Single line:
{"eta":{"trip_id":"myTripHome1024","estimated_arrival_window_begin":"2015-10-31T22:42:59.000Z","estimated_arrival_window_end": "2015-10-31T23:59:59.000Z"}}
To pinpoint exactly which field may be erroneous, try sending just one change at a time for each ie: structures/ID/eta/trip_id, etc for the others.
Useful JSON Validator: http://jsonlint.com/
You could also try to send it to /structures/MY_STRUCTURE_ID.json?auth=[TOKEN] instead of /structures/MY_STRUCTURE_ID/eta.

Get request error in resting framework

I am creating an android client which connects to the web service and gets a response code. The problem is the android app crashes whenever I run the following code:
RequestParams params = new BasicRequestParams();
params.add("client_id", "24f8b46fc9db409012830ca264ad7bcf");
params.add("response_type", "code");
ServiceResponse response=Resting.get("http://pricewatch.ap01.aws.af.cm/api/pricewatch/oAuth/auth",80,params);
IContentData contentData = response.getContentData();
String content = (String) contentData.getContent();
JSONObject jsonObject = new JSONObject(content);
String code = (String) jsonObject.get("code");
return code;
It generates a java.lang.NullPointerException with these line:
IContentData contentData = response.getContentData();
Could someone help with these? I've been stuck with these. Thanks in advance!
I run this code many times in the emulator but never worked. However, when I run this in an android device it worked! NullPointerException happens when it doesn't get anything or any response in the server. But what I don't understand is why does this happen? Is there a difference between an emulator and an android device in terms of executing an android application?

Categories

Resources