发送帖子请求时的排球错误

时间:2016-03-28 09:08:29

标签: android android-volley

我正在制作搜索功能,当用户在edittext中输入名称时,会向网络服务发送一个截击请求,结果会显示在列表视图中。我希望在每次文本更改时发送截击请求,这就是我使用edittextwatcher的原因。但每次文本更改时,我都会在Toast中收到com.android.volley.VolleyError:java.lang.NullPointerException错误。我不知道造成它的原因,而且logcat中也没有任何东西。 This是搜索的json响应。那么有人可以帮我纠正这个凌空错误吗?

POJO的:

public class GridItem {
    private String nameUrls, imageUrls, sportsCat, userId, userName;

    public GridItem() {
        super();
    }

    public String getImage() {
        return imageUrls;
    }

    public void setImage(String imageUrls) {
        this.imageUrls = imageUrls;
    }

    public String getName() {
        return nameUrls;
    }

    public void setName(String nameUrls) {
        this.nameUrls = nameUrls;
    }

    public String getSportsCat(){
        return sportsCat;
    }

    public void setSportsCat(String sportsCat){
        this.sportsCat = sportsCat;
    }

    public String getUserId(){
        return userId;
    }

    public void setUserId(String userId){
        this.userId = userId;
    }

    public String getUserName(){ return userName; }

    public void setUserName(String userName) { this.userName = userName; }
}

适配器:

public class ListAdapter extends ArrayAdapter<GridItem> {

    private Context mContext;
    int resource;
    private ArrayList<GridItem> mGridData = new ArrayList<GridItem>();

    public ListAdapter(Context mContext, int resource, ArrayList<GridItem> mGridData) {
        super(mContext, resource, mGridData);
        this.resource = resource;
        this.mContext = mContext;
        this.mGridData = mGridData;
    }

    public void setGridData(ArrayList<GridItem> mGridData) {
        this.mGridData = mGridData;
        notifyDataSetChanged();
    }

    @Override
    public GridItem getItem(int position) {
        return super.getItem(position);
    }



    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;

        ViewHolder holder;
        if (v == null) {
            holder = new ViewHolder();
            LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();

            v = inflater.inflate(R.layout.listrow, parent, false);
            holder.image = (ImageView) v.findViewById(R.id.item_image);
            holder.name = (TextView) v.findViewById(R.id.item_name);

            holder.image = (ImageView) v.findViewById(R.id.item_image);
            v.setTag(holder);
        } else {
            holder = (ViewHolder) v.getTag();
        }


        GridItem item = mGridData.get(position);
        Picasso.with(mContext)
                .load(item.getImage())
                .placeholder(R.drawable.placeholder)
                .fit()
                .into(holder.image);
        holder.name.setText(item.getName());


        return v;
    }

    class ViewHolder {
        ImageView image;
        TextView name;
    }

}

片段:

public class SearchName extends Fragment{

    private ListView mListView;
    private GridItem newItem;
    private ListAdapter mListAdapter;
    private ArrayList<GridItem> mGridData;
    private EditText editText;
    public static final String KEY_USERID = "user_id", KEY_NAME = "search_text", SPORTS_ID = "sports_id";
    private static final String SEARCH_MEMBER = "http://example.com/api/member/search/";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.searchname, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        editText = (EditText)view.findViewById(R.id.search_et);
        editText.addTextChangedListener(textWatcher);

        mListView = (ListView)view.findViewById(R.id.list_view);   

        mGridData = new ArrayList<>();
        mListAdapter = new ListAdapter(getContext(), R.layout.listrow, mGridData);
        mListView.setAdapter(mListAdapter);

    }



    private final TextWatcher textWatcher = new TextWatcher() {
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        public void afterTextChanged(Editable s) {
            if (s.length() == 0) {

            } else{
                searchmember();
            }
        }
    };

    private void searchmember(){
        StringRequest stringRequest = new StringRequest(Request.Method.POST, SEARCH_MEMBER,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {
                            JSONObject jObj = new JSONObject(response);

                            System.out.println(jObj);

                            String status = jObj.getString("status");

                            // Now check status value
                            if (status.equals("0")) {
                                Toast.makeText(getActivity(), "There was some error! Please try again.", Toast.LENGTH_LONG).show();
                            } else if (status.equals("1")) {


                                JSONArray result = jObj.getJSONArray("result");
                                for (int i = 0; i < result.length(); i++) {
                                    JSONObject json_data = result.getJSONObject(i);
                                    String name = json_data.getString("name");
                                    String user_id = json_data.getString("user_id");
                                    String username = json_data.getString("username");

                                    newItem = new GridItem();

                                    newItem.setName(name);
                                    newItem.setUserId(user_id);
                                    newItem.setUserName(username);
                                    if(json_data.has("profile_picture")){

                                        newItem.setImage(json_data.getString("profile_picture"));

                                    }else{

                                        Uri path = Uri.parse("android.resource://com.sam.fitlincsearch/" + R.drawable.default_profile);
                                        String image_def = path.toString();
                                        newItem.setImage(image_def);

                                    }


                                    mGridData.add(newItem);
                                }


                                mListAdapter.notifyDataSetChanged();

                            } else {
                                // Error in login. Get the error message
                                String errorMsg = jObj.getString("error_msg");
                                Toast.makeText(getActivity(), errorMsg, Toast.LENGTH_LONG).show();
                            }
                        } catch (JSONException e) {
                            // JSON error
                            e.printStackTrace();
                            Toast.makeText(getActivity(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getActivity(), error.toString(), Toast.LENGTH_LONG).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put(KEY_USERID, "1");  //get user_id from SQLite database.
                params.put(KEY_NAME, editText.getText().toString());
                return params;
            }

        };

        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        requestQueue.add(stringRequest);
    }
}

1 个答案:

答案 0 :(得分:0)

protected Map<String, String> getParams(){
            Map<String, String> params = new HashMap<String, String>();
            params.put("key1", value1);
            params.put("key2",value2);
            params.put("key3",value3);
            return checkParams(params);
        };


        private Map<String, String> checkParams(Map<String, String> map){               
            Iterator<Entry<String, String>> it = map.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, String> pairs = (Map.Entry<String, String>)it.next();
                if(pairs.getValue()==null){
                    map.put(pairs.getKey(), "");
                }
            }
            return map;             
        }

在Volley Error的情况下,将此作为errorResponse使用。我希望这能解决你的目的。

更新:

http://stackoverflow.com/questions/4709093/jquery-mobile-val-not-working

我认为这比在将每个值放入地图之前检查每个值更容易。