解析数据时出现json数据错误


json data error while parsing data

你好,我是android开发的新手,不知道如何使用JSON。我正在尝试一个现有的来制作我自己的,但在尝试时遇到了错误,无法使用JSON格式将数据发送到服务器。有人能帮我解决这个问题吗?或者建议我使用工作代码。

这是我的predictionpage.java(主要活动)页面

public class PredictionActivity extends Activity {
private String URL_NEW_PREDICTION = "http://127.0.0.1/new_predict.php";
private Button btnAddPrediction;
String numOfGoal = "1";
String numOfCard = "1";
String diffOfPos = "1";
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_prediction);
    RadioGroup goal = (RadioGroup) findViewById(R.id.answer1);
    goal.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            // TODO Auto-generated method stub
            switch (checkedId) {
                case R.id.answer1A:
                    numOfGoal = "1";
                    break;
                case R.id.answer1B:
                    numOfGoal = "2";
                    break;
                case R.id.answer1C:
                    numOfGoal = "3";
                    break;
            }
        }
    });
    RadioGroup card = (RadioGroup) findViewById(R.id.answer2);
    card.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            // TODO Auto-generated method stub
            switch (checkedId) {
                case R.id.answer2A:
                    numOfCard = "1";
                    break;
                case R.id.answer2B:
                    numOfCard = "2";
                    break;
                case R.id.answer2C:
                    numOfCard = "3";
                    break;
            }
        }
    });
    RadioGroup pos = (RadioGroup) findViewById(R.id.answer3);
    pos.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            // TODO Auto-generated method stub
            switch (checkedId) {
                case R.id.answer3A:
                    diffOfPos = "1";
                    break;
                case R.id.answer3B:
                    diffOfPos = "2";
                    break;
                case R.id.answer3C:
                    diffOfPos = "3";
                    break;
            }
        }
    });
    btnAddPrediction = (Button) findViewById(R.id.submit);
    btnAddPrediction.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // TODO Auto-generated method stub
            new AddNewPrediction().execute(numOfGoal, numOfCard, diffOfPos);
        }
    });
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_prediction, menu);
    return true;
}
private class AddNewPrediction extends AsyncTask<String, Void, Void> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    @Override
    protected Void doInBackground(String... arg) {
        // TODO Auto-generated method stub
        String goalNo = arg[0];
        String cardNo = arg[1];
        String posDiff = arg[2];
        // Preparing post params
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("goalNo", goalNo));
        params.add(new BasicNameValuePair("cardNo", cardNo));
        params.add(new BasicNameValuePair("posDiff", posDiff));
        ServiceHandler serviceClient = new ServiceHandler();
        String json = serviceClient.makeServiceCall(URL_NEW_PREDICTION,
                ServiceHandler.POST, params);
        Log.d("Create Prediction Request: ", "> " + json);

        if (json != null) {
            try {
                JSONObject jsonObj = new JSONObject(json);
                boolean error = jsonObj.getBoolean("error");
                // checking for error node in json
                if (!error) {
                    // new category created successfully
                    Log.e("Prediction added successfully ",
                            "> " + jsonObj.getString("message"));
                } else {
                    Log.e("Add Prediction Error: ",
                            "> " + jsonObj.getString("message"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("JSON Data", "JSON data error!");
        }
        return null;
    }
    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
    }
}
}

这是我的ServiceHandler.java

public class ServiceHandler {
static InputStream is = null;
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
public String makeServiceCall(String url, int method) {
    return this.makeServiceCall(url, method, null);
}

public String makeServiceCall(String url, int method,
                              List<NameValuePair> params) {
    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;

        if (method == POST) {
            HttpPost httpPost = new HttpPost(url);
            if (params != null) {
                httpPost.setEntity(new UrlEncodedFormEntity(params));
            }
            httpResponse = httpClient.execute(httpPost);
        } else if (method == GET) {
            if (params != null) {
                String paramString = URLEncodedUtils
                        .format(params, "utf-8");
                url += "?" + paramString;
            }
            HttpGet httpGet = new HttpGet(url);
            httpResponse = httpClient.execute(httpGet);
        }
        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;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "'n");
        }
        is.close();
        response = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error: " + e.toString());
    }
    return response;
}
}

这是我的php服务器页面:

<?php
$fp=fopen('filename.php','wb');
fwrite($fp, "data to be written");
fclose($fp);
if($fp)
    echo 'checkout';
else 
    echo 'nothing';
exit;
include_once './DbConnect.php';//This page include db connection file

