-1

I have an autocompletetext for which I'm getting suggestions from web service using volley stringrequest. Now the problem is the ArrayList is not getting cleared so as every time I make a request old items gets added to the list. I tried adapter.clear() but it gives me NullPointerException. So any help to clear this so that the list does not holds old items will be much appreciated.

LogCat:

FATAL EXCEPTION: main
Process: com.sam.ubooktoday, PID: 24983
java.lang.NullPointerException
at com.sam.ubooktoday.view.fragments.HomeOptionTwo$1.onResponse(HomeOptionTwo.java:88) 
at com.sam.ubooktoday.view.fragments.HomeOptionTwo$1.onResponse(HomeOptionTwo.java:69) 
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5388)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:655)
at dalvik.system.NativeStart.main(Native Method)
// if you press 'na' json response is:

[
  "Manicure and Pedicure ",
  "Manicures",
  "Pedicures",
  "Student Specials Under 18 Years",
  "Hand & Foot Care and Repair",
  "Nail Art Design ",
  "Polish Change",
  "Kids Menu under 12 years",
  "Healthy Nail Dip in powder",
  "Nail Enhancement",
  "Full Set",
  "Fill Ins"
]
public class HomeOptionTwo extends Fragment implements TextWatcher{

    AutoCompleteTextView autoservice;
    ArrayList<String> arrList = new ArrayList<String>();
    ArrayAdapter<String> adapter;

    private static final String SERVICE = "http://example.com/android/services";

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

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

        autoservice = (AutoCompleteTextView)view.findViewById(R.id.service);


        autoservice.addTextChangedListener(this);





    }

    private void prepareMyList() {

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

                        try {



                            JSONArray jsonarray = new JSONArray(response);
                            for (int i = 0; i < jsonarray.length(); i++) {
                                //Toast.makeText(getActivity(), "services:" + jsonarray.optString(i), Toast.LENGTH_SHORT).show();

                                String strValue = jsonarray.getString(i);


                                arrList.add(strValue);

                            }

                                adapter = new ArrayAdapter<String>(
                                    getActivity(),
                                    android.R.layout.simple_dropdown_item_1line,
                                    arrList);


                            autoservice.setThreshold(1);

                            if(adapter!=null){adapter.clear();}
                            autoservice.setAdapter(adapter);






                        } 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(), "VolleyError" + error.toString(), Toast.LENGTH_LONG).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("phrase", autoservice.getText().toString());
                return params;
            }

        };

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


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        prepareMyList();

    }

    @Override
    public void afterTextChanged(Editable s) {

    }
}
Somnath Pal
  • 190
  • 1
  • 15

2 Answers2

1

You don't need to clear your adapter as you are setting new adapter everytime, but you need to clear your list so you can fetch and display new data from list.

So in prepareMyList() method, in try catch method write down below line first before JSONArray jsonarray = new JSONArray(response); line.

So it will look like,

     arrList = new ArrayList<String>();
     JSONArray jsonarray = new JSONArray(response);

and then check it will resolve your issue.

Vickyexpert
  • 3,147
  • 5
  • 21
  • 34
1

Same thing heppend to me lately, My problem was that the Filter was filtering my results since my results where not string matching with the typed text. It may be your case as well.

Try @Overrideing getFilter() on your array adapter and return a new Filter() that does nothing. like :

public Filter getFilter() {

            return new Filter() {

                @Override
                protected void publishResults(CharSequence constraint,FilterResults results) {


                }

                @Override
                protected FilterResults performFiltering(CharSequence constraint) {

                    return null;
                }
            };
        }
Ofek Ron
  • 8,354
  • 13
  • 55
  • 103