Error while parsing JSON

user3258884

I am new to Android development. I'm sending JSON data from Android to my PHP server.

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;

    }


}

Im getting 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
Fazil Uruniyengal

You cant make a Network call from a main thread.This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in AsyncTask .

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

error while parsing Json in javascript

Error while parsing JSON in python

Error while Parsing JSON to Object

", or } expected while parsing object/hash" error while parsing a JSON file

Error while parsing JSON babel failure

Error message while parsing json in Python

valueNotFound error while parsing Json response in IOS

Error while parsing date from json to object

Error while parsing JSON Object in Java Android

Null error while parsing JSON file in Flutter

Getting error while parsing the the JSON data into android

Error while parsing json file with objects

error while parsing JSON file, probally a hidden value on the JSON content

flutter type error while parsing json data using json serialisable

Parsing of JSON returns error while the JSON seems to be fine

Error While parsing in JSP

Docker build-push action: Error while parsing json secret

Lexical Error while parsing JSON file for chef-client

Error while parsing JSON data received via Alamofire (Swift)

JSON parsing throws error for nil while payload has no null values

Escaped double quotes in JSON string causing error while parsing

Error while parsing Json format data in c#

Babel/browserify throws "Error while parsing JSON - Unexpected token o"

Runtime error while parsing a JSON byte stream with an embedded array

Macro throws a weird error while parsing content from json

Error while parsing JSON in Swift, [String:Any] won't work

error Unexpected end of JSON input while parsing near '...","tarball":"https://'

Python Error while parsing JSON when string changes

mapper_parsing_exception error for JSON array while adding into ES