function createNewPrediction() {
     $response = array();
    $goalNum = $_POST["goalNo"];
    $cardNum = $_POST["cardNo"];
    $posDiff = $_POST["posDiff"];
            $db = new DbConnect();
   // mysql query
    $query = "INSERT INTO prediction(goalNum,cardNum,posDiff) VALUES('$goalNum','$cardNum','$posDiff')";
    $result = mysql_query($query) or die(mysql_error().'hello');
    if ($result) {
        $response["error"] = false;
        $response["message"] = "Prediction added successfully!";
        echo'succes';
    } else {
        $response["error"] = true;
        $response["message"] = "Failed to add prediction!";
    }
   // echo json response
echo json_encode($response);
}
createNewPrediction();
?>

这是我的Logcat错误响应:

03-22 22:59:11.239 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err: org.apache.http.conn.HttpHostConnectException: Connection to http://127.0.0.1 refused
03-22 22:59:11.239 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:193)
03-22 22:59:11.239 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:169)
03-22 22:59:11.240 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:124)
03-22 22:59:11.240 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:366)
03-22 22:59:11.240 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:560)
03-22 22:59:11.240 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:492)
03-22 22:59:11.240 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:470)
03-22 22:59:11.276 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at com.example.muralivss.tjson2_predictionactivity.ServiceHandler.makeServiceCall(ServiceHandler.java:56)
03-22 22:59:11.277 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at com.example.muralivss.tjson2_predictionactivity.PredictionActivity$AddNewPrediction.doInBackground(PredictionActivity.java:143)
03-22 22:59:11.277 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at com.example.muralivss.tjson2_predictionactivity.PredictionActivity$AddNewPrediction.doInBackground(PredictionActivity.java:120)
03-22 22:59:11.278 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:295)
03-22 22:59:11.278 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
03-22 22:59:11.603 3194-3200/com.example.muralivss.tjson2_predictionactivity W/art: Suspending all threads took: 39.124ms
03-22 22:59:12.196 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
03-22 22:59:12.197 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
03-22 22:59:12.197 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
03-22 22:59:12.197 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at java.lang.Thread.run(Thread.java:818)
03-22 22:59:12.197 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err: Caused by: java.net.ConnectException: failed to connect to /127.0.0.1 (port 80): connect failed: ECONNREFUSED (Connection refused)
03-22 22:59:12.197 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at libcore.io.IoBridge.connect(IoBridge.java:124)
03-22 22:59:12.197 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
03-22 22:59:12.198 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:452)
03-22 22:59:12.198 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at java.net.Socket.connect(Socket.java:884)
03-22 22:59:12.198 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:124)
03-22 22:59:12.198 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:149)
03-22 22:59:12.198 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:  ... 15 more
03-22 22:59:12.198 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err: Caused by: android.system.ErrnoException: connect failed: ECONNREFUSED (Connection refused)
03-22 22:59:12.199 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at libcore.io.Posix.connect(Native Method)
03-22 22:59:12.199 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:111)
03-22 22:59:12.199 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
03-22 22:59:12.199 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:     at libcore.io.IoBridge.connect(IoBridge.java:122)
03-22 22:59:12.199 3194-3270/com.example.muralivss.tjson2_predictionactivity W/System.err:  ... 20 more
03-22 22:59:12.199 3194-3270/com.example.muralivss.tjson2_predictionactivity E/Buffer Error: Error: java.lang.NullPointerException: lock == null
03-22 22:59:12.200 3194-3270/com.example.muralivss.tjson2_predictionactivity D/Create Prediction Request:: > null
03-22 22:59:12.205 3194-3270/com.example.muralivss.tjson2_predictionactivity E/JSON Data: JSON data error!
03-22 22:59:31.554 3194-3200/com.example.muralivss.tjson2_predictionactivity W/art: Suspending all threads took: 14.009ms

提供的任何解决方案都将是令人欣慰的。

使用后尝试关闭BufferedReader实例:reader.close()

除此之外,它看起来还不错。还要尝试逐行调试断点,以查看错误的确切来源。

  1. HttpClient现在已弃用。请在此处查看更新http://developer.android.com/about/versions/marshmallow/android-6.0-changes.html

  2. 使用以下链接查看如何在android中处理httpurlconnection、json。http://developer.android.com/reference/java/net/HttpURLConnection.htmlhttp://developer.android.com/reference/android/util/JsonReader.html

  3. httpurlconnection android中处理json请求的示例代码http://danielnugent.blogspot.in/2015/06/updated-jsonparser-with.html

  4. 用于接收php 中的值

    $recValue=file_get_contents('php://input');$json=json_decode($recValue);$valueOne=$json["keyOne"];

如需更多参考,请查看此

http://php.net/manual/en/function.json-decode.php