Fetching array from json not working - java

Currently I am working with a project where I need to get some data from remote server as JSON then need to extract array. Here I am getting data successfully, But problems are near while loop.
I am getting data from remote server successfully.
For example my remote url giving output as:
{"id": "1","amount": "1000","course_code": "BASIC","course": "Basic Course","content": "Sample","thumb": "sample.png"},
{"id": "2","amount": "2000","course_code": "ADVANCED","course": "Advanced Course","content": "Sample","thumb": "sample.png"}`
Code
try {
ur = "http://localhost/getsample.php";
URL url = new URL(ur);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line="";
while (line !=null){
line = bufferedReader.readLine();
data = data+line;
}
data = data.replace("null", "");
JSONArray JA = new JSONArray(data);
for (int i=0;i<JA.length();i++){
JSONObject JO = (JSONObject) JA.get(i);
idArray = idArray + JO.get("id") + ",";
amountArray = amountArray + JO.get("amount") + ",";
course_codeArray = course_codeArray + JO.get("course_code") + ",";
courseArray = courseArray + JO.get("course") + ",";
contentArray = contentArray + JO.get("content") + ",";
thumbArray = thumbArray + JO.get("thumb") + ",";
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}

The data you get from the server are at JSON format but they are not Array . this is an object ,
{"id": "1","amount": "1000","course_code": "BASIC","course": "Basic Course","content": "Sample","thumb": "sample.png"},{"id": "2","amount": "2000","course_code": "ADVANCED","course": "Advanced Course","content": "Sample","thumb": "sample.png"}
So you have to loop inside the json object like
for (var key in jsonResponse) {
if (jsonResponse.hasOwnProperty(key)) {
console.log(key + " -> " + jsonResponse[key]);
}
}
EDIT : If you have multiple Objects inside an object you have to loop inside them ( external for) like for(var i in JsonObject)

Your Code is should be like According to your current Response
try{
JSONObject jso = new JSONObject(data);
amountArray =jsonObject.getString("amount");
course_codeArray =jsonObject.getString("yourNextKey");
courseArray = jsonObject.getString("yourNextKey");
contentArray = jsonObject.getString("yourNextKey");
thumbArray = jsonObject.getString("yourNextKey");
}
catch (JSONException e) {
e.printStackTrace();
}

Related

How to split parsed String data without special characters?

I parsed this data from Wikipedia and trying to get only characters from here. But the result comes with \n* in the front of data.
"": "=== 고양이의 종류 ===\n [[시암고양이]]\n* [[페르시안 네브스카야]]\n* [[페르시안]]\n*
[[노르웨이지언 포레스트]]\n* [[터키시 앙고라]]\n* [[아메리칸 숏헤어]]\n* [[브리티시 숏헤어]]\n*
[[러시안블루]]\n* [[뱅갈]]\n* [[메인쿤]]\n* [[랙돌]]\n* [[히말라얀]]\n* [[재패니즈
밥테일]]\n* [[오리엔탈 숏헤어]]\n* [[피터볼드]]\n* [[스코티시 폴드]]\n* 스코티시 스트레이트\n*
[[하일랜드 폴드]]\n* [[시베리안 포레스트]]\n* [[터키시 반]]\n* [[코리안 쇼트헤어]]\n*
[[올블랙]]\n* [[사바나캣]]\n* [[쿠나]]\n* [[아비시니안]]\n* 먼치킨"
This is my code.
try {
URL url = new URL("https://ko.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&rvsection=20&titles=%EA%B3%A0%EC%96%91%EC%9D%B4&format=json");
URLConnection con = url.openConnection();
InputStream is = con.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr);
while(true){
String data = reader.readLine();
if(data == null) break;
result += data;
}
JSONObject obj = new JSONObject(result);
JSONObject query = (JSONObject) obj.get("query");
JSONObject pages = (JSONObject) query.get("pages");
JSONObject pageid = (JSONObject) pages.get("93349");
JSONArray revisions = (JSONArray) pageid.get("revisions");
String catcat = String.valueOf(revisions);
String star = "\n*";
catcat = catcat.replaceAll("\\[\\[","").replaceAll("\\]\\]",",").replaceAll("\\r|\\n", "").replaceAll(star,"");
String[] catcategory = catcat.split(",");
for (int i = 0; i<catcategory.length;i++){
list.add(catcategory[i]);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
Result for this looks like
\n시암고양이
\n페르시안
and I want to remove \n*.
How to split parsed String data without special characters?
Try this piece of code, It's removed \n* , Then you can add _result_word to your list.
for (int i = 0; i < catcategory.length; i++) {
try {
String _result_word = catcategory[i].replaceFirst("\\\\n", "").replace("*", "");
//String _result_word=catcategory[i].replaceFirst("\\\\n", "").replace("*", "").replaceFirst("\\\\n", "").replace("*", "");
System.out.println("" + _result_word);
list.add(_result_word);
} catch (Exception ex) {
System.out.println("Special Exception occurred at index : i = " + i);
ex.printStackTrace();
}
}
Everything correct except one line where you need escape asterisk character and escape slash character
String star = "\\\\n\\*";
str.replaceAll(star, "");

Keep getting java.lang.NegativeArraySizeException: -2, not sure why

I am working on an Android project. I am creating a graph and populating the graph with json content. My problem is that i keep getting this error and i am not sure why. java.lang.NegativeArraySizeException: -2
My Log.v shows the content of the array. So it's not empty. Maybe i am missing something.
I go through the rest api and add everything to the arraylist resModelList.
In the onPostExecute, I want to add my y-axis values to this array list yVals1.
This is where i get my error. (java.lang.NegativeArraySizeException: -2)
If i add the values like this, I get no error.
yVals1 = new ArrayList<Entry>();
yVals1.add(new Entry(1451606400, 10));
yVals1.add(new Entry(1454284800, 20));
yVals1.add(new Entry(1456790400, 30));
yVals1.add(new Entry(1459468800, 50));
My code
Global variables
ArrayList<ResultModel> resModelList;
ArrayList<Entry> yVals1;
Parse Json
//getResult
public class JSONTask extends AsyncTask<String, String, List<ResultModel>> {
#Override
protected List<ResultModel> doInBackground(String... params) {
BufferedReader reader = null;
HttpURLConnection connection = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Cookie",session_name+"="+session_id);
connection.setRequestProperty("X-CSRF-Token", token);
//connection.setRequestProperty("Accept-Encoding", "identity");
connection.connect();
int length = connection.getContentLength();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
String line = "";
StringBuffer buffer = new StringBuffer();
while ((line = reader.readLine()) != null){
buffer.append(line);
}
Log.v("TESt", " " + length);
String finalJson = buffer.toString();
JSONArray parentArray = new JSONArray(finalJson);
resModelList = new ArrayList<>();
for(int i=0; i<parentArray.length(); i++){
JSONObject finalObject = parentArray.getJSONObject(i);
ResultModel resModel = new ResultModel();
resModel.setPost_date(finalObject.getString("post_date"));
resModel.setHow_much_has_ocd(finalObject.getString("how_much_has_ocd"));
resModelList.add(resModel);
}
return resModelList;
}catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection != null) {
connection.disconnect();
}
try {
if(reader != null){
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<ResultModel> result) {
super.onPostExecute(result);
if(!resModelList.isEmpty()){
//here is where i get my errors
yVals1 = new ArrayList<Entry>();
for (ResultModel ocd : resModelList){
int score = Integer.parseInt(ocd.getHow_much_has_ocd());
int timeStamp = Integer.parseInt(ocd.getPost_date());
//I get these log values
Log.v("Score: ", " " + score + " Timestamp: " + timeStamp);
yVals1.add(new Entry(timeStamp, score));
}
graph();
Log.v("Not Empty list", "");
}else {
Log.v("Empty list", "");
}
}
}
finalJson log.v
[{"post_date":"1481895820","did_you_avoid":"25","how_much_has_ocd":"81","how_would_you_rate":"82","overall_how_would":"35","were_there_any_distressing":"0","uid":"2"},{"post_date":"1481723564","did_you_avoid":"13","how_much_has_ocd":"10","how_would_you_rate":"13","overall_how_would":"16","were_there_any_distressing":"0","uid":"2"},{"post_date":"1481723488","did_you_avoid":"28","how_much_has_ocd":"56","how_would_you_rate":"75","overall_how_would":"32","were_there_any_distressing":"0","uid":"2"},{"post_date":"1481537274","did_you_avoid":"53","how_much_has_ocd":"59","how_would_you_rate":"15","overall_how_would":"71","were_there_any_distressing":"1","uid":"2"},{"post_date":"1481295470","did_you_avoid":"67","how_much_has_ocd":"64","how_would_you_rate":"66","overall_how_would":"57","were_there_any_distressing":"0","uid":"2"},{"post_date":"1481097609","did_you_avoid":"72","how_much_has_ocd":"85","how_would_you_rate":"62","overall_how_would":"64","were_there_any_distressing":"0","uid":"2"},{"post_date":"1480673252","did_you_avoid":"33","how_much_has_ocd":"69","how_would_you_rate":"84","overall_how_would":"37","were_there_any_distressing":"1","uid":"2"},
I am a beginner so it might just be simple mistake.
Thanks in advance
I found the error. It was my graph library.
I am using MPAndroidChart library and you need to sort the data. My back-end was sorted desc. I had to change it to Post date (asc).
Its related to this problem.
NegativeArraySizeException adding Scatter Data to a CombinedChart
I hope this helps someone else.

Google Distance Matrix not getting distance

I have roughly tried to parse the JSON from Google Distance Matrix API, but it is not showing the distance.
My GPS location is not 0,0 that I'm sure of.
String distance = getMatrix(latitude,longitude);
My code for the function is:
private String getMatrix(double lat , double lang){
JSONObject jObj;
String getdistance = "";
String strUrl = "http://maps.googleapis.com/maps/api/distancematrix/json?origins="
+ Double.toString(my_lat) + ","
+ Double.toString(my_lang)
+ "&destinations="+ Double.toString(lat) + ","
+ Double.toString(lang)
+ "&mode=walking&sensor=false";
String data = "";
InputStream reader = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
reader = urlConnection.getInputStream();
int bRead = -1;
byte[] buffer = new byte[1024];
do {
bRead = reader.read(buffer, 0, 1024);
if (bRead == -1) {
break;
}
data += new String(buffer, 0, bRead);
} while (true);
urlConnection.disconnect();
} catch(Exception e) {
} finally {
}
try {
jObj = new JSONObject(data);
JSONArray rowsArray = jObj.getJSONArray("rows");
JSONObject rows = rowsArray.getJSONObject(0);
JSONArray elementsArray = rows.getJSONArray("elements");
JSONObject newDisTimeOb = elementsArray.getJSONObject(0);
JSONObject distOb = newDisTimeOb.getJSONObject("distance");
getdistance = distOb.optString("text").toString();
} catch (JSONException e) {
e.printStackTrace();
}
return getdistance;
}
First, check if you've correctly build the url string in the code:
String strUrl = "http://maps.googleapis.com/maps/api/distancematrix/json?origins="
+ Double.toString(my_lat) + ","
+ Double.toString(my_lang)
+ "&destinations="+ Double.toString(lat) + ","
+ Double.toString(lang)
+ "&mode=walking&sensor=false";
// Line to check if url code is right
Log.d("APP", "strUrl = " + strUrl);
Then check your following code, whether it really produce the data:
reader = urlConnection.getInputStream();
int bRead = -1;
byte[] buffer = new byte[1024];
do {
bRead = reader.read(buffer, 0, 1024);
if (bRead == -1) {
break;
}
data += new String(buffer, 0, bRead);
} while (true);
My suggestion is to use BufferedReader instead reading the response byte per byte.
Then change:
getdistance = distOb.optString("text").toString();
to
getdistance = distOb.getString("text");
Because you don't need to convert to string again here.
I've search Client Libraries for Google Maps Web Services and found DistanceMatrixApi.java. Maybe we can use it, but I can't assure of it.

How to read multiple jsonArrays from a file?

I want to read many jsonArrays from a file.
these are the JsonArrays in the file:
[{name:"John",preis:"123",bild:1235},
{name:"Smith",preis:"256",bild:7205},
{name:"Steeven",preis:"632",bild:324035}]
[{name:"Hans",preis:"85",bild:1005},
{name:"Peter",preis:"420",bild:22205},
{name:"Joe",preis:"200",bild:3240}]
[{name:"Jane",preis:"355",bild:10505},
{name:"Calith",preis:"630",bild:96505},
{name:"Eva",preis:"260",bild:32440}]
I can not read the whole file, but i can read only the first jsonArray from the file.
here is my code to read it:
ArrayList<Werkzeug> myWerkzeuge = new ArrayList<Werkzeug>();
String alteBestellung = "";
try {
FileInputStream fileInputStream = openFileInput(fileName);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
while ( (line = bufferedReader.readLine()) != null){
alteBestellung = alteBestellung + line;
}
JSONArray jsonArray = new JSONArray(alteBestellung);
for (int i = 0; i<jsonArray.length(); ++i){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name_werkzeuge = (String) jsonObject.get("name");
String preis_werkzeuge = (String) jsonObject.get("preis");
Integer bild_werkzeuge = Integer.valueOf( (String)jsonObject.get("bild") );
myWerkzeuge.add( new Werkzeug(name_werkzeuge, preis_werkzeuge, bild_werkzeuge));
}
fileInputStream.close();
inputStreamReader.close();
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
String bestellung = " ";
for (int i = 0; i< myWerkzeuge.size(); ++i) {
bestellung = bestellung + "\n" + myWerkzeuge.get(i).getName() + " " + myWerkzeuge.get(i).getPreis() + " €" + myWerkzeuge.get(i).getBild();
}
bestellungsTextView.setText( bestellung );
How to read these three jsonArrays from this file?
What you need is a valid json.
You probably want a JsonArray of JsonArray :
[
[{name:"John",preis:"123",bild:1235},
{name:"Smith",preis:"256",bild:7205},
{name:"Steeven",preis:"632",bild:324035}],
[{name:"Hans",preis:"85",bild:1005},
{name:"Peter",preis:"420",bild:22205},
{name:"Joe",preis:"200",bild:3240}],
[{name:"Jane",preis:"355",bild:10505},
{name:"Calith",preis:"630",bild:96505},
{name:"Eva",preis:"260",bild:32440}]
]
This is not valid json .
First of all make a valid json.

Can't POST data to site using HttpURLConnection on Android

I'm essentially trying to mimic what's been done here through the Android app but for some reason data doesn't get returned as soon as it attempts to post data (it returns fine when I delete the writer.write(finalResult) line).
All I want right now is to be able to search for a user's data once I've sent the username.
Here's my code below:
try {
URL u = new URL(url);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("POST");
c.setRequestProperty("Content-length", "0");
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.setDoInput(true);
c.setDoOutput(true);
//Attempting to send data!
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", paramValue));
OutputStream os = c.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
String finalResult = getQuery(params);
Log.d("params", finalResult);
writer.write(finalResult);
writer.close();
os.close();
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
result = sb.toString();
}
} catch (MalformedURLException ex) {
Log.e("log_tag", "Error converting result ");
} catch (IOException ex) {
Log.e("log_tag", "Error in http connection ");
}
//json code!
//parse json data
try{
JSONArray jArray = new JSONArray(result);
//for each object in our json array
for(int i =0; i < jArray.length(); i++){
JSONObject json_data =jArray.getJSONObject(i);
String address = "";
//Checks for missing data in address - Need a class for all fields
if (json_data.isNull("address")){
address = "N/A";
}
else
{
address = json_data.getString("address");;
}
//read one line of the response
myListView.setText("Username: "+json_data.getString("username")
+" / " + "Name: " + json_data.getString("name")
+" / " + "E-mail: " + json_data.getString("email")
+" / " + "Address: " + address);
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data"+e.toString());
}
}
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params)
{
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
And here is my php script:
<?php
$searchuser = $_GET["username"];
$databasehost = databasehost;
$databasename = database;
$databaseusername = username;
$databasepassword = password;
$con = mysql_connect($databasehost, $databaseusername, $databasepassword) or die(mysql_error());
mysql_select_db($databasename) or die(mysql_error());
$query = "SELECT * FROM testusers";
$sth = mysql_query($query);
if (mysql_errno()) {
header("HTTP/1.1 500 Internal Server Error");
echo $query."\n";
echo mysql_error();
}
else
{
$rows = array();
while ($r = mysql_fetch_assoc($sth)){
$rows[] = $r;
}
print json_encode($rows);
}
?>
Since you set the header Content-Length to be 0, the server doesn't even read your content... So anything you send isn't received. You should set Content-Length to finalResult.length().
remove this,
c.setRequestProperty("Content-length", "0");

Categories

Resources