Android和HTML页面之间的Webview数据不匹配


Webview Data Mismatch between Android and HTML page

我有一个jQuery列表视图在我的Android webview从服务器加载数据。我使用HTTP GET响应从服务器-数据库获取数据。我在<body onload="loadRes()">中使用这个。这是我的方法:

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

但是,我想按特定的顺序对这个列表排序。为此,我从Android代码发送一个POST消息到服务器,其中包含一个像这样的字符串对象:

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

这个list_order String对象表示数据库中的RestaurantID,它也是主键。此主键的格式为VARCHAR(4)。这是我的php文件:然而,我总是得到消息"仍在工作"在我的web视图,即使我可以看到在LogCat通过HttpResponse排序列表的HTML

<?
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";
    }
?>

httppostd . Class - POST数据到服务器的类

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;
    }
}

我在我的活动中调用它:new HttpPostID(tester).execute(); tester是一个字符串对象。

LogCat(只有几行,因为输出很大)

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;" 

首先在html中编写如下的javascript

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

然后重写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)");
    }
    }

}

我是android开发人员,所以我不确定函数reloadRes(var data),请根据您的要求修改它

我接触Android开发已经有很长一段时间了,所以情况可能已经发生了变化,但我还是会尝试一下。

webview有能力调用加载在它里面的html页面中的javascript函数。如果你改变你的函数(或者为这个特定的任务创建一个新的),这样它就可以接受参数,你可以从android代码中调用这个函数,当你计算了距离。

<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>

然后修改你的PHP来反映这些变化:

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."')";
...

希望你能从中拼凑出你需要的东西。好运!

PS !我再说一遍,我真的对Android的东西生透了,但我看到一个评论者留下了一个问题的链接,其中的答案基本上涵盖了相同的方法。

编辑

在我看来,Tibro完美地涵盖了问题的Android部分。他应该得到赏金,因为我只会用javascript和PHP呈现代码。

你的HttpPostID类缺少一个方法。方法doInBackground在后台线程上完成工作。但是结果是在onPostExecute方法中收集的。更进一步,我看到您正在将结果(来自http post的响应)分配给一个静态变量。那个值应该从doInBackground方法返回。然后将其作为输入参数传递给onPostExecute方法。因此,您不需要静态变量。

看一下这里的第一个示例代码块:http://developer.android.com/reference/android/os/AsyncTask.html。更改您的HttpPostID类以匹配该模型,您应该都设置好了。一件事……示例代码从doInBackground返回一个long。这个长度包含在类声明中,并作为onPostExecute的输入参数。您需要将其更改为字符串,如下所示:

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;
 }
 }