JSON Exception Error - java

I am getting the following error on logcat when I run my application. I had many errors before which I have managed to resolve after doing some research. However, this one I am unable to figure out:
03-04 02:52:29.475: E/JustDealsUtils(1913): Error parsing to json on getJarrayFromString(); org.json.JSONException: Expected ':' after result at character 8 of {result}
EDIT 1:
The error now is:
Error parsing to json on getJarrayFromString(); org.json.JSONException: Value result of type java.lang.String cannot be converted to JSONArray
Also linked to this is error for fillproductlist()
Here is my Java Code for this:
public void onTaskCompleted(String result) {
try {
if(result!=""){
// the remote php link
// converting the response into json array
Log.i(DEBUG, result);
jarray = utils.getJarrayFromString(result);
// number of rows in total for a query
int mysqlSize = (jarray.getJSONObject(0).getInt("numRows"));
Log.i(DEBUG, "From " + from + " to " + mysqlSize);
// to check if all the rows are parsed from the mysql
if(from <= mysqlSize){
int rows;
// to check if there is 0
if(jarray.length()>0){
Log.i(DEBUG, "From " + from + " to " + Math.floor(mysqlSize/nr)*nr);
if(from+5<=Math.floor(mysqlSize/nr)*nr){
rows = jarray.length();
}else{
rows = mysqlSize%nr+1;
Utils.IS_ENDED_PRODUCT_LIST = true;
}
ArrayList<String> list = new ArrayList<String>();
for(int i=1; i<rows; i++){
JSONObject row = jarray.getJSONObject(i);
bid.add(row.getInt("bid"));
bTitle.add(row.getString("bTitle"));
bCode.add(row.getString("bCode"));
bPrice.add(row.getString("bPrice") + "£");
bDescription.add(row.getString("bDescription"));
bModule.add(row.getString("bModule"));
bImage.add(Utils.PATH + row.getString("bImage"));
list.add(row.getString("bImage"));
// to check if an id already exists in the db or to create one if doesn't exist
if(!db.hasIDBooks(row.getInt("bid"))) db.createRowOnBooks(row.getInt("bid"), row.getString("bTitle"), row.getString("bCode"), row.getString("bPrice"), row.getString("bDescription"), row.getString("bModule"), Utils.PATH + row.getString("bImage"), row.getString("bSpecialOffer"), row.getInt("bSpecialDiscount"), row.getString("bDateAdded"));
Log.i(DEBUG, row.getString("bDescription"));
}
new DownloadImages(list, bAdapter).execute();
}
}
postParameters.removeAll(postParameters);
}else{
Utils.IS_ENDED_PRODUCT_LIST = true;
if(rlLoading.isShown()){
rlLoading.startAnimation(fadeOut());
rlLoading.setVisibility(View.INVISIBLE);
}
}
} catch (Exception e) {
Log.e(DEBUG, "Error at fillProductList(): " + e.toString());
}
}
});
task.execute();
}else{
// if internet connectio is not available
// then, rows will be fetched from the local sqllite database stored on the android phone
if(db.size(justdealsDatabase.TABLE_BOOKS) > 0){
Cursor cursor = db.getBooksRows(justdealsDatabase.TABLE_BOOKS);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
bid.add(cursor.getInt(cursor.getColumnIndex(justdealsDatabase.KEY_BID)));
bTitle.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BTITLE)));
bCode.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BCODE)));
bPrice.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BPRICE))+ "£");
bDescription.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BDESCRIPTION)));
bModule.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BMODULE)));
bImage.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BIMAGE)));
cursor.moveToNext();
}
bAdapter.notifyDataSetChanged();
Utils.IS_ENDED_PRODUCT_LIST = true;
}
}
}
MY JSON ARRAY CODE ( FULL EDIT 2):
public String getJsonFromUrl(String url){
// to initialise the objects
InputStream is = null;
String result = "";
//making HTTP POST request
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e(DEBUG, "Error getJsonFromUrl: " + e.toString());
}
// Converting to String
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e(DEBUG, "Error converting the response to string getJsonFromUrl: " + e.toString());
}
return result;
}
/**
* To convert the string recieved into json object
* result refers to the string that will be converted
* #return will return the json array
*/
public JSONArray getJarrayFromString(String result){
// Parsing string to JSON Array
try{
jarray = new JSONArray("result");
}catch(JSONException e){
Log.e(DEBUG, "Error parsing to json on getJarrayFromString(); " + e.toString());
}
return jarray;
}
And My PHP API (EDIT 1):
<?php
include("MysqlConnection.php");
header('Content-Type: application/json');
$from = $_POST["from"];
$nr = $_POST["nr"];
// those variables are for search
$title = $_POST["title"];
$code = $_POST["code"];
$price = $_POST["price"];
$module = $_POST["module"];
$order = $_POST["order"];
$by = $_POST["by"];
$sql = "SET CHARACTER SET utf8";
$db->query($sql);
// if those 2 var are set then we order the query after them
if(isset($order) && isset($by)){
$sql .= " ORDER BY `$order` $by LIMIT $from, $nr";
}else{
$sql .= "LIMIT $from, $nr";
}
$query = $db->query($sql);
$rows = array();
$rows[] = array("numRows"=>$db->numRows($query));
if($db->numRows($query)!=0){
while($row = mysql_fetch_assoc($query)) {
$rows[] = $row;
}
echo(json_encode($rows));
}
}
$db->closeConnection();
?>
I have implemented all the suggestions recommended by you guys, still there is no luck in getting this code work!!!!
I AM NOT SURE WHY VALUE OF 'RESULT' STRING CANNOT BE CONVERTED INTO JSONARRAY????
I have shown you the JSON ARRAY Declaration, RESULT STRING DECLARATION as well as PHP (See Above for edited versions)

