如何解析从asynctask到方法的参数?

时间:2015-08-09 18:51:33

标签: java php android json android-asynctask

我的代码存在问题。我将JSON字符串从数据库解析到android,但我似乎无法运行代码。

我使用asynctask类来doInBackground从数据库中检索JSONparse并将其提供给onPostExecute方法。

我想将参数提供给setCharges方法以获取参数并将android textview的费用设置为double。

如果我的代码有任何问题,请提供建议。

提前致谢。

下面的代码是PHP脚本

<?php

require("config.php");

        //initial query
$query = "SELECT fHAH,sHAH,rHAH FROM charges";

//execute query

$stmt   = $db->prepare($query);
$result = $stmt->execute($query_params);

// Finally, we can retrieve all of the found rows into an array using fetchAll 
$rows = $stmt->fetchAll();


if ($rows) {

    $response["charges"] = array();

    foreach ($rows as $row) {

        $charge = array();

        $charge["fHAH"] = $row["fHAH"];
        $charge["sHAH"]    = $row["sHAH"];
        $charge["rHAH"]  = $row["rHAH"];


        //update our repsonse JSON data
        array_push($response["charges"], $post);
    }

    // echoing JSON response
    echo json_encode($response);


}

这是AsyncTask类

    private class getLoadData extends AsyncTask<Void, Void, Void> {

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

            JSONParser jParser = new JSONParser();
            json = jParser.getJSONDataFromURL(chargesSettingURL);

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            double fCharge = 0.0;
            double sCharge = 0.0;
            double rCharge = 0.0;

            try {

                chargesJSONArray = json.getJSONArray(TAG_CHARGES);

                for (int i = 0; i < chargesJSONArray.length(); i++) {
                    JSONObject c = chargesJSONArray.getJSONObject(i);

                    fCharge = Double.parseDouble(c.getString(TAG_FHAH));
                    sCharge = Double.parseDouble(c.getString(TAG_SHAH));
                    rCharge = Double.parseDouble(c.getString(TAG_RHAH));


                    setCharges(fCharge, sCharge, rCharge);

                }

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

        }
    }

这是setCharges方法

public void setCharges(double fHAH, double sHAH, double rHAH) {
    this.F_HALF_AN_HOUR = fHAH;
    this.S_HALF_AN_HOUR = sHAH;
    this.R_HALF_AN_HOURS = rHAH;
}

我已收到错误日志

08-09 17:56:35.650    1860-2094/com.gpark.nerdherd.fyp 

E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
    Process: com.gpark.nerdherd.fyp, PID: 1860
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:300)
            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
            at java.util.concurrent.FutureTask.run(FutureTask.java:242)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.StringBuilder.toString()' on a null object reference
            at com.gpark.nerdherd.fyp.libs.JSONParser.getJSONDataFromURL(JSONParser.java:45)
            at com.gpark.nerdherd.fyp.libs.CalculateParking$getLoadData.doInBackground(CalculateParking.java:42)
            at com.gpark.nerdherd.fyp.libs.CalculateParking$getLoadData.doInBackground(CalculateParking.java:36)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)
08-09 17:56:43.620    2110-2110/com.gpark.nerdherd.fyp D/Atlas﹕ Validating map...
08-09 17:56:43.980    2110-2125/com.gpark.nerdherd.fyp D/﹕ HostConnection::get() New Host Connection established 0x7fd75984f1a0, tid 2125
08-09 17:56:44.000    2110-2125/com.gpark.nerdherd.fyp I/OpenGLRenderer﹕ Initialized EGL, version 1.4
08-09 17:56:44.060    2110-2125/com.gpark.nerdherd.fyp D/OpenGLRenderer﹕ Enabling debug mode 0
08-09 17:56:44.070    2110-2125/com.gpark.nerdherd.fyp W/EGL_emulation﹕ eglSurfaceAttrib not implemented
08-09 17:56:44.070    2110-2125/com.gpark.nerdherd.fyp W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0x7fd75984e300, error=EGL_SUCCESS
08-09 17:56:47.150    2110-2129/com.gpark.nerdherd.fyp E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
    Process: com.gpark.nerdherd.fyp, PID: 2110
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:300)
            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
            at java.util.concurrent.FutureTask.run(FutureTask.java:242)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.StringBuilder.toString()' on a null object reference
            at com.gpark.nerdherd.fyp.libs.JSONParser.getJSONDataFromURL(JSONParser.java:45)
            at com.gpark.nerdherd.fyp.libs.CalculateParking$getLoadData.doInBackground(CalculateParking.java:42)
            at com.gpark.nerdherd.fyp.libs.CalculateParking$getLoadData.doInBackground(CalculateParking.java:36)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)
08-09 17:56:47.270    2110-2133/com.gpark.nerdherd.fyp I/Process﹕ Sending signal. PID: 2110 SIG: 9

这是getJSONDataFromURL

public JSONObject getJSONDataFromURL(final String url) {

    try {

        urlObj = new URL(url);
        httpURLConnection = (HttpURLConnection) urlObj.openConnection();
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setRequestProperty("Accept-Charset", charset);
        httpURLConnection.setReadTimeout(10000);
        httpURLConnection.setConnectTimeout(15000);
        httpURLConnection.connect();
        paramsString = sbParams.toString();

        wr = new DataOutputStream(httpURLConnection.getOutputStream());
        wr.writeBytes(paramsString);
        wr.flush();
        wr.close();

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

    try {
        //Receive the response from the server
        InputStream in = new BufferedInputStream(httpURLConnection.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in, "iso-8859-1"), 8);

        String line;
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }

        in.close();
        json = result.toString();

    } catch (IOException e) {
        Log.e("JSON Parser", "result: " + e.toString());
    }

    httpURLConnection.disconnect();

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON Object
    return jObj;

}

1 个答案:

答案 0 :(得分:1)

您似乎在PHP代码中发明了$post变量。你似乎也过于复杂了

试试这个

require("config.php");
//initial query
$query = "SELECT fHAH,sHAH,rHAH FROM charges";

$response = array();

// as there is nothing to prepare use ->query
foreach ($db->query($sql) as $row)

    $response["charges"][] = $row;
}

echo json_encode($response);

现在你有一个合适的json对象来处理android设备上的java代码

现在,如果你read this you will find out how to parse a JSON string into a JSON object in JAVA