3

I have a jQuery List View in my Android webview that loads data from the server. I use a HTTP GET response to get data from the server-database. I use this in <body onload="loadRes()">. This is my method:

<script>
lastRecord=0;

    function loadRes(){
        $('#sample').html( 'hello' );
        $.get( 
        "queryRestaurantsList.php?lastRecord="+lastRecord,
        function( data ) {
            $('#rest_mesgs').append( data )
            .listview( 'refresh' );
        });
    }
</script> 

However, i want to sort this list in a particular order. For that i send a POST message from Android code to the server which contains a string object like this:

String list_order ="0012,0002,0003,0001";

This list_order String object represent RestaurantID in the database which is also the primary key. The format of the this primary key is VARCHAR(4). This is my php file: However, i always get the message "Still working" on my web view even though i can see the HTML of the sorted list in LogCat though HttpResponse

<?
mysql_connect($host,$username,$password);
mysql_select_db($database) or die( "Unable to select database");

echo $_POST['ids'];

if($_POST != null){

$query = "SELECT RestaurantID,Name,Short_Loc,Image_Link,Full_Link,Type FROM Restaurant_Info
          ORDER BY FIND_IN_SET(RestaurantID,'".$ids."')";

$result = mysql_query($query) or die( "Unable to execute query");

while ($row = mysql_fetch_array($result)){
        print '<li id="'.$row['RestaurantID'].'" onclick="newAct('.$row['RestaurantID'].')">';   
        print '<a href="'.$row['Full_Link'].'">';
        print '<img style="height:80px;" src="'.$row['Image_Link'].'">';
        print '<h2 style="text-wrap : normal" >'.$row['Name'].'</h2>';
        print '<p id="type" class="ui-li-aside"><strong>'.$row['Type'].'</strong></p>';
        print '<p>'.$row['Short_Loc'].'</p>';
        print '</a>';
        print '</li>';
        }
}
else {
    echo "Still working";
    }

?>

HttpPostID.class - Class that POST data to server

public class HttpPostID extends AsyncTask<Void,Integer,Void> {

    static String result;

    private static final String webphp = "http://...../queryRestaurantsList.php";

    String IDs;

    HttpPostID(String ids){
        this.IDs =ids;
    }

    @Override
    protected Void doInBackground(Void... params){

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(webphp);

        try {

            String hello="111,222,333";

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("order",IDs));
            nameValuePairs.add(new BasicNameValuePair("hello",hello));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse response = httpclient.execute(httppost);
            HttpEntity resEntity = response.getEntity();

            result = EntityUtils.toString(resEntity);

            System.out.println(result);


        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}

I call this in my Activity: new HttpPostID(tester).execute(); tester is a String object.

LogCat (only a few lines since output is large)

07-12 02:25:14.850: I/System.out(10440): <li id="0013" onclick="newAct(0013)"><a href=""><img style="height:80px;" src="http://cedars.hku.hk/sections/campuslife/images/pacific.jpg"><h2 style="text-wrap : normal" >Pacific Coffee Company</h2><p id="type" class="ui-li-aside"><strong>Sandwiches, Cut cakes, Pies, Pastries, Muffins, Premium Ground Coffee, Fruit Juices</strong></p><p>Main Campus</p></a></li><li id="0003" onclick="newAct(0003)"><a href="#page4"><img style="height:80px;" 
stud91
  • 1,854
  • 6
  • 31
  • 56
  • you mean that first you are getting data via GET and then sending the same data to via POST to sort ? – MTahir Jul 09 '14 at 18:37
  • @MTahir. yes you can say but the channel is different. I am sending POST request from the app code to the php file. The web page reads that php file from a GET request – stud91 Jul 09 '14 at 18:42
  • You can either return the sorted results in first place or you can do it using jQuery in your app. See [http://stackoverflow.com/questions/1134976/how-may-i-sort-a-list-alphabetically-using-jquery] for example. – MTahir Jul 09 '14 at 18:46
  • @MTahir Actually i am trying to sort this list according to the places that are nearest to me in terms of distance. That is why I'm using the app to send a POST message to the server so that it could create this list. The `$_POST['ids']` contains id's of restaurant in order of nearest location – stud91 Jul 09 '14 at 18:50
  • I just need something to load the list in HTML whenever the POST message is sent. I am able to catch this in my response shown in LogCat which shows me the HTML of sorted list. BUT this does not appear in webview – stud91 Jul 09 '14 at 18:52
  • Can you show us your POST request ? – Shivam Verma Jul 11 '14 at 18:11
  • @ShivamVerma I have added that. Please have a look – stud91 Jul 11 '14 at 18:31
  • @stud91 So, once you get the response from the POST Request, you'll need to update the webview with the newly received data. Do you do that ? – Shivam Verma Jul 12 '14 at 02:25
  • @ShivamVerma how do u update the webview? – stud91 Jul 12 '14 at 09:44
  • You do want to show the received data right ? – Shivam Verma Jul 12 '14 at 09:46
  • Yes that is my objective – stud91 Jul 12 '14 at 09:46
  • why don't you make the POST Request using jQuery itself ? That way you can easily update your HTML Code from jQuery when the response is received. If you need to update WebView from the Java code, you'll need a Javascript Interface. – Shivam Verma Jul 12 '14 at 09:48
  • Actually this POST request is the order of restaurants according to their distance from me..i am not sure how can i calculate that in html – stud91 Jul 12 '14 at 09:50
  • try the method listed here to pass back to webpage from java, http://stackoverflow.com/questions/11752052/passing-data-from-java-class-to-web-view-html – Qarib Haider Jul 14 '14 at 08:27

3 Answers3

5

At first write a javascript in the html like this

 <script>
 function reloadRes(var data){
    $('#sample').html( 'hello' );
    $('#rest_mesgs').append( data )
        .listview( 'refresh' );
}
</script>

then rewrite Http

public class HttpPostID extends AsyncTask<Void,Integer,String> {

static String result;

private static final String webphp = "http://...../queryRestaurantsList.php";

String IDs;

HttpPostID(String ids){
    this.IDs =ids;
}

@Override
protected String doInBackground(Void... params){

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(webphp);

    try {

        String hello="111,222,333";

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("order",IDs));
        nameValuePairs.add(new BasicNameValuePair("hello",hello));

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();

        result = EntityUtils.toString(resEntity);


        System.out.println(result);
        return result;


    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }


}
    @Override
    protected void onPostExecute(String data){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
    {
        webview.evaluateJavascript("javascript:reloadRes(data)",
                null);
    }
    else
    {
        webview.loadUrl("javascript:reloadRes(data)");
    }

    }

}

I am an android developer, so I am not sure about the function reloadRes(var data), please modify it as per your requirement.

Ratul Ghosh
  • 1,512
  • 9
  • 15
  • +1 for great Android fix and providing pre-/post kitkat check. Way more helpful than my PHP and JS answer. – Canis Jul 18 '14 at 21:24
0

It's been a long while since I touched Android dev, so things may have changed, but I'll give it a try.

The webview has the ability to call javascript functions in the html page loaded inside of it. If you alter the function you have (or create a new one for this specific task) in such a way that it can accept parameters, you can call that function from android code when you have calculated the distances.

<script>
lastRecord=0;

