Viewed   110 times

While trying to parse json string to android, HTML values are passed. Before a day all was working good, and suddenly my app start crashing when trying to fetch database with the help of php files.

When I checked noticed that html values.. see logcat

08-10 01:09:55.814: E/result(6744): <html><body><h2>Checking your browser..<h2><script type="text/javascript" src="/aes.js" ></script><script>function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++)e+=(16>d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("7965e114a1dccaf35af3756261f75ad8");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/";location.href="http://realroom.byethost24.com/medical/stokist.php?ckattempt=1";</script></body></html>
08-10 01:09:55.814: E/JSON Parser(6744): Error parsing data org.json.JSONException: Value <html><body><h2>Checking of type java.lang.String cannot be converted to JSONObject
08-10 01:09:55.816: E/AndroidRuntime(6744): FATAL EXCEPTION: AsyncTask #1
08-10 01:09:55.816: E/AndroidRuntime(6744): Process: com.example.medionline, PID: 6744
08-10 01:09:55.816: E/AndroidRuntime(6744): java.lang.RuntimeException: An error occured while executing doInBackground()
08-10 01:09:55.816: E/AndroidRuntime(6744):     at android.os.AsyncTask$3.done(AsyncTask.java:304)
08-10 01:09:55.816: E/AndroidRuntime(6744):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
08-10 01:09:55.816: E/AndroidRuntime(6744):     at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
08-10 01:09:55.816: E/AndroidRuntime(6744):     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
08-10 01:09:55.816: E/AndroidRuntime(6744):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
08-10 01:09:55.816: E/AndroidRuntime(6744):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
08-10 01:09:55.816: E/AndroidRuntime(6744):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
08-10 01:09:55.816: E/AndroidRuntime(6744):     at java.lang.Thread.run(Thread.java:818)
08-10 01:09:55.816: E/AndroidRuntime(6744): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
08-10 01:09:55.816: E/AndroidRuntime(6744):     at com.example.medionline.All_supplier_list$FetchMFG.doInBackground(All_supplier_list.java:182)
08-10 01:09:55.816: E/AndroidRuntime(6744):     at com.example.medionline.All_supplier_list$FetchMFG.doInBackground(All_supplier_list.java:1)
08-10 01:09:55.816: E/AndroidRuntime(6744):     at android.os.AsyncTask$2.call(AsyncTask.java:292)
08-10 01:09:55.816: E/AndroidRuntime(6744):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
08-10 01:09:55.816: E/AndroidRuntime(6744):     ... 4 more

This is happening to all the pages that I have hosted on byethost server, while the pages that are hosted on other server are working well and fine. I tried moving one of my file to other server and on that it is returning proper json string.

Also when I check the url in browser it is returning proper json string without any exception or error with byethost.. but in android giving html values..

Here's my JSONfunction class

package com.example.medionline;
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.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.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONfunctions
{

     static InputStream is = null;
 static String result = "";
 static JSONObject jArray = null;
public static JSONObject getJSONfromURL(String url) 
{
    // Download JSON data from URL
    try 
    {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        httppost.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240 ");
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
    } 
    catch (Exception e) 
    {
        Log.e("log_tag", "Error in http connection " + e.toString());
    }

    try 
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) 
        {
            Log.e("jsonnnnnnn", line);
            sb.append(line + "n");
        }
        is.close();
        result = sb.toString();
        Log.e("result", result);
    } 
    catch (Exception e) 
    {
        Log.e("log_tag", "Error converting result " + e.toString());
    }
    try 
    {
        jArray = new JSONObject(result);
    } 
    catch (JSONException e)
    {
        Log.e("log_tag", "Error parsing data " + e.toString());
    }
    return jArray;
}

public static JSONObject makeHttpRequest(String loginUrl, String post, List<NameValuePair> para)
{
    try 
    {
        if(post == "POST")
        {
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(loginUrl);
            httpPost.setEntity(new UrlEncodedFormEntity(para));
            httpPost.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240 ");
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }
        else if(post == "GET")
        {
            HttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(para, "utf-8");
            loginUrl += "?" + paramString;
            HttpGet httpGet = new HttpGet(loginUrl);
            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);
        StringBuilder sb = new StringBuilder();
        String line = null;
        if (is != null) 
        {
            while ((line = reader.readLine()) != null) 
            {
                //Log.e("jsonnnnnnn", line);
                sb.append(line + "n");
            }
            is.close();
            result = sb.toString();
            Log.e("result", result);
        }
    }
    catch (Exception e)
    {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }
    try
    {
        jArray = new JSONObject(result);
    }
    catch (JSONException e)
    {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }
    return jArray;
}
}

And this is my PHP file

<?php
include('config.php');
date_default_timezone_set("Asia/Calcutta");

