I have searched for solutions for a day and cannot find one that applies for my situation. I am sorry but I am new to JSON (self taught programmer) and I don't know what classes should I only post, so I will put in everything I have. I am getting the following error from LogCat:
Error parsing data org.json.JSONException: Value <?xml of type java.lang.String cannot be converted to JSONArray
Here is my class:
package com.example.mytravelbuddy;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.util.Log;
import android.view.Menu;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Itinerary extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
//JSON Parser
JSONParser jParser = new JSONParser();
//URL To Get Products
public static String url = "URL REMOVED"; //Removed my url since i was hosting online
//JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_ITEMS = "items";
private static final String TAG_ID = "ID";
private static final String TAG_LOCATION = "Location";
private static final String TAG_DESCRIPTION = "Description";
private static final String TAG_LATITUDE = "Latitude";
private static final String TAG_LONGITUDE = "Longitude";
private static final String TAG_TIME = "Time";
//Array list
ArrayList<HashMap<String, String>> itemList;
//Items JSONArray
JSONArray items = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starting_point);
itemList = new ArrayList<HashMap<String, String>>();
new LoadAllItems().execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.starting_point, menu);
return true;
}
class LoadAllItems extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Itinerary.this);
pDialog.setMessage("Loading items. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
//Building Params
List<NameValuePair> params = new ArrayList<NameValuePair>();
//Getting JSON String
JSONObject json = jParser.makeHttpRequest(url, "GET", params);
try{
//Getting array of items
Log.i("Error","ERROR 1"); //This error message is displayed
items = json.getJSONArray(TAG_ITEMS); //This is the line that is giving me a problem
Log.i("Error","ERROR 2"); //This error message is not displayed
//Looping through
for(int i = 0; i < items.length();i++){
JSONObject c = items.getJSONObject(i);
//Storing JSON item in variable
String location = c.getString(TAG_LOCATION);
String description = c.getString(TAG_DESCRIPTION);
String longitude = c.getString(TAG_LONGITUDE);
String latitude = c.getString(TAG_LATITUDE);
String time = c.getString(TAG_TIME);
//Creating HashMap
HashMap<String, String> map = new HashMap<String, String>();
//Put value in hashmap map
map.put(TAG_LOCATION, location);
map.put(TAG_DESCRIPTION, description);
map.put(TAG_LONGITUDE, longitude);
map.put(TAG_LATITUDE, latitude);
map.put(TAG_TIME, time);
itemList.add(map);
}
}catch(JSONException e){
e.printStackTrace();
}
return null;
}}
}
I found in which line I am getting the error by displaying error messages in LogCat.
Here is my PHP file that I am trying to get response from:
<?php
$user = "root";
$pass = "";
$database = "travel_buddy";
$server = "127.0.0.1";
mysql_connect($server, $user, $pass);
$db_found = mysql_select_db($database);
if($db_found){
echo"DB Found<br>";
}else{
echo"DB NOT Found<br>";
}
echo"Connection Established<br>";
get_details();
function get_details(){
$response = array();
$result = mysql_query("SELECT *FROM adventure");
if(mysql_num_rows($result)>0){
$response["items"] = array();
while($row = mysql_fetch_array($result)){
$info = array();
$product["ID"] = $row["ID"];
$product["Location"] = $row["Location"];
$product["Description"] = $row["Description"];
$product["Latitude"] = $row["Latitude"];
$product["Longitude"] = $row["Longitude"];
$product["Time"] = $row["Time"];
array_push($response["items"], $product);
}
$response["success"] = 1;
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No Information Found";
echo json_encode($response);
}
}
?>
Here is my JSON Response:
{
"items": [
{
"ID": "1",
"Location": "TEST",
"Description": "TEST DESC",
"Latitude": "1",
"Longitude": "2",
"Time": "3:00"
},
{
"ID": "2",
"Location": "TEST2",
"Description": "TEST2 DESC",
"Latitude": "1",
"Longitude": "1",
"Time": "7:00"
},
{
"ID": "3",
"Location": "TEST3",
"Description": "TEST3 DESC",
"Latitude": "3",
"Longitude": "4",
"Time": "12:00"
}
],
"success": 1
}
Here is my JSON Parser Class:
package com.example.mytravelbuddy;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Any help would be really helpful, possible explaining why I have this error so I don't repeat it again.
The php page is echoing other strings instead of json(only).
I strongly recommend using Gson to parse your JSON response.
For the example above the class would look like this:
public class ItemList {
List<Item> items;
}
and Item would be:
public class Item {
private String ID;
private String Location;
private String Description;
private String Longitude;
private String Latitude;
private String Time;
}
Then, parsing becomes absolutely trivial. Put gson-2.2.4.jar in your libs folder, and then just do this:
Gson GSON = new Gson();
ItemList itemList = GSON.fromJson(json_string_here, ItemList.class);
That's it. You have a first class java object parsed from JSON. Easy and powerful.
This can cause problem
mysql_connect($server, $user, $pass);
$db_found = mysql_select_db($database);
if($db_found){
echo"DB Found<br>";
}else{
echo"DB NOT Found<br>";
}
echo"Connection Established<br>";
your service is echoing other things.
It should only be echo'ing the JSON.
Instead such information could be logged
mysql_connect($server, $user, $pass);
$db_found = mysql_select_db($database);
if($db_found){
error_log("DB Found<br>");
}else{
error_log("DB NOT Found<br>)";
}
error_log("Connection Established<br>");
Also the header is important to have:
header("Content-Type: application/json");
Place it at the top of your script.
EDIT:
I just tried your code, and I can parse the JSON without error.
Most likely your PHP server is sending XML for some reason. You need to check that script again.
It could even be error reporting messing your encoded json, Log any error but only echo the JSON .
Hope this helps.
Related
I am making an app using the Kitsu API. Here in this moment I have a fragment that allows me to search different anime using the api to get information such as name, synopsis, etc. After parsing the information I proceed to go back to my main activity to pass it to my new fragment, but it crashes the moment I initialize the method to go back to my main activity. My question is how do I use a fragment to read a JSON with a background class using ASYNCTASK and display it in a new fragment?
I have noticed that it jumps around a lot from my fragment, in an activity different from my main, to a class running in the background, to my main, to my fragment. Below are images of my code. Thank you very much.
Search fragment code, Main Activity search related methods, Search results background tasks, Search Results Fragment. To clarify It stops before I get to the string I labeled crashpoint and doesn't make it to the search results fragment. I felt like it would be handy to have that bit of code in there. Here is the error I get with my code when I run it.
You don't need to create a new fragment after reading JSON. Just to post an simple code that read JSON with async task:
package com.example.compsci_734t;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.zip.GZIPInputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class People extends Activity{
ArrayList<String> items = new ArrayList<String>();
static InputStream is = null;
//private static String url = "";
//private static String url = "http:...";
private static String url = "http....";
//URL requestUrl = new URL(url);
JSONArray people = null;
private static final String TAG_COURSES = "Courses";
static JSONObject jObj = null;
static String json = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.people);
new MyTasks().execute();
}
private class MyTasks extends AsyncTask<URL, Void, JSONObject> {
#Override
protected JSONObject doInBackground(URL... urls) {
// return loadJSON(url);
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
//HttpPost httpPost = new HttpPost(url);
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
/*BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);*/
InputStream inputStream = is;
GZIPInputStream input = new GZIPInputStream(inputStream);
InputStreamReader reader = new InputStreamReader(input);
BufferedReader in = new BufferedReader(reader);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = in.readLine()) != null) {
sb.append(line);
//System.out.println(line);
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
JSONArray people = new JSONArray(json);
//JSONArray people = new JSONArray(json);
for (int i = 0; i < people.length(); i++) {
//System.out.println(courses.getJSONObject(i).toString());
JSONObject p = people.getJSONObject(i);
// Storing each json item in variable
String person_id = p.getString("someString1");
items.add(person_id);
/*Log.v("--", "People: \n" + "\n UPI: " + person_id);*/
}
//jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
protected void onPostExecute(JSONObject json) {
ListView myListView = (ListView)findViewById(R.id.peopleList);
myListView.setAdapter(new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, items));
}
}
The sample code was taken from this answer.
I created a class for my android application that connects to mysql database using json.. note that the php code getNews.php is tested and it responds with the required data in json format properly. And note that i only want to get an array containing the data with this class ArrayReceiver.java ... it isn't working though... can anyone check the code please.
ArrayReceiver.java
package com.example.batoul.uptodate4;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class ArrayReceiver extends AsyncTask<String, Integer, String> {
List<Article> a=new ArrayList<Article>();
String url="192.168.11.8/utd/getNews.php";
Boolean error = false;
private ProgressDialog pDialog;
Boolean success = false;
String msg = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
}
public List<Article> getA() {
return a;
}
#Override
protected String doInBackground(String... arg) {
publishProgress(2);
// agendaArrayList = new ArrayList<>();
List<NameValuePair> params = new ArrayList<>();
try {
// params.add(new BasicNameValuePair("notActivated", "false"));
ServiceHandler serviceClient = new ServiceHandler();
String json = serviceClient.makeServiceCall(url,
ServiceHandler.POST, params);
// Log.e("aaa ", "> " + ServiceHandler.url);
// Log.d("Create Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
//int catObj22 = jsonObj.getInt("success");
// if (catObj22 == 1) {
JSONArray titles = jsonObj.getJSONArray("title");
for (int i = 0; i < titles.length(); i++) {
String catObj = (String) titles.get(i);
Article obj = new Article(0,"");
obj.setTitle(catObj);
a.add(obj);
}
success = true;
} else {
success = false;
}
// }
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
} catch (Exception e) {
error = true;
return null;
}
Log.e("aaa ", " success");
return "success";
}
#Override
protected void onProgressUpdate(Integer... values) {
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// if (pDialog.isShowing()) {
// pDialog.dismiss();
// }
// Toast.makeText(TravelsActivity.this, s, Toast.LENGTH_LONG).show();
if (success) {
// for (int i = 0; i < travelsArr.size(); i++) {
// new getPic().execute("" + i);
// }
//ListAdapterClass adapter = new ListAdapterClass( ArticleArr,view.getContext());
//SubjectListView.setAdapter(adapter);
}
}
}
ServiceHandler.java
package com.example.batoul.uptodate4;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
public class ServiceHandler {
static InputStream is = null;
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public static String url ,u;
public ServiceHandler() {
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
this.url =url +"?" + paramString;
}
HttpGet httpGet = new HttpGet(this.url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
response = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error: " + e.toString());
}
return response;
}
}
getNews.php :
<?php
$response = array();
$db = mysqli_connect('localhost', 'root', '', 'utd1_db');
$query = " SELECT * FROM `article`";// need change
$result = $db->query($query);
if ($result->num_rows > 0) {
$title = array();
while ($row = $result->fetch_assoc()) {
array_push($title, $row["title"]);// need change
}
$response["success"] = 1;
$response["title"] = $title;
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "Nothing found";
echo json_encode($response);
}
?>
I am beginner to JAVA with API.
The response That I'm getting during my program as follows:
*Object Response:
{
"statusLine":{
"reasonPhrase":"OK",
"protocolVersion":{},
"statusCode":200
},
"protocolVersion":{},
"locale":"en_IN",
"entity":{
"repeatable":false,
"content":{}
}
}
Exception Occured. JSONArray initial value should be a string or collection or array.*
Unable to get full complete values in the results. I am getting only header details.
Please help me in get complete details from the API. using JAVA
package IOT;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;
import org.json.JSONArray;
public class HttpPostWithBody {
public static void main(String args[]) {
String Message = "6f2159f998";
try {
new HttpPostWithBody().sendJSONData(Message);
} catch (Exception E) {
System.out.println("Exception Occured. " + E.getMessage());
}
}
public String sendJSONData(String message) throws Exception {
Map< String, Object> jsonValues = new HashMap< String, Object>();
{
jsonValues.put("thing_key", message);
jsonValues.put("from", "2016/08/29 16:55:00");
jsonValues.put("to", "2016/08/29 17:05:00");
jsonValues.put("time_zone", "Mumbai");
jsonValues.put("time_format", "str");
jsonValues.put("per", 50);
//jsonValues.put("metrics", "1st data");
}
JSONObject json = new JSONObject(jsonValues);
String url = "https://api.datonis.io/api/v3/datonis_query/thing_data";
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setHeader("Content-Type", "application/json");
post.setHeader("Accept", "application/json");
post.setHeader("X-Auth-Token", "YZ0Sa7IfpdtAXQQ-2CNeAg");
StringEntity entity = new StringEntity(json.toString(), "UTF8");
System.out.println("This is the entity: " + entity);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(json.toString());
String prettyJsonString = gson.toJson(je);
System.out.println("Pretty Json: " + prettyJsonString);
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(entity);
//this is your response:
HttpResponse response = client.execute(post);
JSONObject jo = new JSONObject(response);
System.out.println("Object Response: " + jo);
JSONArray ab = new JSONArray(response);
JSONObject cd = ab.getJSONObject(0);
System.out.println("Array Response: " + cd);
System.out.println("Array Response: " + jo.getJSONArray("6f2159f998"));
System.out.println("Connection Status: " + response.getStatusLine());
return response.getStatusLine().toString();
}
}
First of all, you must confirm that the response data is valid JSON data. With some JSON check sites, you can easily find that your json is valid. After format:
{
"statusLine": {
"reasonPhrase": "OK",
"protocolVersion": {},
"statusCode": 200
},
"protocolVersion": {},
"locale": "en_IN",
"entity": {
"repeatable": false,
"content": {}
}
}
Now, the problem is that this JSON data is a JSON Object, not a JSON Array. So, the sentence JSONArray ab = new JSONArray(response); will cause an error. If you want to get statusLine result, you can use the code below:
JSONObject jo = new JSONObject(response);
String statusLine = jo.getJSONObject("statusLine").toString();
I am getting java.lang.NullPointerException when I run this. Does anyone know why this is happening and how I can fix it?
Please take a look at my code and let me know if you have any suggestions.
{"begin":[{"id":1,"name":"Andy","size":1}],"open":[{"id":1,"name":"Tom","size":2}]}
Fragment
public class MainFragment extends Fragment {
public MainFragment() {}
//URL to get JSON Array
private String url = "URL...";
//JSON Node Names
private static final String TAG_BEGIN = "begin";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_SIZE = "size";
JSONArray begin = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
new JSONParse().execute();
return rootView;
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(HomeActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array
begin = json.getJSONArray(TAG_BEGIN);
JSONObject c = begin.getJSONObject(0);
// Storing JSON item in a Variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String size = c.getString(TAG_SIZE);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
JSONParser
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Error:
E/JSON Parser﹕ Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
FATAL EXCEPTION: main
java.lang.NullPointerException
at
...$MainFragment$JSONParse.onPostExecute(MainActivity.java:399)
at
...$MainFragment$JSONParse.onPostExecute(MainActivity.java:373)
Which is...
begin = json.getJSONArray(TAG_BEGIN);
and...
private class JSONParse extends AsyncTask<String, String, JSONObject> {
EDIT (Answer)
JSONParser
Inside of JSONParser I changed my code to this:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpUriRequest request = new HttpGet(url);
request.setHeader("Accept", "application/json");
HttpResponse response = httpClient.execute(request);
HttpEntity httpEntity = response.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Inside of onPostExecute
JSONArray begin = json.getJSONArray(TAG_BEGIN);
for (int i = 0; i < begin(); i++) {
try {
JSONObject b = = begin(i);
String id = b.getString(TAG_ID);
String name = b.getString(TAG_NAME);
String size = b.getString(TAG_SIZE);
} catch (JSONException e) {
e.printStackTrace();
}
}
First make sure your JSONObject is not null. Then slowly transverse line by line based off the type.
JSONArray begin = json.getJSONArray(TAG_BEGIN);
Then possibly do something like this?
for(int n = 0; n < begin.length(); n++)
{
JSONObject object = begin.getJSONObject(n);
// query through the array
String id = object.getString(TAG_ID);
String name = object.getString(TAG_NAME);
String size = object.getString(TAG_SIZE);
//Now do something with the strings
}
Of course you'd do the same thing with the TAG_OPEN. Let me know if this works, I'll gladly help as much as possible.
the error shows that the return string of you http request is not only the json data
something like <!DOCTYPE are includeed
please check you are request the right url, and the server handle the request correctly
you can use your browser visit the url you request and check the return result
I am not using a fragment but here is similar solution.
Change your url and key values for retrieving values from json. I didn't have your url so i used some other. Please check it out. Same concept except i am not using fragments but this json parsing code works just fine.
First of all, you have to deal with the network on main thread exception
Add:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
in your class,
and
ADD this to ManiFestFile:
<uses-permission android:name="android.permission.INTERNET"/>
MainActivity.Java
package com.example.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Making HTTP request
String url = "http://api.androidhive.info/contacts/";
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting JSON Array
JSONArray begin = json.getJSONArray("contacts");
JSONObject c = begin.getJSONObject(0);
// Storing JSON item in a Variable
String id = c.getString("id");
String name = c.getString("name");
String size = c.getString("email");
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
JSONParser.Java
package com.example.test;
import android.os.StrictMode;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
I am getting this error in my LogCat:
Error parsing data org.json.JSONException: Value of type java.lang.String cannot be converted to JSONArray
Below are every file I could show you! Please let me know the problem and its solution ASAP. What I guess is:
1. Maybe the is problem is with parsing data in JSON array.
2. Maybe the problem is with my php api, I think I am not properly encoding the json_encode because it gives me RAW JSON, like every thing in one line.
as below
[{"uid":"120","name":"MyFirstName MyLastName"}]
Please also let me know, their is some difference in working of both format, 1. Raw JSON and 2. Intented Json
below is the intented json format
[
{
"uid":"120",
"name":"MyFirstName MyLastName"
}
]
Here is the JSONUseActivity.java
package com.example.oncemore;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import com.example.oncemore.CustomHttpClient;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class JSONUseActivity extends Activity {
EditText email,password;
Button submit;
TextView tv; // TextView to show the result of MySQL query
String returnString; // to store the result of MySQL query after decoding
// JSON
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork() // StrictMode is
// most commonly
// used to catch
// accidental
// disk or
// network
// access on the
// application's
// main thread
.penaltyLog().build());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jsonuse);
email = (EditText) findViewById(R.id.email);
password = (EditText) findViewById(R.id.password);
submit = (Button) findViewById(R.id.submitbutton);
tv = (TextView) findViewById(R.id.showresult);
// define the action when user clicks on submit button
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// declare parameters that are passed to PHP script i.e. the
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
// define the parameter
postParameters.add(new BasicNameValuePair("email",email.getText().toString()));
postParameters.add(new BasicNameValuePair("password",password.getText().toString()));
String response = null;
// call executeHttpPost method passing necessary parameters
try {
response = CustomHttpClient.executeHttpPost(
"http://mywebsite.com/android/api.php",
postParameters);
// store the result returned by PHP script that runs MySQL
// query
String result = response.toString();
// parse json data
try {
returnString = "";
//I think the line below is creating some problem
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag",
"id: " + json_data.getInt("uid")+", name: " + json_data.getString("name"));
// Get an output to the screen
returnString += "\n" + json_data.getString("name")
+ " -> " + json_data.getInt("uid");
}
}catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
try {
tv.setText(returnString);
}
catch (Exception e) {
Log.e("log_tag", "Error in Display!" + e.toString());
;
}
}
catch (Exception e) {
Log.e("log_tag",
"Error in http connection!!" + e.toString());
}
}
});
}
}
Here is the CustomHttpClient.java
package com.example.oncemore;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import android.util.Log;
public class CustomHttpClient {
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
/** Single instance of our HttpClient */
private static HttpClient mHttpClient;
/**
* Get our single instance of our HttpClient object.
*
* #return an HttpClient object with connection parameters set
*/
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
/**
* Performs an HTTP Post request to the specified url with the specified
* parameters.
*
* #param url
* The web address to post the request to
* #param postParameters
* The parameters to send via the request
* #return The result of the request
* #throws Exception
*/
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
Log.e("log_tag", "Error converting result "+e.toString());
e.printStackTrace();
}
}
}
}
/**
* Performs an HTTP GET request to the specified url.
*
* #param url
* The web address to post the request to
* #return The result of the request
* #throws Exception
*/
public static String executeHttpGet(String url) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
Log.e("log_tag", "Error converting result "+e.toString());
e.printStackTrace();
}
}
}
}
}
Here is the api.php
<?php
require_once("../contactdb.php");
$myusername=$_REQUEST["email"];
$mypassword=$_REQUEST["password"];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT uid,name FROM u_info WHERE email='".$myusername."' AND password ='".$mypassword."'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
if($count==1){
while($row=mysql_fetch_assoc($result))
$output[]=$row;
echo json_encode($output);
mysql_close();
}else{
echo "Error Occured!";
}
?>
Finally, When I goto browser and write like this
http://mywebsite.com/android/api.php?email=myname#yahoo.com&password=1234
I got this json array!
[{"uid":"120","name":"MyFirstName MyLastName"}]
So Far I google, I have found different formats of json array! I found everywhere Intented Json. My json array is currently in Raw Json format. I don't find anywhere how to convert Raw Json format into Intented Json format.
Thanks in advance guys!
Any help would be appreciated! If possible, please provide the correct code!
That is NOT valid JSON syntax:
{
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}
Is Valid.
Note: This is also valid:
{"employees": [ { "firstName":"John" , "lastName":"Doe" }, { "firstName":"Anna" , "lastName":"Smith" }, { "firstName":"Peter" , "lastName":"Jones" } ] }
The syntax structure is the important part, not the formatting in terms of indentation.
As otherwise said, to use the fomat you're returning, you need to cut the substring from the response, i.e get rid of the square brackets surrounding the braces.
In PHP I create a proper json response as follows:
// array for JSON response
$response = array();
$response["apps"] = array();
$apps = array();
$apps["name"] = $row["name"];
$apps["package"] = $row["package"];
$apps["version"] = $row["version"];
$apps["dateversion"] = $row["dateversion"];
array_push($response["apps"], $apps);
$response["success"] = 1;
echo json_encode($response);
This basically gives
{ "success":"1", "apps":{["name":"NAME", "package":"PACKAGE", "version":"VERSION", "dateversion":"DATEVERSION"]}}
which can be parsed correctly by any of the abundant examples of JSON classes which you can make use of. Hacking and using substring to manually remove the first N characters is NOT good practice...