I'm trying to take the JSON from BITTREX and parse it and present it to the screen in Android Studio. This works for me with test JSON I made myself plus other requests i have made using the same API. However, when i go to use the actual request I need i get the following error :
JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONArray
This is the request used: https://bittrex.com/api/v1.1/public/getmarketsummaries
API Documentation
Here is the Code :
public class fetchData extends AsyncTask<Void,Void,Void> {
String data=""; //all json lines after loop
String dataParsed ="";
String singleParsed =""; //parsed attributes
#Override
protected Void doInBackground(Void... voids) {
//Background Thread i.e API request
try {
URL url = new URL("https://bittrex.com/api/v1.1/public/getmarketsummaries\n");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream(); //read data in from the connection
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); //Buff reader to read the inputstream (otherwise we get ints)
String line ="";
//Loop that reads all lines and represents them to as a string
while(line != null) {
line = bufferedReader.readLine(); //read line of json and assign to "line" if not null
data = data + line;
}
JSONArray myJsonArray = new JSONArray(data); //store json in a json array
for (int i = 0; i < myJsonArray.length(); i++) {
//Itterate through the array and get each object i.e btc,ltc
JSONObject myJsonObject = (JSONObject) myJsonArray.get(i);
//Single JSON object parsed
singleParsed = "Coin" + myJsonObject.get("MarketName") + "\n" +
"high" + myJsonObject.get("High") + "\n" +
"low" + myJsonObject.get("Low") + "\n" +
"volume" + myJsonObject.get("Volume") + "\n" +
"last" + myJsonObject.get("Last") + "\n" +
"basevolume" + myJsonObject.get("BaseVolume") + "\n" +
"time" + myJsonObject.get("Timestamp") + "\n" +
"bid" + myJsonObject.get("Bid") + "\n" +
"ask" + myJsonObject.get("Ask") + "\n" +
"openbuyorders" + myJsonObject.get("OpenBuyOrders") + "\n" +
"opensellorders" + myJsonObject.get("OpenSellOrders") + "\n" +
"prevday" + myJsonObject.get("PrevDay") + "\n" +
"created" + myJsonObject.get("Created") + "\n";
dataParsed = dataParsed + singleParsed + "\n";
}
}catch(MalformedURLException e ){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//UI thread
MainActivity.data.setText(this.dataParsed);
}
}
Any thoughts would be greatly appreciated. Thanks :)
**UPDATE - SOLVED **
I added the following line before the loop and it solved the issue.
//target the "result" Array of objects(BTC,LTC,ETH) and map them to a JsonArray for parsing
JSONArray myJsonArray = myJsonObj.getJSONArray("result");
The exception is perfectly valid. Your trying to convert json object into json array. Try below code
remove "\n" character at the end.
URL url = new URL("https://bittrex.com/api/v1.1/public/getmarketsummaries\n")
add below logs
while(line != null) {
line = bufferedReader.readLine(); //read line of json and assign to "line" if not null
data = data + line;
}
Log.debug("api_response","api-response->"+data);
and try below code
if(data!= null){ // add this if condition too.
JSONObject jsonObj = new JSONObject(data);
JSONArray myJsonArray = jsonObj.getJSONArray("result"); ; //store json in a json array
for (int i = 0; i < myJsonArray.length(); i++) {
//Itterate through the array and get each object i.e btc,ltc
JSONObject myJsonObject = (JSONObject) myJsonArray.get(i);
The json data returned by the API is in the following format:
{
"success": true,
"message": "",
"result": [
{
},
{
}
]
}
So you need to get the whole data as JSONObject first, then from it you can extract the JSONArray with the "result" key.
The code is something like this:
// get the JSONObject from the data
JSONObject jsonObject = new JSONObject(data);
// then you get the array with result key
JSONArray myJsonArray = jsonObject.getJSONArray("result");
for (int i = 0; i < myJsonArray.length(); i++) {
// now you can process the item here.
}
UPDATE
The above code is working. The remaining problem is there is a typo in your key. You're using "Timestamp" but the existing key is "TimeStamp". Here is the working code:
public class FetchData extends AsyncTask<Void,Void,Void> {
String data=""; //all json lines after loop
String dataParsed ="";
String singleParsed =""; //parsed attributes
#Override
protected Void doInBackground(Void... voids) {
//Background Thread i.e API request
try {
URL url = new URL("https://bittrex.com/api/v1.1/public/getmarketsummaries");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream(); //read data in from the connection
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); //Buff reader to read the inputstream (otherwise we get ints)
String line ="";
//Loop that reads all lines and represents them to as a string
while(line != null) {
line = bufferedReader.readLine(); //read line of json and assign to "line" if not null
data = data + line;
Log.d("DATA", "line = " + line);
}
Log.d("DATA", "construct data = " + data);
JSONObject jsonObject = new JSONObject(data);
JSONArray myJsonArray = jsonObject.getJSONArray("result");
for (int i = 0; i < myJsonArray.length(); i++) {
//Itterate through the array and get each object i.e btc,ltc
JSONObject myJsonObject = (JSONObject) myJsonArray.get(i);
//Single JSON object parsed
singleParsed = "Coin" + myJsonObject.get("MarketName") + "\n" +
"high" + myJsonObject.get("High") + "\n" +
"low" + myJsonObject.get("Low") + "\n" +
"volume" + myJsonObject.get("Volume") + "\n" +
"last" + myJsonObject.get("Last") + "\n" +
"basevolume" + myJsonObject.get("BaseVolume") + "\n" +
"time" + myJsonObject.get("TimeStamp") + "\n" +
"bid" + myJsonObject.get("Bid") + "\n" +
"ask" + myJsonObject.get("Ask") + "\n" +
"openbuyorders" + myJsonObject.get("OpenBuyOrders") + "\n" +
"opensellorders" + myJsonObject.get("OpenSellOrders") + "\n" +
"prevday" + myJsonObject.get("PrevDay") + "\n" +
"created" + myJsonObject.get("Created") + "\n";
dataParsed = dataParsed + singleParsed + "\n";
}
}catch(MalformedURLException e ){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//UI thread
//MainActivity.data.setText(this.dataParsed);
Log.d("DATA", "data = " + this.dataParsed);
}
}
Here's my code
public static ArrayList<KeyValue> peticionRest(final ArrayList<KeyValue> parametros, final String funcionAPI, final String metodo){
ArrayList<KeyValue> respuesta = new ArrayList<>();
try {
respuesta.clear();
String urlParametros = URLEncoder.encode(parametros.get(0).getKey(), "utf-8")+"="+URLEncoder.encode(parametros.get(0).getValue(), "utf-8");
for (int x = 1; x < parametros.size(); x++){
urlParametros += "&"+URLEncoder.encode(parametros.get(x).getKey(), "utf-8")+"="+URLEncoder.encode(parametros.get(x).getValue(), "utf-8");
}
String stringURL = "url to site";
URL url = new URL(stringURL);
HttpURLConnection myConnection = (HttpURLConnection) url.openConnection();
myConnection.setInstanceFollowRedirects(false);
if (metodo.equals("post")){
myConnection.setDoOutput(true);
}
for (int x = 0; x < parametros.size(); x++){
myConnection.setRequestProperty(parametros.get(x).getKey(), parametros.get(x).getValue());
}
if (myConnection.getResponseCode() == 200) {
InputStream responseBody = myConnection.getInputStream();
InputStreamReader responseBodyReader = new InputStreamReader(responseBody, "UTF-8");
JsonReader jsonReader = new JsonReader(responseBodyReader);
jsonReader.setLenient(true);
jsonReader.beginObject(); // Start processi ng the JSON object
while (jsonReader.hasNext()) { // Loop through all keys
String key = jsonReader.nextName(); // Fetch the next key
String value = jsonReader.nextString();
respuesta.add(new KeyValue(key, value));
}
jsonReader.close();
} else {
respuesta.add(new KeyValue("ok", "false"));
respuesta.add(new KeyValue("error", "error en la peticion"));
}
myConnection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return respuesta;
}
I get a "java.lang.IndexOutOfBoundsException: Index: 0, Size: 0" because respuesta is empty.
If i log the url and click it, it works fine.
The program stops when it reaches myConnection.getResponseCode()
Any ideas?
Thanks in advance!
You problem is
"java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
There are two List in your code .So it may cause in it .
In your code .
String urlParametros = URLEncoder.encode(parametros.get(0).getKey(), "utf-8")+"="+URLEncoder.encode(parametros.get(0).getValue(), "utf-8");
You use parametros.get(0).getKey() .It may be the problem .
Try this.
Before call parametros in your code .
if(parametros != null && parametros.size() > 0){
// you can do something here
String urlParametros = URLEncoder.encode(parametros.get(0).getKey(), "utf-8")+"="+URLEncoder.encode(parametros.get(0).getValue(), "utf-8");
}
i try to get multiple table from json, i have two tables ( hotline and other ) , i can get data from hotline table, but cannot get from other table
in my php (json):
{"hotline":[{"id":"2","name_hotline":"Tourist Police","phone_hotline":"192"},{"id":"6","name_hotline":"Water","phone_hotline":"1199"}]}{"other":[{"id":"1","name_other":"Lao National Tourism Administration","phone_other":"+85621212248 ","latitude_other":"0","pic_other":"","longtitude_other":"0"},{"id":"2","name_other":"Tourism Police Department","phone_other":"+85621251128 ","latitude_other":"0","pic_other":"","longtitude_other":"0"}]}
MainActivity.java :
InputStream objInputStream = null;
String strJSON = "";
try {
HttpClient objHttpClient = new DefaultHttpClient();
HttpPost objHttpPost = new HttpPost("http://192.168.1.102/emergencycall/php_get_data.php");
HttpResponse objHttpResponse = objHttpClient.execute(objHttpPost);
HttpEntity objHttpEntity = objHttpResponse.getEntity();
objInputStream = objHttpEntity.getContent();
Log.d("Emergency", "Connected HTTP Success !");
} catch (Exception e) {
Log.d("Emergency", "Error Connect to : " + e.toString());
}
try {
BufferedReader objBufferesReader = new BufferedReader(new InputStreamReader(objInputStream, "UTF-8"));
StringBuilder objStrBuilder = new StringBuilder();
String strLine = null;
while ((strLine = objBufferesReader.readLine()) != null) {
objStrBuilder.append(strLine);
}
objInputStream.close();
strJSON = objStrBuilder.toString();
Log.d("Emergency", "Connected JSON Success !");
} catch (Exception e) {
Log.d("Emergency","Error Convert To JSON :" + e.toString() );
}
try {
JSONObject object = new JSONObject(strJSON);
JSONArray objJSONArray = object.getJSONArray("hotline");
JSONArray objJSONAraay2 = object.getJSONArray("other");
for (int i = 0; i < objJSONArray.length(); i++) {
JSONObject objJSONObject = objJSONArray.getJSONObject(i);
strNameHotlineMySQL = objJSONObject.getString("name_hotline");
strPhoneHotlineMySQL = objJSONObject.getString("phone_hotline");
}
for (int j = 0; j < objJSONAraay2.length(); j++) {
JSONObject objJSONObject1 = objJSONAraay2.getJSONObject(j);
strNameHospitalMySQL = objJSONObject1.getString("name_other");
strPhoneHospitalMySQL = objJSONObject1.getString("phone_other");
long insertID4 = objHotlineTable.addDataFromSQLiteHospital(strNameHospitalMySQL, strPhoneHospitalMySQL, strPicHospitalMySQL);
}
} catch (Exception e) {
Log.d("Emergency","Error syncdata to SQLite :" + e.toString() );
}
and i get an error in Logcat:
: Error syncdata to SQLite :org.json.JSONException: No value for other
Your json data format is not correct. Json data format should be like this:
{
"hotline":[
{
"id":"2",
"name_hotline":"Tourist Police",
"phone_hotline":"192"
},
{
"id":"6",
"name_hotline":"Water",
"phone_hotline":"1199"
}
],
"other":[
{
"id":"1",
"name_other":"Lao National Tourism Administration",
"phone_other":"+85621212248 ",
"latitude_other":"0",
"pic_other":"",
"longtitude_other":"0"
},
{
"id":"2",
"name_other":"Tourism Police Department",
"phone_other":"+85621251128 ",
"latitude_other":"0",
"pic_other":"",
"longtitude_other":"0"
}
]
}
And than,
You can use "Retrofit" and "gson" for http request and object mapping.
I've been trying to use the Forecast.io API and the JAR that was provided by their website for my application. But when making web API calls it looks like the data that is being returned by the site isn't fully downloaded.
I try it print the data and it appears that it is not all the information.
I'm using this code:
HttpClient client = new DefaultHttpClient();
URI website = new URI(requestURL);
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
scanner = new BufferedReader(new inputStreamReader(response.getEntity()
.getContent()));
String availalbe;
while ((availalbe = scanner.readLine()) != null) {
res += availalbe;
}
Data that is printed out (it stops partway through what is expected):
{"latitude":51.7589177,"longitude":-0.2342903,"timezone":"Europe/London","offset":1,"currently":{"time":1370612854,"summary":"Partly Cloudy","icon":"partly-cloudy-day","precipIntensity":0,"temperature":20.65,"dewPoint":10.56,"windSpeed":9.92,"windBearing":59,"cloudCover":0.34,"humidity":0.5,"pressure":1023.91,"visibility":10.75,"ozone":356.06},"minutely":{"summary":"Light rain in 30 min.","icon":"rain","data":[{"time":1370612820,"precipIntensity":0},{"time":1370612880,"precipIntensity":0},{"time":1370612940,"precipIntensity":0},{"time":1370613000,"precipIntensity":0},{"time":1370613060,"precipIntensity":0},{"time":1370613120,"precipIntensity":0},{"time":1370613180,"precipIntensity":0},{"time":1370613240,"precipIntensity":0},{"time":1370613300,"precipIntensity":0},{"time":1370613360,"precipIntensity":0},{"time":1370613420,"precipIntensity":0},{"time":1370613480,"precipIntensity":0},{"time":1370613540,"precipIntensity":0},{"time":1370613600,"precipIntensity":0},{"time":1370613660,"precipIntensity":0.107,"precipIntensityError":0.055,"precipProbability":0.01,"precipType":"rain"},{"time":1370613720,"precipIntensity":0.111,"precipIntensityError":0.057,"precipProbability":0.01,"precipType":"rain"},{"time":1370613780,"precipIntensity":0.132,"precipIntensityError":0.065,"precipProbability":0.01,"precipType":"rain"},{"time":1370613840,"precipIntensity":0.137,"precipIntensityError":0.062,"precipProbability":0.03,"precipType":"rain"},{"time":1370613900,"precipIntensity":0.142,"precipIntensityError":0.065,"precipProbability":0.03,"precipType":"rain"},{"time":1370613960,"precipIntensity":0.161,"precipIntensityError":0.072,"precipProbability":0.04,"precipType":"rain"},{"time":1370614020,"precipIntensity":0.174,"precipIntensityError":0.074,"precipProbability":0.04,"precipType":"rain"},{"time":1370614080,"precipIntensity":0.187,"precipIntensityError":0.077,"precipProbability":0.08,"precipType":"rain"},{"time":1370614140,"precipIntensity":0.207,"precipIntensityError":0.084,"precipProbability":0.09,"precipType":"rain"},{"time":1370614200,"precipIntensity":0.223,"precipIntensityError":0.088,"precipProbability":0.1,"precipType":"rain"},{"time":1370614260,"precipIntensity":0.224,"precipIntensityError":0.094,"precipProbability":0.15,"precipType":"rain"},{"time":1370614320,"precipIntensity":0.243,"precipIntensityError":0.102,"precipProbability":0.16,"precipType":"rain"},{"time":1370614380,"precipIntensity":0.259,"precipIntensityError":0.108,"precipProbability":0.17,"precipType":"rain"},{"time":1370614440,"precipIntensity":0.262,"precipIntensityError":0.108,"precipProbability":0.24,"precipType":"rain"},{"time":1370614500,"precipIntensity":0.28,"precipIntensityError":0.115,"precipProbability":0.25,"precipType":"rain"},{"time":1370614560,"precipIntensity":0.3,"precipIntensityError":0.12,"precipProbability":0.25,"precipType":"rain"},{"time":1370614620,"precipIntensity":0.322,"precipIntensityError":0.125,"precipProbability":0.26,"precipType":"rain"},{"time":1370614680,"precipIntensity":0.33,"precipIntensityError":0.125,"precipProbability":0.33,"precipType":"rain"},{"time":1370614740,"precipIntensity":0.352,"precipIntensityError":0.131,"precipProbability":0.34,"precipType":"rain"},{"time":1370614800,"precipIntensity":0.375,"precipIntensityError":0.136,"precipProbability":0.34,"precipType":"rain"},{"time":1370614860,"precipIntensity":0.38,"precipIntensityError":0.14,"precipProbability":0.42,"precipType":"rain"},{"time":1370614920,"precipIntensity":0.402,"precipIntensityError":0.147,"precipProbability":0.42,"precipType":"rain"},{"time":1370614980,"precipIntensity":0.425,"precipIntensityError":0.154,"precipProbability":0.42,"precipType":"rain"},{"time":1370615040,"precipIntensity":0.432,"precipIntensityError":0.157,"precipProbability":0.5,"precipType":"rain"},{"time":1370615100,"precipIntensity":0.454,"precipIntensityError":0.164,"precipProbability":0.5,"precipType":"rain"},{"time":1370615160,"precipIntensity":0.477,"precipIntensityError":0.168,"precipProbability":0.5,"precipType":"rain"},{"time":1370615220,"precipIntensit
Method calling the Forecast Api test class
public void weatherLike()
{
StrictMode.enableDefaults();
MyLocation myLocation = new MyLocation();
myLocation.getLocation(MyService.this, new LocationResult() {
ForecastIO fio = null;
#Override
public void gotLocation(Location location) {
try {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
fio= new ForecastIO("[API_KEY]");
} catch (Exception e) {
speakOut(user + ", I am not able to locate you");
e.printStackTrace();
}finally
{
System.out.println("Latitude: "+fio.getLatitude());
System.out.println("Longitude: "+fio.getLongitude());
System.out.println("Timezone: "+fio.getTimezone());
System.out.println("Offset: "+fio.offsetValue());
System.out.println("\n");
}
}
});
}
Thanks to all the Answers. i found out that My LogCat was trucating long messages no wonder why i never showed a full reply.
in case any one fell in the same problem.
Split the String reply to pieces using this code
if (sb.length() > 4000) {
Log.v("length", "sb.length = " + sb.length());
int chunkCount = sb.length() / 4000; // integer division
for (int i = 0; i <= chunkCount; i++) {
int max = 4000 * (i + 1);
if (max >= sb.length()) {
Log.v("1st", "chunk " + i + " of " + chunkCount + ":" + sb.substring(4000 * i));
} else {
Log.v("2nd", "chunk " + i + " of " + chunkCount + ":" + sb.substring(4000 * i, max));
}
}
}
BufferedReader use 'buffer' so U have to use 'flush method' (or close method )
refer link : http://docs.oracle.com/javase/tutorial/essential/io/buffers.html
try this
public static String getResponseText(String stringUrl) throws IOException
{
StringBuilder response = new StringBuilder();
System.out.println("webservice 1");
URL url = new URL(stringUrl);
HttpURLConnection httpconn = (HttpURLConnection)url.openConnection();
if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK)
{
System.out.println("webservice 2");
BufferedReader input = new BufferedReader(new InputStreamReader(httpconn.getInputStream()),8192);
String strLine = null;
while ((strLine = input.readLine()) != null)
{
response.append(strLine);
}
input.close();
}
return response.toString();
}
I tried to request a large amount of data from freebase. But I got error message "HTTP response code: 403". Did anyone have similar problem before?
Here is my code
private static final String service_url = "https://www.googleapis.com/freebase/v1/mqlread";
public static void main(String[] args)
{
try
{
String cursor = "";
String urlStr_initial = service_url + "?query=" + URLEncoder.encode(getQuery(), "UTF-8") + "&cursor";
URL url = new URL(urlStr_initial);
List<Freebase> list = new ArrayList<Freebase>();
Freebase f_b;
do
{
HttpURLConnection url_con = (HttpURLConnection)url.openConnection();
url_con.addRequestProperty("User-Agent", "Mozilla/4.76");
StringBuilder str_builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(url_con.getInputStream()));
String line;
while((line = reader.readLine()) != null)
{
str_builder.append(line);
}
String response = str_builder.toString();
JSONObject j_object = new JSONObject(response);
if(j_object.has("result"))
{
JSONArray j_array = j_object.getJSONArray("result");
for(int i = 0; i < j_array.length(); i++)
{
JSONObject j_o = j_array.getJSONObject(i);
if(j_o.has("id") == true && j_o.has("name"))
{
String id = j_o.getString("id");
String name = j_o.getString("name");
System.out.println("ID: " + id + " / Name:" + name);
f_b = new Freebase(id, name);
if(f_b != null)
{
list.add(f_b);
}
else
{
System.out.println("Null value in Freebase");
}
}
}
}
else
{
System.out.println("There is no \"result\" key in JASON object");
}
if(j_object.has("cursor"))
{
cursor = j_object.get("cursor").toString();
}
else
{
cursor = "false";
}
String urlStr = urlStr_initial + "=" + cursor;
url = new URL(urlStr);
}while( !cursor.equalsIgnoreCase("false"));
if(list != null)
{
TextFile tf = new TextFile();
tf.writeToFile(list);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
private static String getQuery()
{
return "[{"
+ "\"name\": null,"
+ "\"id\": null,"
+ "\"type\":\"/people/person\","
+ "\"limit\": 500"
+ "}]";
}
You don't say what "large" is, but the API isn't designed for bulk downloads. You should be using the data dumps for that.
There's usually more detailed error message included with the HTTP response code. If, for example, it says 403 - Forbidden - API key required, it means you didn't include your API key (I don't see where you include it in your code). If it says 403 - Forbidden - quota exceeded it means you've exceeded your request quota (you can look on the API console to see how much quota you have remaining).