INT org.json.JSONArray.length()上的一个空对象引用 [英] int org.json.JSONArray.length() on a null object reference

查看:1956
本文介绍了INT org.json.JSONArray.length()上的一个空对象引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用凌空库连接到服务器,我有一个交易类和服务器类与此codeS:

I'm using volley library to connect to server and I have a Transaction class and a Server class with this codes:

横贯:

public class Trans extends Server {
    public Object suggest(Context context) {
        return connect("xxxxxxx", Request.Method.GET);
    }
}

服务器:

public Object connect(String url, int method) {
    final Object[] object = {null};
    StringRequest postRequest;
    postRequest = new StringRequest(method, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    object[0] = response;
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                }
            }
    ) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<String, String>();
            return params;
        }

        @Override
        public String getBodyContentType() {
            return "application/x-www-form-urlencoded; charset=UTF-8";
        }
    };
    int socketTimeout = 20000;
    RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    postRequest.setRetryPolicy(policy);
    AppController.getInstance().addToRequestQueue(postRequest);
    return object[0];
}

但是,当我试图让 JSONArray 与此:

@Override
protected void onResume() {
    ArrayList<Suggests> arrayList = new ArrayList<>();
    JSONArray jsonArray = (JSONArray) trans.suggest(MainActivity.this);
    for (int i = 0; i < jsonArray.length(); i++) {
        try {
            JSONObject item = (JSONObject) jsonArray.get(i);
            Suggests suggests = new Suggests();
            suggests.title = item.getString("title");
            suggests.type = item.getString("type");
            arrayList.add(suggests);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    super.onResume();
}

应用程序强制关闭,我有这个错误的logcat

java.lang.RuntimeException: Unable to resume activity {ir.aftabeshafa.shafadoc/ir.aftabeshafa.shafadoc.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONArray.length()' on a null object reference

有什么问题,我应该如何解决?

What's the problem and how can I fix it?

推荐答案

去关建议,意见,

第1步定义将传递沿着你想要的结果的接口。在&LT; T&GT; 是一个泛型类型,这样你就可以回到你想要的任何数据。你会看到,在步骤2

Step 1 Define an interface that will pass-along the result you want. The <T> is a generic type, so you can return whatever data you want. You'll see that in Step 2.

public interface AsyncResponse<T> {
    void onResponse(T response);
}

第2步更新服务器和跨类借此作为一个参数

Step 2 Update the Server and Trans classes to take this as a parameter

public class Server {

    public void connect(String url, int method, final AsyncResponse<String> asyncResponse) {
        StringRequest request = new StringRequest(method, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (asyncResponse != null) {
                    asyncResponse.onResponse(response);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("VolleyError", error.getMessage());
                Log.e("VolleyError", new String(error.networkResponse.data));
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                return params;
            }

            @Override
            public String getBodyContentType() {
                return "application/x-www-form-urlencoded; charset=UTF-8";
            }
        };

        int socketTimeout = 20000;
        RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        request.setRetryPolicy(policy);

        AppController.getInstance().addToRequestQueue(request);
    }
}


侧的问题:你是否真的需要在上下文?它不使用...

public class Trans extends Server {
    public void suggest(Context context, AsyncResponse<String> asyncResponse) {
        connect("xxxxxxxx", Request.Method.GET, asyncResponse);
    }
}

第3步:使用像这样的方法来获得一个回调的结果。 //jsonplaceholder.typi$c$c.com/users HTTP测试一>,它返回10 User对象的JSONArray。

Step 3 Use your method like so to get a result in a callback. This was tested against the url http://jsonplaceholder.typicode.com/users, which returns a JSONArray of 10 User objects.

ArrayAdapter 加入了一个完整的例子,因为它没有出现在的ArrayList 的问题是有益的为了任何东西。

The ArrayAdapter was added for a full example since it didn't appear the ArrayList in the question was useful for anything.

public class MainActivity extends AppCompatActivity {

    private ArrayList<User> arrayList;
    private Trans trans;
    private ArrayAdapter<User> adapter;
    private ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        trans = new Trans();
        arrayList = new ArrayList<User>();

        adapter = new ArrayAdapter<User>(MainActivity.this, android.R.layout.simple_list_item_1, arrayList);
        listView = (ListView) findViewById(android.R.id.list);
        listView.setAdapter(adapter);

    }

    @Override
    protected void onResume() {
        trans.suggest(MainActivity.this, new AsyncResponse<String>() {
            @Override
            public void onResponse(String response) {
                arrayList.clear(); // prevent duplicate data

                try {
                    // The URL that was tested returns a JSONArray
                    // Change to JSONObject, if necessary
                    JSONArray jsonArray = new JSONArray(response);

                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject item = (JSONObject) jsonArray.get(i);
                        User user = new User();
                        user.username = item.getString("name");
                        user.email = item.getString("email");
                        arrayList.add(user);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                // Notify since the arrayList has changed the adapter
                adapter.notifyDataSetChanged();
            }
        });

        super.onResume();
    }
}

这篇关于INT org.json.JSONArray.length()上的一个空对象引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