简体   繁体   English

JSON空对象引用错误{Android}

[英]JSON null Object Reference Error {Android}

I have made an application by this tutorial http://javatechig.com/android/json-feed-reader-in-android 我已经通过本教程http://javatechig.com/android/json-feed-reader-in-android提出了申请

but when I run app in android studio there are following errors 但是当我在android studio中运行应用程序时,出现以下错误

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 这是FeedListActivity类

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 另外,我找到了这个答案( Android奇怪的错误 ),但是没有用

I would be thankful to consider this error and help me to solve that. 我很乐意考虑这个错误并帮助我解决该错误。

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. 我知道这可能是愚蠢的,但令我困扰的一个错误是: JSONObject.put(java.lang.String, java.lang.Object)' on a null object reference即使您没有将json声明为您的doInBackground。 So when you write your code don't forget to insert: final JSONObject jsonresponse = new JSONObject(); 因此,在编写代码时,请不要忘记插入: final JSONObject jsonresponse = new JSONObject();

授予您的应用权限以通过AndroidManifest.xml连接到互联网

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

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. json为null,因此无法创建JSONObject。 Please check why json is not assigned and remains null in this code: 请检查为什么未分配json并在此代码中将其保留为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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM