Rogerio Setubal Rogerio Setubal - 6 months ago 176
JSON Question

JSON error: java.lang.String cannot be converted to JSONObject

I'm developing an android app and I'm trying to use Volley Library. The problem that I can't solve is about the JSON. I checked my php file, the result and the Java code but I'm still getting the same error.

The interesting part is that VolleyLog doesn't show an error message but, Log, does.

E/Volley﹕ [1] 2.onErrorResponse: VOLLEY_ERROR


and

E/LOG﹕ Error: org.json.JSONException: Value You of type java.lang.String cannot be converted to JSONObject


That's my PHP code:

<?php
# Inform which carachters type will be used.
header('Content-Type: text/html; charset=utf-8');
// array for JSON response
$response = array();

// include db connect class

require_once ('../conn.php');
require_once('pClass.php');

error_reporting( E_ALL );

// connecting to db
$db = new DB_CONNECT();

//Setting to UTF8
mysql_query("SET NAMES 'utf8_general_ci'");
mysql_query('SET character_set_connection=utf8_general_ci');
mysql_query('SET character_set_client=utf8_general_ci');
mysql_query('SET character_set_results=utf8_general_ci');
mysql_query('SET CHARACTER SET utf8');

$ff_error = "ERROR";
$arrPOI["arrPOI"] = array();
$poi=new POI();

if (isset($_REQUEST["ff_01"]))
{
//Execute the query
$ff_01 = $_REQUEST['ff_01'];
$return = mysql_query($ff_01) or die(mysql_error());

// check for empty result
if (mysql_num_rows($return) > 0) {
while ($row = mysql_fetch_array($return)) {
$poi->setPOIId($row["intPointId"]);
$poi->setPOIName($row["vchPointName"]);
$poi->setPOIImage($row["vchAwesomeFont"]);
$poi->setStatusId($row["intStatusId"]);
$poi->setLanguageId($row["intLanguageId"]);

// push single category into final response array
array_push($arrPOI["arrPOI"], $poi->getPOIData());
}
// echoing JSON response
header('Content-Type: application/json');
echo json_encode($arrPOI, JSON_NUMERIC_CHECK | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_UNICODE | JSON_NUMERIC_CHECK | JSON_NUMERIC_CHECK);
} else {
//No data found
array_push($arrPOI["arrPOI"], $poi->getPOIData());

// echo no users JSON
header('Content-Type: application/json');
echo json_encode($arrPOI);
}
} else {
//ERROR
array_push($arrPOI["arrPOI"], $poi->getPOIData());

//Echo
header('Content-Type: application/json');
echo json_encode($arrPOI);
}
?>


The PHP result:

{"arrPOI":[{"intPOIId":1,"strPOIName":"Cinema","strPOIImage":"fa-film","intStatusId":1,"intLanguageId":1},{"intPOIId":2,"strPOIName":"Teatro","strPOIImage":"fa-smile-o|fa-frown-o","intStatusId":1,"intLanguageId":1},{"intPOIId":3,"strPOIName":"Restaurante","strPOIImage":"fa-cutlery","intStatusId":1,"intLanguageId":1},{"intPOIId":4,"strPOIName":"Bar","strPOIImage":"fa-beer","intStatusId":1,"intLanguageId":1},{"intPOIId":5,"strPOIName":"Pontos Turísticos","strPOIImage":"fa-map-marker","intStatusId":1,"intLanguageId":1},{"intPOIId":6,"strPOIName":"Cafeteria","strPOIImage":"fa-coffee","intStatusId":1,"intLanguageId":1},{"intPOIId":7,"strPOIName":"Shopping","strPOIImage":"fa-diamond","intStatusId":1,"intLanguageId":1},{"intPOIId":8,"strPOIName":"Livraria","strPOIImage":"fa-book","intStatusId":1,"intLanguageId":1},{"intPOIId":9,"strPOIName":"Show","strPOIImage":"fa-microphone","intStatusId":1,"intLanguageId":1},{"intPOIId":10,"strPOIName":"Boates","strPOIImage":"fa-glass","intStatusId":1,"intLanguageId":1},{"intPOIId":11,"strPOIName":"Lanchonete","strPOIImage":"fa-cutlery","intStatusId":1,"intLanguageId":1},{"intPOIId":12,"strPOIName":"Hotéis","strPOIImage":"fa-building","intStatusId":1,"intLanguageId":1},{"intPOIId":13,"strPOIName":"Pub","strPOIImage":"fa-beer","intStatusId":1,"intLanguageId":1},{"intPOIId":14,"strPOIName":"Pizzaria","strPOIImage":"fa-pie-chart","intStatusId":1,"intLanguageId":1},{"intPOIId":15,"strPOIName":"Univesidade","strPOIImage":"fa-university","intStatusId":1,"intLanguageId":1},{"intPOIId":16,"strPOIName":"Hospital","strPOIImage":"fa-plus-square","intStatusId":1,"intLanguageId":1}]}