you have to use echo not print_r
echo json_encode($rows);
print_r gives output in array format.

You have send the result two times you have to send the result only one time with encoded
remove the following code and try
echo json_encode($rows);

Maybe you should name your array without "{}" symbols?
jarray = new JSONArray("result");
instead of
jarray = new JSONArray("{result}");

Related

Values Cannot be Converted to JSON Array

This is the function that's giving me the problem:
public String URLToJson() {
String result = "";
String jsonString = ReadingURL(" here goes my URL that reads a JSON ");
JSONObject jsonResult = null;
try {
jsonResult = new JSONObject(jsonString);
JSONArray data = jsonResult.getJSONArray("Configuracion");
if (data != null) {
for (int i = 0; i <= data.length(); i++) {
result = result + "Dirección: " + data.getJSONObject(i).getString("Direccion") + "\n";
result = result + "Cédula: " + data.getJSONObject(i).getString("Cedula") + "\n";
result = result + "Nombre: : " + data.getJSONObject(i).getString("Nombre") + "\n";
result = result + "Teléfono : " + data.getJSONObject(i).getString("Telefono") + "\n";
result = result + "Hacienda: " + data.getJSONObject(i).getString("Hacienda") + "\n";
}
}
return result;
}catch (JSONException e){
e.printStackTrace();
return "Error Reading JSON Data";
}
}
And then this comes up:
`W/System.err: org.json.JSONException: Value {"Direccion":"Somewhere","Cedula":"111111","Nombre":"Something","Telefono":"2222-2440","Hacienda":"Something"} at Configuracion of type org.json.JSONObject cannot be converted to JSONArray
at org.json.JSON.typeMismatch(JSON.java:100)
W/System.err: at org.json.JSONObject.getJSONArray(JSONObject.java:588)
at com.example.user.mypos.PrintManager.URLToJson(PrintManager.java:977)
W/System.err: at com.example.user.mypos.PrintManager$4.run(PrintManager.java:917)
at java.lang.Thread.run(Thread.java:818)W/System.err: org.json.JSONException: Value { the values that are supposed to be } of type org.json.JSONObject cannot be converted to JSONArray`
ReadingURL basically reads the content of an URL, that has the JSON in String.
From the exception it's clear that the JSON string returned by the URL is of type JSONObject not of JSONArray .
Value { the values that are supposed to be } of type org.json.JSONObject cannot be converted to JSONArray
JSON object will starts with { & ends with }
{
"KEY1":"VALUE1",
"KEY2":"VALUE2"
}
and JSON array will starts with [ and ends with ] .
[
{"KEY1":"VALUE1","KEY2":"VALUE2"},{"KEY1":"VALUE1","KEY2":"VALUE2"}
]
So you are getting this exception because you are trying to convert JSON object to JSON array.
to Deepak Gunasekaran
public String URLToJson() {
String result = "";
String jsonString = ReadingURL("http://deliciasmarinas.avancari.co.cr/app/tiquete.php?factura=414696772");
JSONObject jsonResult = null;
try {
jsonResult = new JSONObject(jsonString);
for (int i = 0; i <= jsonResult.length(); i++) {
result = result + "Dirección: " + jsonResult.get("Direccion") + "\n";
result = result + "Cédula: " + jsonResult.get("Cedula") + "\n";
result = result + "Nombre: : " + jsonResult.get("Nombre") + "\n";
result = result + "Teléfono : " + jsonResult.get("Telefono") + "\n";
result = result + "Hacienda: " + jsonResult.get("Hacienda") + "\n";
}
return result;
}catch (JSONException e){
e.printStackTrace();
return "Error Reading JSON Data";
}
}
And now it just shows
W/System.err: org.json.JSONException: No value for Direccion
at org.json.JSONObject.get(JSONObject.java:389)
W/System.err: at com.example.user.mypos.PrintManager.URLToJson(PrintManager.java:978)
at com.example.user.mypos.PrintManager$4.run(PrintManager.java:917)
at java.lang.Thread.run(Thread.java:818)

