I am getting error when I test below code in Android phone:
org.json.JSONException:
Value <!-- of type java.lang.String cannot be converted to JSONArray
My PHP Code as follows: I have used prepare statement
<?php
define('__ROOT__', dirname(dirname(__FILE__)));
require_once(__ROOT__.'/public_html/Config.php');
// Connecting to mysql database
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
// json response array
$response = array();
if (isset($_POST['treecondition'])) {
// receiving the post params
$treecondition = $_POST['treecondition'];
// get the tree details for google map marker
if($stmt = $mysqli->prepare("SELECT treeid, treelatitude, treelongitude FROM tree WHERE treecondition = ?")){
$stmt->bind_param("s", $treecondition);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($treeid, $treelatitude, $treelongitude);
if ($stmt->num_rows > 0) {
while($tree = $stmt->fetch()) {
$response['treeid'] = $treeid;
$response['treelatitude'] = $treelatitude;
$response['treelongitude'] = $treelongitude;
echo json_encode($response);
}
}
} else {
// user is not found with the credentials
$response["error"] = TRUE;
$response["error_msg"] = "Tree list view credentials are wrong. Please try again!";
echo json_encode($response);
}
$mysqli->close();
}
My Android volley code as follows: Used Jsonarray
public void onResponse(String response) {
Log.d(TAG, "Location Response: " + response.toString());
hideDialog();
try {
JSONArray jTreeList = new JSONArray(response);
// boolean error = jObj.getBoolean("error");
ArrayList<LatLng> list = new ArrayList<LatLng>();
// Check for error node in json
for (int i = 0; i < jTreeList.length(); i++) {
JSONObject location = jTreeList.getJSONObject(i);
String treeid = location.getString("treeid");
// String treespecies = location.getString("treespecies");
Double treelatitude = location.getDouble("treelatitude");
Double treelongitude = location.getDouble("treelongitude");
LatLng latlng = new LatLng(treelatitude, treelongitude);
list.add(new LatLng(treelatitude, treelongitude));
// Create a heat map tile provider, passing it the latlngs of the police stations.
HeatmapTileProvider provider = new HeatmapTileProvider.Builder().data(list).build();
// Add a tile overlay to the map, using the heat map tile provider.
mMap.addTileOverlay(new TileOverlayOptions().tileProvider(provider));
// Moving CameraPosition to last clicked position
mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
// Setting the zoom level in the map on last position is clicked
mMap.animateCamera(CameraUpdateFactory.newLatLng(latlng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(3));
}
// Launch
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getActivity().getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getActivity().getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("search", search);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
Please look of my error after the output of program
11-20 14:32:38.450 23138-23138/com.example.bharat.plantnow D/ClusterMapFragment﹕ Location Response:
<!-- Hosting24 Analytics Code -->
<script type="text/javascript" src="http://stats.hosting24.com/count.php"></script>
<!-- End Of Analytics Code -->
11-20 14:32:38.450 23138-23138/com.example.bharat.plantnow W/System.err﹕ org.json.JSONException: Value <!-- of type java.lang.String cannot be converted to JSONArray
11-20 14:32:38.450 23138-23138/com.example.bharat.plantnow W/System.err﹕ at org.json.JSON.typeMismatch(JSON.java:111)
11-20 14:32:38.450 23138-23138/com.example.bharat.plantnow W/System.err﹕ at org.json.JSONArray.<init>(JSONArray.java:96)
11-20 14:32:38.450 23138-23138/com.example.bharat.plantnow W/System.err﹕ at org.json.JSONArray.<init>(JSONArray.java:108)
11-20 14:32:38.450 23138-23138/com.example.bharat.plantnow W/System.err﹕ at com.example.bharat.plantnow.Maps.ClusterMapFragment$2.onResponse(ClusterMapFragment.java:143)
11-20 14:32:38.450 23138-23138/com.example.bharat.plantnow W/System.err﹕ at com.example.bharat.plantnow.Maps.ClusterMapFragment$2.onResponse(ClusterMapFragment.java:131)
11-20 14:32:38.450 23138-23138/com.example.bharat.plantnow W/System.err﹕ at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
11-20 14:32:38.450 23138-23138/com.example.bharat.plantnow W/System.err﹕ at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
11-20 14:32:38.450 23138-23138/com.example.bharat.plantnow W/System.err﹕ at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
11-20 14:32:38.450 23138-23138/com.example.bharat.plantnow W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:739)
11-20 14:32:38.450 23138-23138/com.example.bharat.plantnow W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:95)
11-20 14:32:38.450 23138-23138/com.example.bharat.plantnow W/System.err﹕ at android.os.Looper.loop(Looper.java:135)
11-20 14:32:38.450 23138-23138/com.example.bharat.plantnow W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5292)
11-20 14:32:38.450 23138-23138/com.example.bharat.plantnow W/System.err﹕ at java.lang.reflect.Method.invoke(Native Method)
11-20 14:32:38.450 23138-23138/com.example.bharat.plantnow W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:372)
11-20 14:32:38.450 23138-23138/com.example.bharat.plantnow W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
11-20 14:32:38.451 23138-23138/com.example.bharat.plantnow W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
The Json response you receive is not formatted as JSON it contains invalid character '<!--' thats why your jsonparser throw an Jsonexception.
Try to save your php file in cp1252 Encoding
Open your php file in Eclipse
Edit> Set Encoding then set to cp1252
save
Related
I am trying to read the valid JSON response but getting the error String cannot be converted to JSONObject don't know why.?
android code
String sendParam = sendParams[0];
byte[] sendParamsByte = sendParam.getBytes("UTF-8");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(sendParamsByte.length));
conn.setDoOutput(true);
conn.getOutputStream().write(sendParamsByte);
InputStream responseInputStream = conn.getInputStream();
StringBuffer responseStringBuffer = new StringBuffer();
byte[] byteContainer = new byte[1024];
for (int i; (i = responseInputStream.read(byteContainer)) != -1; ) {
responseStringBuffer.append(new String(byteContainer, 0, i));
}
JSONObject response = new JSONObject(responseStringBuffer.toString());
My JSON Response -
{
"firstOne":"XXXXXXXXXX",
"secOne":"XXXXXXXXXXXXXXXXXX",
"thrOne":"XXXXXXXXXXXXX",
"final":"XXXXXXXXXXXXXXX"
}
error log -
org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
06-02 12:09:13.975 2310-3800/X.x W/System.err: at org.json.JSON.typeMismatch(JSON.java:111)
06-02 12:09:13.975 2310-3800/X.x W/System.err: at org.json.JSONObject.<init>(JSONObject.java:159)
06-02 12:09:13.975 2310-3800/X.x W/System.err: at org.json.JSONObject.<init>(JSONObject.java:172)
Any idea..?
Try this
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
}
you can get JSONObject from sb.toString().trim().
good luck
conn.setRequestProperty("Content-Length","application/json;charset=UTF-8");
Change to this.
I've an error that occur when I try to fix it but it doesn't fix.
JSONArray application_band =jsonResponse.getJSONArray("banda");
String [] list = new String[application_band.length()];
for(int i = 0; i<application_band.length(); i++){
list[i] = application_band.getString(i);
}
And this when I create the intent:
if (hurado_section ==1) {
Intent intent = new Intent(LoginActivity.this, CategoryOneActivity.class);
intent.putExtra("hurado_name", hurado_name);
intent.putExtra("hurado_id", hurado_id);
intent.putExtra("hurado_section", hurado_section);
intent.putExtra("application_band",list);
LoginActivity.this.startActivity(intent);
}
Error:
07-20 16:47:10.781 27808-27808/com.example.cursoft.scoringsystemseu W/System.err: org.json.JSONException: No value for banda
What could be the problem?
So I came over this tutorial right here https://www.youtube.com/watch?v=mdAXqQoADt8 (last part of it) everything is working absolutly fine when I'm refering to my local server.
Now I switched it up to an online server/database to test if it works the same way. Also here everything is working fine except of the json response in the onPostExecute Method. I'm getting no messages from registration or login anymore. I really can't figure out how to solve this problem and I don't understand why it doesn't work the same way when I switch it up to an online server/database.
Hope anyone here can help me with that. I'll post some code below, maybe somebody can figure it out without doing the whole tutorial.
Thankful for any help!
#Override
protected void onPostExecute(String json) {
try {
Log.d("JSON-String",json+"");
progressDialog.dismiss();
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
JSONObject JO = jsonArray.getJSONObject(0);
String code = JO.getString("code");
String message = JO.getString("message");
if (code.equals("reg_true"))
{
showDialog("Registrierung erfolgt.", message, code);
}
else if (code.equals("reg_false"))
{
showDialog("Registrierung fehlgeschlagen", message, code);
}
else if(code.equals("login_true"))
{
Intent intent = new Intent(activity, Talkscreen.class); //SPÄTER WIEDER RAUSNEHMEN
activity.startActivity(intent);
activity.finish();
}
else if (code.equals("login_false"))
{
showDialog("Login fehlgeschlagen", message,code);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
It seems you're getting wrong JSON string from the server.
2905-2905/com.appmac.ron.testapp W/System.err: org.json.JSONException: Value <h3>DB< of type java.lang.String cannot be converted to JSONObject
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at org.json.JSON.typeMismatch(JSON.java:111)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at org.json.JSONObject.<init>(JSONObject.java:160)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at org.json.JSONObject.<init>(JSONObject.java:173)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at com.appmac.ron.testapp.ServerKlassen.BackgroundTask.onPostExecute(BackgroundTask.java:172)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at com.appmac.ron.testapp.ServerKlassen.BackgroundTask.onPostExecute(BackgroundTask.java:39)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at android.os.AsyncTask.finish(AsyncTask.java:651)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at android.os.AsyncTask.-wrap1(AsyncTask.java)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at android.os.Looper.loop(Looper.java:148)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5417)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at java.lang.reflect.Method.invoke(Native Method)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
04-23 12:35:53.172 2905-2905/com.appmac.ron.testapp W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Above error shows that String could not be converted to JSON object.
Check the server code for any bug.
My problem is the next ...
Im trying to display a image, that is defined in my phpmyadmin, and hosted in the correspondient folder, but the bitmapfactory returns nothin.
MY JAVA:
if (success == 1) {
// successfully received product details
JSONArray productObj = json.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// Edit Text
txtName = (EditText) findViewById(R.id.inputName);
txtPrice = (EditText) findViewById(R.id.inputPrice);
txtDesc = (EditText) findViewById(R.id.inputDesc);
// display product data in EditText
txtName.setText(product.getString(TAG_NAME));
txtPrice.setText(product.getString(TAG_PRICE));
txtDesc.setText(product.getString(TAG_DESCRIPTION));
//imageview
imageView1 = (ImageView)findViewById(R.id.imageView1);
imagen_url=product.getString("TAG_IMAGEN");
String imagen_url2=product.optString("TAG_IMAGEN");
byte[] encodeByte = Base64.decode(imagen_url, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
imageView1.setImageBitmap(bitmap);
AND THE PHP
$product["imagen"] = base64_encode($result["imagen"]);
It returns a error:
04-10 04:12:32.344: W/System.err(1424): org.json.JSONException: No value for TAG_IMAGEN
04-10 04:12:32.364: W/System.err(1424): at org.json.JSONObject.get(JSONObject.java:355)
04-10 04:12:32.364: W/System.err(1424): at org.json.JSONObject.getString(JSONObject.java:515)
04-10 04:12:32.374: W/System.err(1424): at com.example.androidhive.EditProductActivity$GetProductDetails$1.run(EditProductActivity.java:180)
04-10 04:12:32.374: W/System.err(1424): at android.os.Handler.handleCallback(Handler.java:733)
04-10 04:12:32.374: W/System.err(1424): at android.os.Handler.dispatchMessage(Handler.java:95)
04-10 04:12:32.404: W/System.err(1424): at android.os.Looper.loop(Looper.java:136)
04-10 04:12:32.404: W/System.err(1424): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-10 04:12:32.404: W/System.err(1424): at java.lang.reflect.Method.invokeNative(Native Method)
04-10 04:12:32.414: W/System.err(1424): at java.lang.reflect.Method.invoke(Method.java:515)
04-10 04:12:32.414: W/System.err(1424): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-10 04:12:32.414: W/System.err(1424): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-10 04:12:32.434: W/System.err(1424): at dalvik.system.NativeStart.main(Native Method)
The problem was the TAG, if I put :
imagen_url=product.getString("imagen");
works, but with not :
imagen_url=product.getString("TAG_IMAGEN");
I dont know why, but with this change, it works fine!
Here´s the JSON that my php file delivers:
[{"id":"408","punktezahl":"15","name":"testname","email":"hsksjs","datum":"24.01.14 17:11","wohnort":"Vdhdhs","newsletter":"J"}]
When I try to access the JSON Object like this
public void connect(){
System.out.println("%%%%%%%%%%%%%%%%%1" );
Thread t = new Thread(){
#Override
public void run() {
try {
System.out.println("%%%%%%%%%%%%%%%%%2" );
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(params, 0);
HttpClient httpClient = new DefaultHttpClient(params);
String urlString = "http://url";
//prepare the HTTP GET call
HttpGet httpget = new HttpGet(urlString);
//get the response entity
HttpEntity entity = httpClient.execute(httpget).getEntity();
System.out.println("%%%%%%%%%%%%%%%%%3" );
if (entity != null) {
//get the response content as a string
String response = EntityUtils.toString(entity);
//consume the entity
entity.consumeContent();
// When HttpClient instance is no longer needed, shut down the connection manager to ensure immediate deallocation of all system resources
httpClient.getConnectionManager().shutdown();
//return the JSON response
JSONObject parentObject = new JSONObject(response);
JSONObject userDetails = parentObject.getJSONObject("output");
String name = userDetails.getString("name");
System.out.println("HEEEEEEEEEEEEEEEEEEEEEEEEEEEE" + name);
}
}catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
}
I get the following error:
01-24 18:18:21.746: W/System.err(20673): org.json.JSONException: Value [{"id":"408","datum":"24.01.14 17:11","punktezahl":"15","email":"hsksjs","newsletter":"J","wohnort":"Vdhdhs","name":"testname"}] of type org.json.JSONArray cannot be converted to JSONObject
01-24 18:18:21.746: W/System.err(20673): at org.json.JSON.typeMismatch(JSON.java:111)
01-24 18:18:21.746: W/System.err(20673): at org.json.JSONObject.<init>(JSONObject.java:159)
01-24 18:18:21.746: W/System.err(20673): at org.json.JSONObject.<init>(JSONObject.java:172)
01-24 18:18:21.746: W/System.err(20673): at com.wuestenfest.jagdenwilli.Highscore_zeigen$1.run(Highscore_zeigen.java:82)
Where´s my mistake?
Your response is a JSONArray not a JSOnObject.
So change
JSONObject parentObject = new JSONObject(response);
to
JSONArray jsonarray = new JSONArray(response);
Your JSON
[ // json array node
{ // jsson onject npode
"id": "408",
"punktezahl": "15",
"name": "testname",
"email": "hsksjs",
"datum": "24.01.14 17:11",
"wohnort": "Vdhdhs",
"newsletter": "J"
}
]
I do not see any json object output either in the above json. So
JSONObject userDetails = parentObject.getJSONObject("output");
is also wrong.
Parsing
JSONArray jsonarray = new JSONArray(response);
JSONObject jb =(JSONObject) jsonarray.getJSONObject(0);
String name= jb.getString("name");
The problem is just as the exception describes: you are trying to parse your response object into a JSONObject, but it is actually a JSONArray (as seen by the square brackets). In stead, parse it as a JSONArray, and get the first element from the array, which would be your desired JSONObject.