    function loadRes(listOrder){
        $('#sample').html( 'hello' );
        $.get( 
        "queryRestaurantsList.php?lastRecord="+lastRecord+"&listOrder="+listOrder,
        function( data ) {
            $('#rest_mesgs').append( data )
            .listview( 'refresh' );
        });
    }
</script>

Then just alter your PHP to reflect the changes:

echo $_GET['listOrder']; // Test to see if you catch the param

if( isset($_GET['listOrder'],$_GET['lastRecord']) ){

$query = "SELECT RestaurantID,Name,Short_Loc,Image_Link,Full_Link,Type FROM Restaurant_Info
          ORDER BY FIND_IN_SET(RestaurantID,'".$ids."')";
...

Hope you can piece together what you need from this. Good luck!

PS! I say again, I'm really rusty on the actual Android stuff, but I see a commenter left a link to a question with answers that cover basically the same method.

EDIT

Tibro covered the Android part of the question perfectly to my eyes. He should get the bounty, as I only was able to present code in javascript and PHP.

Canis
  • 4,130
  • 1
  • 23
  • 27
-1

Your HttpPostID class is missing a method. The method doInBackground does the work on a background thread. But the results are gathered in the onPostExecute method. Going further, I see that you are assigning the result (the response from the http post) to a static variable. That value should be returned from the doInBackground method. It will then be passed in to the onPostExecute method as an input parameter. As a result you won't need the static variable.

Take a look at the first block of sample code here: http://developer.android.com/reference/android/os/AsyncTask.html. Change your HttpPostID class to match that model and you should be all set. One thing.... the sample code returns a long from doInBackground. That long is included in the class declaration and as an input parameter to onPostExecute. You will need to change to a string, like this:

private class DownloadFilesTask extends AsyncTask<URL, Integer, String> {


String IDs;

HttpPostID(String ids){
    this.IDs =ids;
}
protected String doInBackground(URL... urls) {
    String result = null;
    String webphp = "http://...../queryRestaurantsList.php";
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(webphp);

    try {

        String hello="111,222,333";

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("order",IDs));
        nameValuePairs.add(new BasicNameValuePair("hello",hello));

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();

        result = EntityUtils.toString(resEntity);



    } catch (Exception e) {
        e.printStackTrace();
    }
   return result;

 }

 protected void onPostExecute(String result) {
   // this method is executed on the main UI thread
   // result is what is returned from the http post
   String html = result;
 }
 }
itsben
  • 1,017
  • 1
  • 6
  • 11
  • I already am catching the response of my http post. Please see the LogCat dump in my question. My problem is why isn't this response catched by the `$.get` in javascript – stud91 Jul 16 '14 at 15:48