Reputation: 2278
I have an android app which does some network process in the background, requesting information from json api at https://ipinfo.io/json. The bufferReader httpConnection
is successfully made, and BufferReader
contains the information which I later add into output String (while loop).
Now when converting into the json object..
String INTERNET_IP_SOURCE = "https://ipinfo.io/json"
is declare globally. I'm getting exception about malformed json object. What am I missing here? Thanks!
private class TaskPublicNet extends AsyncTask<Void, String, Void> {
String output = "";
int progress = 0;
String json = "";
//only 7 lines of information for public ip info (set progress at 5)
final static int PROGRESS_MAX = 5;
String[] iface;
@Override
protected void onPreExecute() {
progressBar.setMax(PROGRESS_MAX);
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(1);
}
@Override
protected void onPostExecute(Void aVoid) {
progressBar.setProgress(5);
Log.v("ALL ", localIfaceInfo.toString());
}
@Override
protected void onProgressUpdate(String... values) {
Log.v("PROGRESS ", values[0]);
localIfaceInfo.add(values[0]);
localNetAdapter.notifyDataSetInvalidated();
}
@Override
protected Void doInBackground(Void... params) {
/** Getting public interface information*/
try {
// Make a URL to the web page
URL url = new URL(INTERNET_IP_SOURCE);
// Get the input stream through URL Connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
// read each line and write to System.out
while ((line = bf.readLine()) != null) {
Log.v("LINE ", line);
output += line;
}
bf.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
//json parsing
try {
JSONArray ja = new JSONArray(output);
JSONObject jo = (JSONObject) ja.get(0);
String publicIp = jo.get("ip").toString();
String city = jo.get("city").toString();
String provider = jo.get("org").toString();
Log.v("PUBLIC ", publicIp +" "+city+" "+provider);
publishProgress("Public Ip: "+publicIp);
publishProgress("City: "+city);
publishProgress("Provider: "+provider);
}
catch (JSONException ex){
ex.printStackTrace();
}
return null;
}
}
Upvotes: 0
Views: 1155
Reputation: 13435
the response looks like this
{
"ip": "XXXXXX",
"city": "",
"region": "",
"country": "XX",
"loc": "XXXXX,XXXXX",
"org": "XXXXXXXX"
}
but in your code you are doing this
JSONArray ja = new JSONArray(output);
JSONObject jo = (JSONObject) ja.get(0);
The json is an object is not an array. Try parsing it directly into an object
JSONObject jo = new JSONObject(output)
Upvotes: 3