0

I have made an application by this tutorial http://javatechig.com/android/json-feed-reader-in-android

but when I run app in android studio there are following errors

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
            at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
            at org.json.JSONTokener.nextValue(JSONTokener.java:94)
            at org.json.JSONObject.<init>(JSONObject.java:156)
            at org.json.JSONObject.<init>(JSONObject.java:173)
            at com.example.administrator.myapplication5.FeedListActivity.getJSONFromUrl(FeedListActivity.java:127)
            at com.example.administrator.myapplication5.FeedListActivity$DownloadFilesTask.doInBackground(FeedListActivity.java:85)
            at com.example.administrator.myapplication5.FeedListActivity$DownloadFilesTask.doInBackground(FeedListActivity.java:67)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)

This is FeedListActivity class

public class FeedListActivity extends Activity {

    private ArrayList<FeedItem> feedList = null;
    private ProgressBar progressbar = null;
    private ListView feedListView = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_posts_list);
        progressbar = (ProgressBar) findViewById(R.id.progressBar);
        String url = "http://javatechig.com/api/get_category_posts/?dev=1&slug=android";
        new DownloadFilesTask().execute(url);
    }

    public void updateList() {
        feedListView= (ListView) findViewById(R.id.custom_list);
        feedListView.setVisibility(View.VISIBLE);
        progressbar.setVisibility(View.GONE);

        feedListView.setAdapter(new CustomListAdapter(this, feedList));
        feedListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> a, View v, int position, long id) {
                Object o = feedListView.getItemAtPosition(position);
                FeedItem newsData = (FeedItem) o;

                Intent intent = new Intent(FeedListActivity.this, FeedDetailsActivity.class);
                intent.putExtra("feed", newsData);
                startActivity(intent);
            }
        });
    }

    private class DownloadFilesTask extends AsyncTask<String, Integer, Void> {

        @Override
        protected void onProgressUpdate(Integer... values) {
        }

        @Override
        protected void onPostExecute(Void result) {
            if (null != feedList) {
                updateList();
            }
        }

        @Override
        protected Void doInBackground(String... params) {
            String url = params[0];

            // getting JSON string from URL
            JSONObject json = getJSONFromUrl(url);

            //parsing json data
            parseJson(json);
            return null;
        }
    }


    public JSONObject getJSONFromUrl(String url) {
        InputStream is = null;
        JSONObject jObj = null;
        String json = null;

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

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

            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 (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }

    public void parseJson(JSONObject json) {
        try {

            // parsing json object
            if (json.getString("status").equalsIgnoreCase("ok")) {
                JSONArray posts = json.getJSONArray("posts");

                feedList = new ArrayList<FeedItem>();

                for (int i = 0; i < posts.length(); i++) {
                    JSONObject post = (JSONObject) posts.getJSONObject(i);
                    FeedItem item = new FeedItem();
                    item.setTitle(post.getString("title"));
                    item.setDate(post.getString("date"));
                    item.setId(post.getString("id"));
                    item.setUrl(post.getString("url"));
                    item.setContent(post.getString("content"));
                    JSONArray attachments = post.getJSONArray("attachments");

                    if (null != attachments && attachments.length() > 0) {
                        JSONObject attachment = attachments.getJSONObject(0);
                        if (attachment != null)
                            item.setAttachmentUrl(attachment.getString("url"));
                    }

                    feedList.add(item);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}

Also, I found this answer (Android strange error) but it didn't work

I would be thankful to consider this error and help me to solve that.

Community
  • 1
  • 1
aziz
  • 93
  • 2
  • 8
  • 1
    `posts` is null and you get NPE on `posts.length()` as your logcat said : `int java.lang.String.length()' on a null object reference` – Shayan Pourvatan Apr 26 '15 at 09:08
  • Probably here ` for (int i = 0; i < posts.length(); i++) {` var posts is null – Piotr Golinski Apr 26 '15 at 09:08
  • do you have an idea why it is null ? how can I post a value to it ? – aziz Apr 26 '15 at 09:45
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – mbrig Jun 09 '16 at 17:17

3 Answers3

0

I know that maybe could be stupid but one error that was bother me was: JSONObject.put(java.lang.String, java.lang.Object)' on a null object reference This can happen even when you have not declared your json into your doInBackground. So when you write your code don't forget to insert: final JSONObject jsonresponse = new JSONObject();

Alexiscanny
  • 581
  • 7
  • 15
0

Give your app permission to get connected to the internet in AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
-1

The exception is thrown here:

try {
    jObj = new JSONObject(json);
} catch (JSONException e) {
    Log.e("JSON Parser", "Error parsing data " + e.toString());
}

json is null, and JSONObject can't be created. Please check why json is not assigned and remains null in this code:

String json = null;

// Making HTTP request
try {
    // defaultHttpClient
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);

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

    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 (UnsupportedEncodingException e) {
    e.printStackTrace();
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
Mattia Maestrini
  • 32,270
  • 15
  • 87
  • 94
  • The exception is null exception and therefore NullPointerException should be caught, not JSONException – Yehonatan Mar 03 '17 at 08:02
  • @Yehonatan No one say that you need to caught JSONException. If you read carefully you can see that i just pointed out *where* the code crashed. – Mattia Maestrini Mar 03 '17 at 08:26