vendredi 31 juillet 2015

Getting JSON from URL getting NullPointerException when creating array of objects from JSON

I am building a datasource for my app that pulls in JSON from our website and then creates an array of custom objects. However, after I get the JSON, and loop through the objects to create my own, I am getting a NullPointerException error.

Method for getting JSON from URL:

public static JSONObject getJSONObjectfromURL(String url)
    {
        InputStream mIs = null;
        String result = "";
        JSONObject jObjectLogin = null;
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httppost = new HttpGet(url);

            // Credentials
            String credentials = username + ":" + password;
            String credBase64 = Base64.encodeToString(credentials.getBytes(), Base64.DEFAULT).replace("\n", "");

            httppost.setHeader("Authorization", "Basic "+credBase64);

            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            mIs = entity.getContent();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            BufferedReader bufferReader = new BufferedReader(new InputStreamReader(mIs,"iso-8859-1"),8);
            StringBuilder stringBuilder = new StringBuilder();
            String line = null;
            while ((line = bufferReader.readLine()) != null) {
                if(line.trim().equals("\n"))
                    continue;
                stringBuilder.append(line + "\n");
            }
            mIs.close();
            result=stringBuilder.toString();
        }catch(Exception e){
            Log.e("log_tag", "Error converting result "+e.toString());
        }
        try {
            jObjectLogin = new JSONObject(result);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return jObjectLogin;
    }

Method for creating my custom objects from JSON:

public static ArrayList<PUCObjects.PUCNewsItem> getPUCNews(boolean isArchives, String assetId) throws IOException, JSONException {

    int maxPerPage = 10;

    String url;
    if (isArchives) {
        url = "http://ift.tt/1KGgu73"+maxPerPage+"&rootId="+assetId;
    } else {
        url = "http://ift.tt/1KGgu73"+maxPerPage;
    }

    JSONObject json = getJSONObjectfromURL(url);
    JSONArray jsonData = json.getJSONArray("data");
    ArrayList<PUCObjects.PUCNewsItem> items = new ArrayList<PUCObjects.PUCNewsItem>();
    PUCObjects.PUCNewsItem item = null;

    for (int i = 0; i < jsonData.length(); i++) {

        JSONObject jsonObject = jsonData.getJSONObject(i);

        item = new PUCObjects.PUCNewsItem();
        item.title = jsonObject.getString("title");
        item.summary = jsonObject.getString("summary");
        item.body = jsonObject.getString("body");
        item.author = jsonObject.getString("author");
        item.assetId = jsonObject.getString("asset_id");

        // Images
        JSONArray images = jsonObject.getJSONArray("images");
        for (int a = 0; a < images.length(); a++) {

            JSONObject imageObject = images.getJSONObject(a);
            item.imageUrlSmall = imageObject.getString("thumb_small");
            item.imageUrlMedium = imageObject.getString("thumb_large");
            item.imageUrlLarge = imageObject.getString("url");
            item.imageUrlExtraLarge = imageObject.getString("url_large");

            // Check to see if we have a high res image. If not, use the next largest image.
            if (item.imageUrlExtraLarge.length() == 0) {
                item.imageUrlExtraLarge = item.imageUrlLarge;
            }

        }

        // Date
        String createdDate = jsonObject.getString("created_date");
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd-H:m");
        Date date = null;
        try {
            date = format.parse(createdDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        DateFormat df = new DateFormat();
        if (date != null) {
            item.created_date = df.format("MMMM d, yyyy", date).toString();
        }

        items.add(item);

    }

    return items;

}//end

Logcat:

07-31 13:37:38.280  20132-20132/com.puc.mobile E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.NullPointerException
            at com.puc.mobile.news.PUCNewsListAdapter.getCount(PUCNewsListAdapter.java:54)
            at android.widget.ListView.setAdapter(ListView.java:466)
            at com.puc.mobile.news.PUCNewsList$DownloadPUCNews.onPostExecute(PUCNewsList.java:181)
            at com.puc.mobile.news.PUCNewsList$DownloadPUCNews.onPostExecute(PUCNewsList.java:159)
            at android.os.AsyncTask.finish(AsyncTask.java:631)
            at android.os.AsyncTask.access$600(AsyncTask.java:177)
            at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4950)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
            at dalvik.system.NativeStart.main(Native Method)

For some reason I am getting a NullPointerException when I am trying to display the results in a table. Having a feeling that for some reason items is coming back null, but not sure why.

Any ideas?

Aucun commentaire:

Enregistrer un commentaire