And my Java Code:

import com.android.volley.NoConnectionError;
import com.android.volley.ServerError;
import com.game.code.guide44.adapter.POIAdapter;
import com.game.code.guide44.app.AppController;
import com.game.code.guide44.data.PointOfInterest;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

public class POIChoose extends Activity {
private ListView lVwPOI;
private POIAdapter adapterPOI;
private ProgressDialog pDialog;
private List<PointOfInterest> POIList;
private String url;
private StringBuilder stbCheckedPOI;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_poi_choose);
//Initialize with ListView object from activity_poi_choose by id
lVwPOI = (ListView)findViewById(R.id.lvwPOI);
//Initialize the list of POI
POIList = new ArrayList<PointOfInterest>();
//initialize with POI List
adapterPOI = new POIAdapter(this, POIList);
//Fill the LiistView with POIAdapter content
lVwPOI.setAdapter(adapterPOI);
stbCheckedPOI = new StringBuilder();
//Base url
//Change "1" to dynamic user language
url = getString(R.string.urlBase)+getString(R.string.urlGetPOI)+"?ff_01="+String.format(getString(R.string.sqlSelectPOI), "1");

//Initialize the ProgressDialog
pDialog = new ProgressDialog(POIChoose.this);
//Show the progress bar befores making HTTP request
pDialog.setMessage(getString(R.string.txtMsgPleaseWait));
pDialog.show();

// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
url, null, new Response.Listener<JSONObject>() {

@Override
public void onResponse(JSONObject response) {
VolleyLog.v("VOLLEY", "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError error) {
if(error instanceof NoConnectionError)
Toast.makeText(POIChoose.this, "No internet available", Toast.LENGTH_SHORT).show();
else if(error instanceof ServerError)
Toast.makeText(POIChoose.this, "Server Error", Toast.LENGTH_SHORT).show();

VolleyLog.e("VOLLEY_ERROR", "Error: " + error.getMessage());
Log.e("LOG", "Error: " + error.getMessage());
pDialog.dismiss();
}
});

// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}

@Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}

private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}

private void parseJsonFeed(JSONObject response){
try{
JSONArray jsonArray = response.getJSONArray("arrPOI");
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
PointOfInterest Poi = new PointOfInterest();
Poi.setPOIId(jsonObject.getInt("intPointId"));
Poi.setPOIName(jsonObject.getString("vchPointName"));
Poi.setPOIPicture(jsonObject.getString("vchAwesomeFont"));
Poi.setStatusId(jsonObject.getInt("intStatusId"));
Poi.setLanguageId(jsonObject.getInt("intLanguageId"));

// adding movie to movies array
POIList.add(Poi);
}

} 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.menu_first_choose, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}

public void performSelectPOI(View view){
for(int i = 0; i < POIList.size(); i++)
{
if(adapterPOI.mCheckStates.get(i)==true)
{
stbCheckedPOI.append(POIList.get(i).toString());
stbCheckedPOI.append("\n");
}
else
{

}
}
Toast.makeText(AppController.getContext(), stbCheckedPOI, Toast.LENGTH_LONG).show();
}
}


I also heard about GSON. Is it the solution? Can anyone help me? Thanks in advance!!

Answer

Well my friends, I tried everything to solve the problem in Java code but I almost forgot to see what my PHP was receiving.

In this part of my code:

url = getString(R.string.urlBase)+getString(R.string.urlGetPOI)+"?ff_01="+String.format(getString(R.string.sqlSelectPOI), "1");

I was passing my SQL query as parameter. Well, the PHP wasn't receiving all query. For example: if I pass

"SELECT ID, NAME, ORDER FROM tblOrder"

my PHP receives only "SELECT", generating an error (obviously!!). So the problem wasn't BOM or UTF-8 or anything like these... Was a basic error.

So, the solution was put the SQL query inside the PHP and pass only a few parameters to receive the correct answer (in this case, the JSONObject)

Thanks a lot!!

P.S.: Thanks to Xjasz! You were right!! I needed to change this:

Poi.setPOIId(jsonObject.getInt("intPointId"));
Poi.setPOIName(jsonObject.getString("vchPointName"));
Poi.setPOIPicture(jsonObject.getString("vchAwesomeFont"));
Poi.setStatusId(jsonObject.getInt("intStatusId"));
Poi.setLanguageId(jsonObject.getInt("intLanguageId"));

for this:

Poi.setPOIId(jsonObject.getInt("intPOIId"));
Poi.setPOIName(jsonObject.getString("strPOIName"));
Poi.setPOIPicture(jsonObject.getString("strPOIImage"));
Poi.setStatusId(jsonObject.getInt("intStatusId"));
Poi.setLanguageId(jsonObject.getInt("intLanguageId"));

Thanks man!!