1

I keep getting the error with my Json Parser. Error parsing data org.json.JSONException: End of input at character 0 of. Couldn't get any data from the url. I have permitted the the app to access the internet in the main. Can someone please help me out with what is wrong with my code? I have verified with JSONLint that my url is a valid JSON.

Sample of URL

[
{
    "tid": "352",
    "title": "10+2 Rule",
    "acronym": [],
    "description": "<p>“United States Customs and Border Protection (CBP) has announced a new rule, known as the Importer Security Filing (ISF) or more commonly called 10+2; which requires cargo information, for security purposes, to be transmitted to the agency at least 48 hours before goods are loaded onto an ocean vessel for shipment into the U.S. 10+2 is pursuant to section 203 of the SAFE Port Act, and requires importers to provide 10 data elements to CBP, as well as 2 more data elements from the carrier. On January 26, 2010, 10+2 was officially effective and importers are required to comply. If compliance is not met, they can face fines up to $5,000 for each violation.&nbsp;The proposed rule was known to the trade as both the ‘Importer Security Filing proposal’ and the ‘10 + 2 proposal’. The name “10 + 2” is shorthand for the number of advance data elements CBP will collect.</p><p>The following 10 data elements are required from the importer:</p><ol><li>Manufacturer (or supplier) name and address</li><li>Seller (or owner) name and address</li><li>Buyer (or owner) name and address</li><li>Ship-to name and address</li><li>Container stuffing location</li><li>Consolidator (stuffer) name and address</li><li>Importer of record number/foreign trade zone applicant identification number</li><li>Consignee number(s)</li><li>Country of origin</li><li>Commodity Harmonized Tariff Schedule number</li></ol><p>From the carrier, 2 data elements are required:</p><ol><li>Vessel stow plan</li><li>Container status messages”</li></ol>",
    "sources": [
        {
            "tid": "350"
        }
    ]
},
{
    "tid": "354",
    "title": "24-Hour Rule",
    "acronym": [],
    "description": "<p><span>“An amendment to the U.S. Trade Act of 2002 requiring that sea carriers and Non-Vessel Operating Common Carriers (NVOCCs) provide U.S. Customs and Border Protection (CBP) with detailed descriptions of the contents of sea containers bound for the United States 24 hours before the container is loaded on board a vessel. The cargo information required is that which is reasonably necessary to enable high-risk shipments to be identified for purposes of ensuring cargo safety and security and preventing smuggling pursuant to the laws enforced and administered by CBP. This information must be detailed and be transmitted electronically through approved systems.”&nbsp;</span><a href=\"http://www.cbp.gov/xp/cgov/trade/trade_outreach/advance_info/\">Learn more</a><span>.</span></p>",
    "sources": [
        {
            "tid": "350"
        }
    ]
},
{
    "tid": "356",
    "title": "3rd Party Logistics",
    "acronym": "3PL",
    "description": "<p>\"<span>A company that provides logistics services to customers who outsource part of, or all of, their supply chain management functions (i.e. transportation, warehousing, freight forwarding, distribution, cross docking, packaging, etc.)\"</span></p>",
    "sources": [
        {
            "tid": "350"
        }
    ]
},

JsonParser

public class JsonParser{

static InputStream is = null;
static JSONArray jarray = null;
static String json = "";



public JSONArray getJSONFromUrl(String url1) {

    StringBuilder builder = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url1);
    try {
        HttpResponse response = client.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        } else {
            Log.e("==>", "Failed to download file");
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // try parse the string to a JSON object
    try {
        jarray = new JSONArray( builder.toString());
        //System.out.println(""+jarray);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jarray;

}
}

Main Java

public class Glossary extends ListActivity {
private ProgressDialog pDialog;

// URL to get contacts JSON
private static String url1 = "https://192.250.28.153/rest/glossary-items";
// JSON Node names

private static final String TAG_TID = "tid";
private static final String TAG_TITLE = "title";
private static final String TAG_ACRONYM = "acronym";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_SOURCES = "sources";

// contacts JSONArray
JSONArray contacts = null;

// Hashmap for ListView
ArrayList<HashMap<String, String>> glossaryList;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_glossary);
    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        System.out.println("*** My thread is now configured to allow connection");
    }
    glossaryList = new ArrayList<HashMap<String, String>>();

    ListView lv = getListView();

    // Calling async task to get json
    new GetData().execute();
}

/**
 * Async task class to get json by making HTTP call
 */
private class GetData extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(Glossary.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        String str = "JSON STRING";

        JsonParser sh = new JsonParser();

        // Making a request to url and getting response
        JSONArray jsonStr = sh.getJSONFromUrl(url1);

        if (jsonStr != null){
        try{
        // looping through All Contacts
        for (int i = 0; i <= jsonStr.length(); i++) {

                JSONObject c = jsonStr.getJSONObject(i);

                String tid = c.getString(TAG_TID);
                String title = c.getString(TAG_TITLE);
                String acronym = c.getString(TAG_ACRONYM);
                String description = c.getString(TAG_DESCRIPTION);


                // tmp hashmap for single contact
                HashMap<String, String> contact = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                contact.put(TAG_TID, tid);
                contact.put(TAG_TITLE, title);
                contact.put(TAG_ACRONYM, acronym);
                contact.put(TAG_DESCRIPTION, description);

                // adding contact to contact list
                glossaryList.add(contact);
            }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("JsonParser", "Couldn't get any data from the url");
            }
            return null;

    }
        @Override
        protected void onPostExecute (Void result){
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    Glossary.this, glossaryList,
                    R.layout.list_item, new String[]{TAG_TITLE}, new int[]{R.id.title});

            setListAdapter(adapter);
        }



}
}

just in case here is also my android manifest

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.wizzard.james.glossary"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    <!-- Internet permission -->
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name="com.wizzard.james.glossary.Glossary" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!-- Single List Item Activity -->
        <activity
            android:label="Contact"
           android:name="com.wizzard.james.glossary.SingleContactActivity" >
        </activity>
    </application>

    </manifest>
mcdubs
  • 11
  • 2
  • the json from the url start with "[" but ends with "}", it needs to end with "]" to indicate the end of the json array. – faljbour Apr 08 '15 at 02:37
  • @faljbour that was just a small part from the url. The glossary is pretty long so i just idd a sample and forgot to close out the end of it – mcdubs Apr 08 '15 at 02:44
  • the only thing I would suggest is to see if you are receiving the complete json array, – faljbour Apr 08 '15 at 02:50
  • would it be because sources is located in another url? @faljbour – mcdubs Apr 08 '15 at 03:07
  • the exception is occurring at line jarray = new JSONArray( builder.toString()), so I would put a break point at that line and look at the complete string in builder or maybe print it out before you pass it to the JSONArray constructor. Also, it is possible your httpget is not working, and you maybe getting an exception from httpget and your builder object is empty. – faljbour Apr 08 '15 at 03:16

0 Answers0