I am getting the following error:
Error parsing to json on getJarrayFromString(); org.json.JSONException: Value result of type java.lang.String cannot be converted to JSONArray
My JSON Code is as follows:
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"); <---- Error is here
}catch(JSONException e){
Log.e(DEBUG, "Error parsing to json on getJarrayFromString(); " + e.toString());
}
return jarray;
}
And My Java Activity is as follows:
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;
}
}
}
FINALLY, my PHP API for above code is here:
<?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();
?>
Now I have carried out an extensive research on this topic and unable to find a concrete solution to above mentioned problem.
I have read on few posts that may be strings are declared without using double quotes. Does this mean values that are stored in SQL file (eg. book name, price etc.) needs to be in double quotes rather than single quotes?
If I run the above code in JSONLint, I get the following error:
Parse error on line 1:
^
Expecting '{', '['
I tried using ("{result}") instead of {result) or ("result") but that gives me even more errors. I am so close to get this whole app work but the only problem is converting result
string into a valid JSON Array.
Any ideas and suggestions would be highly appreciated.
EDITED LOG CAT ERRORS AFTER IMPLEMENETION JARRAY= NEW JSONARRAY (RESULT);
03-06 21:17:31.387: D/AndroidRuntime(818): Shutting down VM
03-06 21:17:31.387: W/dalvikvm(818): threadid=1: thread exiting with uncaught exception (group=0x40014760)
03-06 21:17:31.417: E/AndroidRuntime(818): FATAL EXCEPTION: main
03-06 21:17:31.417: E/AndroidRuntime(818): java.lang.NullPointerException
03-06 21:17:31.417: E/AndroidRuntime(818): at com.fokrul.justdeals.ActivityTab$ProductsAdapter.getView(ActivityTab.java:1565)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.widget.AbsListView.obtainView(AbsListView.java:1970)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.widget.ListView.makeAndAddView(ListView.java:1756)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.widget.ListView.fillDown(ListView.java:656)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.widget.ListView.fillFromTop(ListView.java:716)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.widget.ListView.layoutChildren(ListView.java:1595)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.widget.AbsListView.onLayout(AbsListView.java:1800)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.view.View.layout(View.java:9581)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.view.ViewGroup.layout(ViewGroup.java:3877)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.widget.RelativeLayout.onLayout(RelativeLayout.java:912)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.view.View.layout(View.java:9581)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.view.ViewGroup.layout(ViewGroup.java:3877)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.widget.FrameLayout.onLayout(FrameLayout.java:400)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.view.View.layout(View.java:9581)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.view.ViewGroup.layout(ViewGroup.java:3877)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1542)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1403)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.widget.LinearLayout.onLayout(LinearLayout.java:1314)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.view.View.layout(View.java:9581)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.view.ViewGroup.layout(ViewGroup.java:3877)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.widget.FrameLayout.onLayout(FrameLayout.java:400)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.view.View.layout(View.java:9581)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.view.ViewGroup.layout(ViewGroup.java:3877)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.widget.RelativeLayout.onLayout(RelativeLayout.java:912)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.view.View.layout(View.java:9581)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.view.ViewGroup.layout(ViewGroup.java:3877)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.widget.FrameLayout.onLayout(FrameLayout.java:400)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.view.View.layout(View.java:9581)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.view.ViewGroup.layout(ViewGroup.java:3877)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1542)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1403)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.widget.LinearLayout.onLayout(LinearLayout.java:1314)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.view.View.layout(View.java:9581)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.view.ViewGroup.layout(ViewGroup.java:3877)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.widget.FrameLayout.onLayout(FrameLayout.java:400)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.view.View.layout(View.java:9581)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.view.ViewGroup.layout(ViewGroup.java:3877)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.view.ViewRoot.performTraversals(ViewRoot.java:1282)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.view.ViewRoot.handleMessage(ViewRoot.java:2040)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.os.Handler.dispatchMessage(Handler.java:99)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.os.Looper.loop(Looper.java:132)
03-06 21:17:31.417: E/AndroidRuntime(818): at android.app.ActivityThread.main(ActivityThread.java:4123)
03-06 21:17:31.417: E/AndroidRuntime(818): at java.lang.reflect.Method.invokeNative(Native Method)
03-06 21:17:31.417: E/AndroidRuntime(818): at java.lang.reflect.Method.invoke(Method.java:491)
03-06 21:17:31.417: E/AndroidRuntime(818): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
03-06 21:17:31.417: E/AndroidRuntime(818): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
03-06 21:17:31.417: E/AndroidRuntime(818): at dalvik.system.NativeStart.main(Native Method)
echo(json_encode
? Whitespace, BOM marks, etc? – Wrikken Mar 6 at 20:46jarray = new JSONArray("result");
... why yes, theString
literal "result" certainly isn't a JSON array. You also don't use!=
to compareString
objects in java. Java is not a scripting language. – Brian Roach Mar 6 at 20:50}
which leads me to suspect you are actually getting errors instead of json ouput (or you are cutting out some code) – datasage Mar 6 at 20:50echo statement
@BrianRoach I didn't get that. Are you saying that I shouldn't be using "result", if I use just (result), Log Cat shows more than 15 errors including a fatal exception and application crashes automatically!!! – Tirath Singh Mar 6 at 20:53