无法获得数据在第一次点击在android webview与服务器通信

Unable to get data at first click in android webview with server communication

本文关键字:android webview 通信 服务器 第一次 数据      更新时间:2023-09-26

我从JavaScript调用这个方法。
第一次,它给出了null。但从第二次开始,数据就来了。请帮帮我。

@SuppressLint("JavascriptInterface")
public String loadClickedData() {
    pDialog = ProgressDialog.show(this, "dialog title",
            "dialog message", true);
    new HttpAsyncTaskClickedData()
            .execute("http://192.168.0.9/btrepo/btrepo/android_api.php");
    return bdb.getmPosIdData();
}

这里我们通过Android中的AsyncTask获取数据:

private class HttpAsyncTaskClickedData extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("tag", "get_pos_details"));
        nameValuePairs.add(new BasicNameValuePair("pos_id", posId));
        return GET(urls[0], nameValuePairs);
    }
    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {
        // Toast.makeText(getApplicationContext(), result+" in post ",
        // Toast.LENGTH_LONG).show();
        pDialog.dismiss();
        Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG)
                .show();
        bdb.setmPosIdData(result);
    }
}

这个方法用于从服务器获取数据:

public static String GET(String url, List<NameValuePair> pair) {
    InputStream inputStream = null;
    String result = "";
    try {
        // create HttpClient
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(pair));
        HttpResponse httpResponse = httpClient.execute(httpPost);
        // receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();
        is = inputStream;
        // convert inputstream to string
        if (inputStream != null) {
            // jObj = convertIsToJson(inputStream);
            result = convertIsToJson(inputStream) + " ";
            // jSonStr = result;
        } else
            result = "Did not work!";
    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }
    return result;
}

我从json字符串格式的服务器获取数据。
它显示null值的属性,如{pos["posid":null, "storeName":null]}等。

下面的函数

public String loadClickedData() {
    pDialog = ProgressDialog.show(this, "dialog title",
            "dialog message", true);
    new HttpAsyncTaskClickedData()
            .execute("http://192.168.0.9/btrepo/btrepo/android_api.php");
    return bdb.getmPosIdData();
}

执行HttpAsyncTaskClickedData(),并立即返回bdb.getmPosIdData()(这将永远是一个问题的第一次)

AsyncTask的结果是仅在onPostExecute 中可用,其中您调用 bdb.setmPosIdData(result);

@Override
protected void onPostExecute(String result) {
    // ...
    bdb.setmPosIdData(result); // result is only stored in bdb here!
}

HttpAsyncTaskClickedData在后台运行,可能需要一些时间。
这就是为什么你的第一次调用总是无法获得数据,因为你在执行AsyncTask后立即返回bdb.getmPosIdData()

private class HttpAsyncTaskClickedData extends
            AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs
                    .add(new BasicNameValuePair("tag", "get_pos_details"));
            nameValuePairs.add(new BasicNameValuePair("pos_id", posId));
            return GET(urls[0], nameValuePairs);
        }
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            // Toast.makeText(getApplicationContext(), result+" in post ",
            // Toast.LENGTH_LONG).show();
            data = result;
            pDialog.dismiss();
            bdb.setmPosIdData(result);
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = ProgressDialog.show(MainActivity.this, "dialog title",
                    "dialog message", true);
        }
         @SuppressLint("JavascriptInterface")
         public String loadData() {
         Toast.makeText(getApplicationContext(), data+ " hi ",
         Toast.LENGTH_LONG).show();
         return data;
        }
    }
and calling loadData() method from javascript. 

此函数用于在javascript中使用post url获取数据

 function jsonPost(){
    var http = new XMLHttpRequest();
    var url = "http://192.168.0.9/btrepo/btrepo/android_api.php";
var params = "tag=fav_stores&mobile=984989874";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
  alert("hello "+http.send(params));


    }