解析JSON时出错

时间:2014-05-01 08:00:40

标签: android json

我是Android开发的新手。我将JSON数据从Android发送到我的PHP服务器。

MainActivity.java

public class MainActivity extends Activity implements OnClickListener {
        FlyOutContainer root;
        private static final String TAG_POSTS = "posts";

        String sideMenu[] = { "Place New Report", "My Reports", "Short By",
                "Water", "Road", "Electricity", "Construstion",
                "Waste Disposal and Electricity", "Nearby Reports", "Others",
                "Settings" };
        FlyOutContainer fly;
    int l;
    JSONArray mComments = null;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);

            requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);

            l=1;
            final String READ_COMMENTS_URL = "http://sanoawaz.orgfree.com/comments2.php";
            JSONParser jParser = new JSONParser();
            Log.d("good", "tillhere2");
            JSONObject jsoni = jParser.getJSONFromUrl(READ_COMMENTS_URL);
            Log.d("good", "tillhere3");
            try {
                mComments = jsoni.getJSONArray(TAG_POSTS);
                l = mComments.length();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                l = 10;
            }

JSONParser.java

package com.sdmple.flybar;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }


    public JSONObject getJSONFromUrl(final String url) {

        // Making HTTP request
        try {
            // Construct the client and the HTTP request.
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            // Execute the POST request and store the response locally.
            HttpResponse httpResponse = httpClient.execute(httpPost);
            // Extract data from the response.
            HttpEntity httpEntity = httpResponse.getEntity();
            // Open an inputStream with the data content.
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            Log.e("Buffer Error", "Error converting result " + e.toString());
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            Log.e("Buffer Error", "Error converting result " + e.toString());
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        try {
            // Create a BufferedReader to parse through the inputStream.
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            // Declare a string builder to help with the parsing.
            StringBuilder sb = new StringBuilder();
            // Declare a string to store the JSON object data in string form.
            String line = null;

            // Build the string until null.
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
                json = sb.toString().substring(0, sb.toString().length() - 1);
            }

            // Close the input stream.
            is.close();
            // Convert the string builder data to an actual string.
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // Try to 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 the JSON Object.
        return jObj;

    }


    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity 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, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // 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 String
        return jObj;

    }

    public JSONObject getJSONFromUrl2(final String url) {

        // Making HTTP request
        try {
            // Construct the client and the HTTP request.
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            // Execute the POST request and store the response locally.
            HttpResponse httpResponse = httpClient.execute(httpPost);
            // Extract data from the response.
            HttpEntity httpEntity = httpResponse.getEntity();
            // Open an inputStream with the data content.
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            Log.e("Buffer Error", "Error converting result " + e.toString());
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            Log.e("Buffer Error", "Error converting result " + e.toString());
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        try {
            // Create a BufferedReader to parse through the inputStream.
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            // Declare a string builder to help with the parsing.
            StringBuilder sb = new StringBuilder();
            // Declare a string to store the JSON object data in string form.
            String line = null;

            // Build the string until null.
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            // Close the input stream.
            is.close();
            // Convert the string builder data to an actual string.
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // Try to 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 the JSON Object.
        return jObj;

    }


}

我得到JSONObject jsoni = jParser.getJSONFromUrl(READ_COMMENTS_URL);

Comments2.php

<?php


require("config2.inc.php");

//initial query
$query = "Select * FROM posts";

//execute query
try {
    $stmt   = $db->prepare($query);
    $result = $stmt->execute();
}
catch (PDOException $ex) {
    $response["success"] = 0;
    $response["message"] = "Database Error!";
    die(json_encode($response));
}


$rows = $stmt->fetchAll();


if ($rows) {
    $response["success"] = 1;
    $response["message"] = "Post Available!";
    $response["posts"]   = array();

    foreach ($rows as $row) {
        $post             = array();
        $post["username"] = $row["username"];
        $post["location"]    = $row["location"];
        $post["discreption"]  = $row["discreption"];


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

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


} else {
    $response["success"] = 0;
    $response["message"] = "No Post Available!";
    die(json_encode($response));
}

?>

logcat的

05-01 07:15:01.859: D/Login Successful!(1531): {"message":"Login successful!","success":1}
05-01 07:15:02.407: D/good(1531): tillhere2
05-01 07:15:02.407: D/AndroidRuntime(1531): Shutting down VM
05-01 07:15:02.407: W/dalvikvm(1531): threadid=1: thread exiting with uncaught exception (group=0xa4c46648)
05-01 07:15:02.407: E/AndroidRuntime(1531): FATAL EXCEPTION: main
05-01 07:15:02.407: E/AndroidRuntime(1531): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sdmple.flybar/com.sdmple.flybar.MainActivity}: android.os.NetworkOnMainThreadException

1 个答案:

答案 0 :(得分:1)

您无法从主线程进行网络调用。当应用程序尝试在其主线程上执行网络操作时,将引发此异常。在AsyncTask中运行您的代码。