Extracting JSONObject fromJSONArray

working on an android application to try and connect to "steemit.com' and return JSON data to me.
Everything has been working so far, printing the mass response from the URL to the Textview, only I am now getting no errors, and no text printed out in the screen so I assume I am using the wrong type of object or something. Perhaps the data I am trying to retrieve is not an Array? What do you all think? Here is my code.
public class fetchdata extends AsyncTask<Void,Void,Void> {
String data = "";
String dataParsed = "";
String singleParsed = "";
#Override
protected Void doInBackground(Void... voids) {
{
try {
URL url = new URL("https://steemit.com/#curie.json");
HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
InputStream inputStream = httpsURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String lines = "";
while(lines != null){
lines = bufferedReader.readLine();
data = data + lines;
}
JSONArray JA = new JSONArray(data);
for (int i =0 ;i < JA.length(); i++){
JSONObject JO = (JSONObject) JA.get(i);
singleParsed = "User: " + JO.get("user") + "\n" +
"Location: " + JO.get("location") + "\n" +
"ID: " + JO.get("id")+"\n";
dataParsed = dataParsed + singleParsed;
}
} 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);
followers.dataTV.setText(this.dataParsed);
}
}
and the page I expect the TextView to display data on.
public class followers extends AppCompatActivity {
public static TextView dataTV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_followers);
ListView followList = (ListView)findViewById(R.id.followList);
dataTV = (TextView)findViewById(R.id.followersTVData);
fetchdata process = new fetchdata();
process.execute();
}
}
If I have not been clear, what the issue is, is that when I 'printText' using the variable 'data', there is no problems, and the bulk text is printed, however, I am now trying to break it down into bits, and it is just not printing anything when I use the variable 'dataParsed'. Any help is appreciated. Thank you in advance!
I have been asked for the response. Here it is, though rather long.
{"user":{"id":1026971,"name":"ceruleanblue","owner":{"weight_threshold":1,"account_auths":[],"key_auths":[["STM7UPr1LJMw4aAxcuiYAmad6bjjiaeDcfgSynRMrr5L6uvuSJLDJ",1]]},"active":{"weight_threshold":1,"account_auths":[],"key_auths":[["STM7qUaQCghsFZA37fTxVB4BqBBK49z35ni6pha1Kr4q4qLkrNRyH",1]]},"posting":{"weight_threshold":1,"account_auths":[["minnowbooster",1],["steemauto",1]],"key_auths":[["STM7qF27DSYNYjRu5Jayxxxpt1rtEoJLH6c1ekMwNpcDmGfsvko6z",1]]},"memo_key":"STM7wNQdNS9oPbVXscbzn7vfzjB7SwmLGQuFQNzZgatgpqvdKzWQZ","json_metadata":{"profile":{"profile_image":"https://cdn.steemitimages.com/DQmfNj7SLU1aBtV9UkJa5ZKMZPNuzR4ei5UJRA54JxFk99M/Mushrooms%20Trippy%20Art%20Fabric%20Cloth%20Rolled%20Wall%20Poster%20Print.jpg","name":"Cerulean's Chillzone","about":"IT Technician, Programmer, Day Trader, Night Toker.","location":"Ontario, Canada","cover_image":"https://cdn.steemitimages.com/DQmTwT379V7EcQ1ZkqkmJkpWyu4QXw1LzDinv9uoyixksMY/tumblr_static_tumblr_static__640.jpg"}},"proxy":"","last_owner_update":"2018-06-18T19:57:39","last_account_update":"2018-08-01T04:33:06","created":"2018-06-03T20:28:21","mined":false,"recovery_account":"steem","last_account_recovery":"1970-01-01T00:00:00","reset_account":"null","comment_count":0,"lifetime_vote_count":0,"post_count":321,"can_vote":true,"voting_power":9800,"last_vote_time":"2018-08-09T02:47:03","balance":"8.000 STEEM","savings_balance":"0.000 STEEM","sbd_balance":"1.979 SBD","sbd_seconds":"927621285","sbd_seconds_last_update":"2018-08-09T13:23:15","sbd_last_interest_payment":"2018-07-11T10:18:12","savings_sbd_balance":"0.000 SBD","savings_sbd_seconds":"2067163545","savings_sbd_seconds_last_update":"2018-07-23T08:58:48","savings_sbd_last_interest_payment":"2018-07-09T06:32:27","savings_withdraw_requests":0,"reward_sbd_balance":"0.000 SBD","reward_steem_balance":"0.000 STEEM","reward_vesting_balance":"0.000000 VESTS","reward_vesting_steem":"0.000 STEEM","vesting_shares":"167703.513691 VESTS","delegated_vesting_shares":"29412.000000 VESTS","received_vesting_shares":"0.000000 VESTS","vesting_withdraw_rate":"0.000000 VESTS","next_vesting_withdrawal":"1969-12-31T23:59:59","withdrawn":0,"to_withdraw":0,"withdraw_routes":0,"curation_rewards":182,"posting_rewards":110408,"proxied_vsf_votes":[0,0,0,0],"witnesses_voted_for":1,"last_post":"2018-08-07T12:43:42","last_root_post":"2018-08-07T12:25:39","average_bandwidth":"44620566375","lifetime_bandwidth":"1099256000000","last_bandwidth_update":"2018-08-09T13:23:15","average_market_bandwidth":3415484305,"lifetime_market_bandwidth":"237250000000","last_market_bandwidth_update":"2018-08-07T13:21:39","vesting_balance":"0.000 STEEM","reputation":"1564749115439","transfer_history":[],"market_history":[],"post_history":[],"vote_history":[],"other_history":[],"witness_votes":["guiltyparties"],"tags_usage":[],"guest_bloggers":[]},"status":"200"}null
Perhaps I have implemented this improperly?
for (int i =0 ;i < JA.length(); i++){
JSONObject JO = (JSONObject) JA.getJSONObject(i);
singleParsed = "User: " + JO.get("user.id") + "\n" +
"Location: " + JO.get("location") + "\n" +
"ID: " + JO.get("id")+"\n";
dataParsed = dataParsed + singleParsed;
}
UPDATED FIXES, STILL BROKEN BUT FARTHER ALONG.
String lines = "";
while(lines != null){
lines = bufferedReader.readLine();
data = data + lines;
}
JSONObject JO = new JSONObject(data);
String m = "";
for (int i =0 ;i < JO.length(); i++){
// JSONObject JO = (JSONObject) JO.getJSONObject(i);
singleParsed = "User: " + JO.getString("user.id") + "\n" +
"Location: " + JO.getString("location") + "\n" +
"ID: " + JO.getString("id")+"\n";
dataParsed = dataParsed + singleParsed;
DEBUGGER BREAKS ON "singleParsed = "user:", any ideas from here?
The response is a JSONObject not a JSONArray.
So, you can directly use: new JSONObject(data); in your code.
Also, as you haven't noticed, there's a null at the end after the closing brace.
I think you should parse the data with JSONObject, because the response is not an array. You should create class which contain User class and String for the status to handle the response.
Or you can use retrofit instead.
http://square.github.io/retrofit/
Try this...
try {
JSONObject object = new JSONObject(data);
String user = object.getString("user");
int id = user.getInt("id");
String name = user.getString("name");
String owner = user.getString("owner");
int weight_threshold = owner.getInt("weight_threshold");
JSONArray account_auths = owner.getJSONArray("account_auths");
.....
} catch (Exception e) {
e.printStackTrace();
}
pass other objects so on.

org.json.JSONException: End of input at character 0 of [duplicate]

This question already has answers here:
org.json.JSON Exception : End of input at character 0
(4 answers)
Closed 6 years ago.
When the URL is ran manually in browser, this JSON is returned.
{
  "error": false,
  "0": {
    "question": "Using the information that 6.7 × 52 = 348.4, Find the value of: 6.7 × 520",
    "useranswer": "3484",
    "correctanswer": "3484",
    "correct": "1"
  },
  "1": {
    "question": "Jane drives 50mph. London is 350 miles away. How long will it take?",
    "useranswer": "5",
    "correctanswer": "7",
    "correct": "0"
  },
  "2": {
    "question": "74*3?",
    "useranswer": "222",
    "correctanswer": "222",
    "correct": "1"
  },
  "3": {
    "question": "39+31?",
    "useranswer": "70",
    "correctanswer": "70",
    "correct": "1"
  }
}
The code is as follows:
public List<String> GetTestResultsFromUserID(Integer userID){
BufferedReader bufferedReader = null;
try {
URL url = new URL(AppConfig.Results_URL + "?userid=" + userID);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty ("Authorization", "Basic Z2FycmV0dGg6ZnJBc3Rpbmc0");
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String result;
result = bufferedReader.readLine();
return ProcessResultSetFromDatabase(result);
}catch(Exception e){
Log.d("Exception in try", "Exception" + e.toString());
return null;
}
}
And then the result is processed here:
private List<String> ProcessResultSetFromDatabase(String result){
List<String> resultSet = new ArrayList<String>();
try{
JSONObject jObj = new JSONObject(result);
boolean error = jObj.getBoolean("error");
if (!error){
for (int i=0; i<48; i++){
JSONObject rSet = jObj.getJSONObject(Integer.toString(i));
resultSet.add("Q: "+rSet.getString("question")+" Correct Ans: "+rSet.getString("correctanswer")+" Given Ans: "+rSet.getString("useranswer")+" Correct:"+(rSet.getString("correct")));
}
}else{
resultSet.add("No results at the moment");
}
}catch(JSONException e){
e.printStackTrace();
}
return resultSet;
}
Note: The result passed to ProcessResultSetFromDatabase seems to be null when passed.
Your JSON output is in "0":{"question": String and you pass integer, So you need to convert int to string.
for (int i=0; i<48; i++){
int tmpInt = i;
String str= String.valueOf(i);
JSONObject rSet = jObj.getJSONObject(str);
resultSet.add("Q: "+rSet.getString("question")+" Correct Ans: "+rSet.getString("correctanswer")+" Given Ans: "+rSet.getString("useranswer")+" Correct:"+(rSet.getString("correct")));
}
You should parse your data using Iterator.
JSONObject jObj = new JSONObject(result);
if (jObj.length() > 0) {
Iterator<String> keys = jObj.keys();
while (keys.hasNext()) {
String key = keys.next();
JSONObject json= jObj.optJSONObject(key);
Log.e("json", json.toString());
if (json!= null) {
resultSet.add("Q: "+json.getString("question")+" Correct Ans: "+json.getString("correctanswer")+" Given Ans: "+json.getString("useranswer")+" Correct:"+(json.getString("correct")));
}
}
}

How to parse a multi-array JSON (Java)

I'm currently working on a project that requires the latitude and longitude of a given address (input). Google maps API returns in json format, and I've done research and found that json-simple is the best option for my project. I have this code as well as the String output from google maps API, and would highly appreciate some help in parsing properly.
Also note: the call: MapTile.receiveJson just returns the string from google's API (linked below)
try {
String jsonAdr = MapTile.receiveJson("http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA");
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject)parser.parse(jsonAdr);
System.out.println("lat=" + json.get("address_components"));
} catch (Exception e1) {e1.printStackTrace();System.out.println("Error contacting google or invalid input");}
This is the exact string output from google's API:
http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA
I realize I could do String parsing, however it would be inefficient as I will be using more of google's API. I have also viewed other stack overflow, as well as their JSON website but found no examples with multiple JSON arrays such as those returned by google.
Any help is greatly appreciated.
Here's the solution:
I basically made a stand alone and I parsed your JSON like this:
First : This is the method I used to parse the JSON:
public String loadJSON(String someURL) {
String json = null;
HttpClient mHttpClient = new DefaultHttpClient();
HttpGet mHttpGet = new HttpGet(someURL);
try {
HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);
StatusLine statusline = mHttpResponse.getStatusLine();
int statusCode = statusline.getStatusCode();
if (statusCode != 200) {
return null;
}
InputStream jsonStream = mHttpResponse.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
jsonStream));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
json = builder.toString();
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
mHttpClient.getConnectionManager().shutdown();
return json;
}
Second : Used Async Task to download the data:
public class BackTask extends AsyncTask<Void, Void, Void> {
String url;
public BackTask(String URL) {
super();
this.url = URL;
}
#Override
protected Void doInBackground(Void... params) {
getData(url);
return null;
}
}
Third: Method to get the data and parse it. I have made some comments for this part since it's a bit long than usual.
public void getData(String URL) {
try {
JSONObject mainJsonObject = new JSONObject(loadJSON(URL));
// Log.d("JSON Data : ", mainJsonObject.toString());
String Status = mainJsonObject.getString("status");
Log.d("JSON Status : ", Status + "\n" + "---------------------");
JSONArray mainArray = mainJsonObject.getJSONArray("results");
// Log.d("JSON Array : ", mainArray.toString());
for (int i = 0; i < mainArray.length(); i++) {
JSONObject insideJsonObject = mainArray.getJSONObject(i);
if (insideJsonObject != null) {
String address_components = insideJsonObject
.getString("address_components");
// Log.d("Inside JSON Array : ", address_components);
JSONArray addressJSON = insideJsonObject
.getJSONArray("address_components");
// Log.d("Inside JSON ADDress : ", addressJSON.toString());
String formatted_address = insideJsonObject
.getString("formatted_address");
Log.d("Inside JSON formatted_address : ", formatted_address
+ "\n" + "-----------");
for (int ji = 0; ji < mainArray.length(); ji++) {
JSONObject geoMetryJO = mainArray.getJSONObject(ji);
if (geoMetryJO != null) {
JSONObject geometry = geoMetryJO
.getJSONObject("geometry");
// Log.d("Inside JSON geometry : ",
// geometry.toString()+"\n"+"----------");
String location_type = geometry
.getString("location_type");
Log.d("Inside JSON location_type : ", location_type
+ "\n" + "------------");
JSONObject locationJSONObject = geometry
.getJSONObject("location");
String Latitude = locationJSONObject
.getString("lat");
Log.d("Inside JSON Latitude : ", Latitude + "\n"
+ "--------------");
String Longitude = locationJSONObject
.getString("lng");
Log.d("Inside JSON Longitude : ", Longitude + "\n"
+ "------------");
JSONObject viewportJSONObject = geometry
.getJSONObject("viewport");
// Log.d("Inside JSON viewportJSONObject : ",
// viewportJSONObject.toString()+"\n"+"------------");
JSONObject northeastJSONObject = viewportJSONObject
.getJSONObject("northeast");
String Lat = northeastJSONObject.getString("lat");
Log.d("Inside JSON Lat : ", Lat + "\n"
+ "------------");
String Lon = northeastJSONObject.getString("lng");
Log.d("Inside JSON Lon : ", Lon + "\n"
+ "------------");
JSONObject southwestJSONObject = viewportJSONObject
.getJSONObject("southwest");
String south_Lat = southwestJSONObject
.getString("lat");
Log.d("Inside JSON south_Lat : ", south_Lat + "\n"
+ "------------");
String south_Lon = southwestJSONObject
.getString("lng");
Log.d("Inside JSON south_Lon : ", south_Lon + "\n"
+ "------------");
}
}
for (int k = 0; k < addressJSON.length(); k++) {
JSONObject addressJSONObject = addressJSON
.getJSONObject(k);
if (addressJSONObject != null) {
String long_name = addressJSONObject
.getString("long_name");
Log.d("Inside JSON LongName : ", long_name);
String short_name = addressJSONObject
.getString("short_name");
Log.d("Inside JSON ShortName : ", short_name);
JSONArray addressJSONArray = addressJSONObject
.getJSONArray("types");
Log.d("Inside JSON JSONADD : ",
addressJSONArray.toString() + "\n"
+ "-------------");
}
}
JSONArray insideJsonArray = insideJsonObject
.getJSONArray("types");
Log.d("Inside JSON Types : ", insideJsonArray.toString());
String street = insideJsonObject.getString("types");
Log.d("Inside JSON Street : ", street);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
After getting all the data, you can use it in anyway you want cause it's mostly in the string format. You can just copy and paste this method and it should run fine.
Fourth : On the onCreate() method, just executed the task like this:
public static final String URL = "http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new BackTask(URL).execute();
}
This was the complete solution for this question. Let me know if have any questions for this. Hope this helps..Good Luck.. :)
I did this for formatted_address. I type casted explicitly here. But getJSONArray () and getJSONObject() methods will perform the typecasting too.
// parse the Result String to JSON
JSONObject myJSONResult = new JSONObject(results);
for (int i = 0; i <((JSONArray) myJSONResult.get("results")).length(); i++)
System.out.println(((JSONObject) ((JSONArray) myJSONResult.get("results")).get(i)).get("formatted_address")); // This is your final options.

JSON Parsing Error - String cannot be converted to JSONArray

I am having trouble in running my Android app. It is a simple activity meant to get data from a remote database via HTTP.
I am getting these two errors in log cat:
Error parsing to json on getJarrayFromString();
org.json.JSONException: Value Database of type java.lang.String cannot
be converted to JSONArray.
And:
Error at fillproductlist(): java.lang.NullPointerException
I am not very good at Java/Android and this is first time I am asking this question here. I am unable to understand what layer of my app the problem might be in (my Java code, PHP, or database code)?
Code snapshot:
private void fillProductList() {
if (utils.isInternet()
&& CustomHttpClient.isAddressOk(Utils.LINK_PRODUCTS)) {
final int from = bid.size();
final int nr = 5;
long sqliteSize = db.size(mySqlDatabase.TABLE_BOOKS);
if (from == 0) {
// we add the post variables and values for the request
postParameters.add(new BasicNameValuePair("from", String
.valueOf(0).toString()));
postParameters.add(new BasicNameValuePair("nr", String.valueOf(
nr).toString()));
} else {
postParameters.add(new BasicNameValuePair("from", String
.valueOf(from).toString()));
postParameters.add(new BasicNameValuePair("nr", String.valueOf(
nr).toString()));
}
postParameters.add(new BasicNameValuePair("title", titleSearch));
postParameters.add(new BasicNameValuePair("code", codeSearch));
postParameters.add(new BasicNameValuePair("module", moduleSearch));
if (sortOrder != null)
postParameters.add(new BasicNameValuePair("order", sortOrder));
if (sortType != null)
postParameters.add(new BasicNameValuePair("by", sortType));
task = new RequestTask("books", postParameters);
task.setOnTaskCompleted(new OnTaskCompletedListener() {
public void onTaskStarted() {
if (!rlLoading.isShown()) {
rlLoading.startAnimation(fadeIn());
rlLoading.setVisibility(View.VISIBLE);
}
IS_PRODUCTS_TASK = true;
}
public void onTaskCompleted(String result) {
try {
if (result != "") {
// Enter the remote php link
// we convert the response into json array
jarray = utils.getJarrayFromString(result);
int mysqlSize = (jarray.getJSONObject(0)
.getInt("numRows"));
Log.i(DEBUG, "From " + from + " to " + mysqlSize);
if (from <= mysqlSize) {
int rows;
// we check to see if there is 0
if (jarray.length() > 0) {
Log.i(DEBUG,
"From "
+ from
+ " to "
+ Math.floor(mysqlSize / nr)
* nr);
if (from + 5 <= Math.floor(mysqlSize / nr)
* nr) {
rows = jarray.length();
} else {
rows = mysqlSize % nr + 1;
Utils.IS_ENDED_PRODUCT_LIST = true;
}
ArrayList<String> list = new ArrayList<String>();
for (int i = 1; i < rows; i++) {
JSONObject row = jarray
.getJSONObject(i);
bid.add(row.getInt("bid"));
bTitle.add(row.getString("bTitle"));
bCode.add(row.getString("bCode"));
bPrice.add(row.getString("bPrice")
+ "£");
bDescription.add(row
.getString("bDescription"));
bModule.add(row.getString("bModule"));
bImage.add(Utils.PATH
+ row.getString("bImage"));
list.add(row.getString("bImage"));
// we check if this id already exists in the db, if it doesn't exists w create new one
if (!db.hasIDbooks(row.getInt("bid")))
db.createRowOnBooks(
row.getInt("bid"),
row.getString("bTitle"),
row.getString("bCode"),
row.getString("bPrice"),
row.getString("bDescription"),
row.getString("bModule"),
Utils.PATH
+ row.getString("bImage"),
row.getString("bSpecialOffer"),
row.getInt("bSpecialDiscount"),
row.getString("bDateAdded"));
Log.i(DEBUG,
row.getString("bDescription"));
}
new DownloadImages(list, bAdapter)
.execute();
}
}
postParameters.removeAll(postParameters);
} else {
Utils.IS_ENDED_PRODUCT_LIST = true;
if (rlLoading.isShown()) {
rlLoading.startAnimation(fadeOut());
rlLoading.setVisibility(View.INVISIBLE);
}
}
} catch (Exception e) {
Log.e(DEBUG,
"Error at fillProductList(): " + e.toString());
}
}
});
task.execute();
} else {
// if we are not connected on internet or somehow the link would not work, then we will take the rows stored in sqlite db
if (db.size(mySqlDatabase.TABLE_BOOKS) > 0) {
Cursor cursor = db.getBookssRows(mySqlDatabase.TABLE_BOOKS);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
bid.add(cursor.getInt(cursor
.getColumnIndex(mySqlDatabase.KEY_BID)));
bTitle.add(cursor.getString(cursor
.getColumnIndex(mySqlDatabase.KEY_BTITLE)));
bCode.add(cursor.getString(cursor
.getColumnIndex(mySqlDatabase.KEY_BCODE)));
bPrice.add(cursor.getString(cursor
.getColumnIndex(mySqlDatabase.KEY_BPRICE)) + "£");
bDescription.add(cursor.getString(cursor
.getColumnIndex(mySqlDatabase.KEY_BDESCRIPTION)));
bModule.add(cursor.getString(cursor
.getColumnIndex(mySqlDatabase.KEY_BMODULE)));
bImage.add(cursor.getString(cursor
.getColumnIndex(mySqlDatabase.KEY_BIMAGE)));
cursor.moveToNext();
}
bAdapter.notifyDataSetChanged();
Utils.IS_ENDED_PRODUCT_LIST = true;
}
}
}
In the OnTaskCompleted before
jarray = utils.getJarrayFromString(result);
add a log entry with
Log.i(DEBUG,result);
I am suspecting that you are getting a null value as result
if(result!="")
does not ensure a valid value.
Cheers

Categories

Resources