$result1 = mysqli_query($con,"SELECT  *
                                    FROM  `pj_medionline_mst_stockist` 
                                    ORDER BY  `pj_medionline_mst_stockist`.`ID` ASC ");


$response = array();
$posts = array();
while($row=mysqli_fetch_array($result1))
{
    $id =$row["ID"];
    $stkcode =$row["stkcode"];
    $comName =$row["ComName"];
    $operatorid =$row["operatorid"];
    $password =$row["Password"];


    $posts[] = array('id'=>$id, 'stkcode'=>$stkcode, 'stkname'=>$comName, 'operatorid'=>$operatorid, 'password'=>$password);
}

$response['stokist'] = $posts;
print(json_encode($response));
?>

 Answers

1

I should add the following as answer as it is the workaround to bypass the above problem. Posting as it might help someone:

This problem can be solved by simply writing exit(); in the php file at the last executable statement. This will exit the php file and will not append the text. eg.

<?php
include('config.php');
date_default_timezone_set("Asia/Calcutta");

$result1 = mysqli_query($con,"SELECT  *
                                FROM  `pj_medionline_mst_stockist` 
                                ORDER BY  `pj_medionline_mst_stockist`.`ID` ASC ");


$response = array();
$posts = array();
while($row=mysqli_fetch_array($result1))
{
    $id =$row["ID"];
    $stkcode =$row["stkcode"];
    $comName =$row["ComName"];
    $operatorid =$row["operatorid"];
    $password =$row["Password"];


    $posts[] = array('id'=>$id, 'stkcode'=>$stkcode, 'stkname'=>$comName, 'operatorid'=>$operatorid, 'password'=>$password);
}

$response['stokist'] = $posts;
print(json_encode($response));
exit();
?>
Wednesday, December 7, 2022
3

Try this way to creating the associative array in php,

<?php
   $object=array();
   $i=0;
   while($i<10){
     $employee = array("name"=>"hassan", "Designation"=>"Software Engineer");
     $i++;
     $object[]=$employee;
   }
   $orginal["data"]=$object;
   echo json_encode($orginal)
?>

OUTPUT WILL BE

{"data":[{"name":"hassan","Designation":"Software Engineer"},{"name":"hassan","Designation":"Software Engineer"},{"name":"hassan","Designation":"Software Engineer"},{"name":"hassan","Designation":"Software Engineer"},{"name":"hassan","Designation":"Software Engineer"},{"name":"hassan","Designation":"Software Engineer"},{"name":"hassan","Designation":"Software Engineer"},{"name":"hassan","Designation":"Software Engineer"},{"name":"hassan","Designation":"Software Engineer"},{"name":"hassan","Designation":"Software Engineer"}]}
Tuesday, December 27, 2022
 
wimh
 
4

After almost searching for 3+ weeks and n+ hours of frustration, i've finally found an working solution to my problem and sharing it with people so they could benefit from it (as i was blocked from another a/c due to asking too many questions and down votes ) , in order to send your array list to your server we need to use another library and the best fit according to my need is async-http library by loop j and these are the steps to import and use the library in your program :-

1.)import the library into your project by writing this statement in your bulid.gradle(app module):-

compile 'com.loopj.android:android-async-http:1.4.9'

2.)Create the following variables in order to use them in your program:-

 AsyncHttpClient (a client to send data to your server)
    RequestPrarms (Data sent to your server for parsing and further operations )
    String url(Link to your server where actually operations occurs)

3.) Now we use these variables and run the program :-

p

arams.put("OrderSummary", <your array list>);
           httpClient.post(APIURL.API_URL,params, new AsyncHttpResponseHandler() {
               @Override
               public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                   //your operations on success
               }

               @Override
               public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    Toast.makeText(getApplicationContext(),error.toString(),Toast.LENGTH_LONG).show();
               }
           });  

i hope this clears your doubts somewhat i'm still creating my php side in order to insert data in the database

Saturday, September 17, 2022
 
wonil
 
4

Here is the JSfiddle Demo

I changed your HTML and give your input textfield an id of value. I removed the passed param for your verifyorder function, and instead grab the content of your textfield by using document.getElementById(); then i convert the str into value with +order so you can check if it's greater than zero:

<input type="text" maxlength="3" name="value" id='value' />
<input type="button" value="submit" onclick="verifyorder()" />
</p>
<p id="error"></p>
<p id="detspace"></p> 

function verifyorder() {
        var order = document.getElementById('value').value;
        if (+order > 0) {
            alert(+order);
            return true;
        }
        else {
            alert("Sorry, you need to enter a positive integer value, try again");
            document.getElementById('error').innerHTML = "Sorry, you need to enter a positive integer value, try again";
        }
    }
Thursday, November 24, 2022
 
2

First of all you can avoid structure like this:

{first_name: $('[name=first_name]').val(), last_name: $('[name=last_name]').val(), email: $('[name=email]').val()}

With jQuery's built in serialize method:

$.serialize(this)

As far as you already specified "json" as a response type "data" variable will contain already unserialized JSON object.

In php script side of things you need to do following:

echo json_encode($_POST);
exit();

Of course you need to change $_POST superglobal with your array/object of result, I used it for demo purpose in script line above.

Obviously $_POST variable contains data passed from Ajax request, such variable is available in any scope in PHP script.

Wednesday, November 30, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :