Поиск в представлении списка во фрагменте и адаптере, расширенный с помощью BaseAdapter Получение сбоев - PullRequest
0 голосов
/ 26 февраля 2019

Приложение падает при поиске текста в ListView, реализованном в Fragment.Я сделал fragment Адаптер и doSearch();метод который на fragmentdoSearch() метод описывает beforeTextChanged, onTextChanged, afterTextChanged.имена ArrayList, которые поступают из API в формате JSON.Хотите искать имена, но приложение аварийно завершает работу и получает сообщение об ошибке. В Adapter расширено на BaseAdapter.Как я могу решить эту ошибку и найти определенный текст в виде списка.

Может быть что-то не так в методе filter ().Невозможно распознать проблему.

Сейчас в нижней строке адаптера отображается ошибка:

textView.setText(names.get(position));

Ошибка:

java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.get(ArrayList.java:411)
    at novumlogic.payment.adater.CustomListAdapter.getView(CustomListAdapter.java:164)
    at android.widget.AbsListView.obtainView(AbsListView.java:2367)
    at android.widget.ListView.measureHeightOfChildren(ListView.java:1326)
    at android.widget.ListView.onMeasure(ListView.java:1233)
    at android.view.View.measure(View.java:19756)
    at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
    at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)

Фрагмент

public class CateFragment extends Fragment
{


    View rootView;
    String loadedString;

            CustomListAdapter institutionAdapter;
            ArrayList<Movie> institutions;
String j;

    private ArrayList<String> images;
    private ArrayList<String> names;
String l;
    private ListView listView;

    //ArrayList<listView> mAllData=new ArrayList<DrinksList>();


public CateFragment() {

        }



@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
   CateFragment activity = new CateFragment();
    Bundle savedData = activity.getSavedData();
    Log.d("idssssbe",""+savedData);






        }


    @Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_gridcatefragment, container, false);
        listView = (ListView) rootView.findViewById(R.id.list);


        images = new ArrayList<>();
        names = new ArrayList<>();



        String id =getActivity().getIntent().getStringExtra("j");
        Log.d(TAG, "idcate: " + id);
        SharedPreferences.Editor editor = getActivity().getSharedPreferences(MySharedPreffilter,MODE_PRIVATE).edit();
        editor.putString("id",id);*/





        getClientsList();


        doSearch();
        return rootView;








        }


    private void doSearch() {

         final EditText et = (EditText)rootView.findViewById(R.id.search_viewSP);
        et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

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

            }

            @Override
            public void afterTextChanged(Editable s) {
                String text = et.getText().toString().toLowerCase(Locale.getDefault());
                filter(text);
            }
        });
    }







private void getClientsList() {
    String tag_string_req = "req_register";
    String selectedId = null;
    SharedPreferences prefs = getContext().getSharedPreferences(MySharedPrefLogin, MODE_PRIVATE);
    loadedString = prefs.getString("selectedId", selectedId);
    Log.d("hdshfh","dfsfh"+loadedString);
    String id = loadedString;
    Log.d("check",""+id);
        String url = AppConfig.Base_Url +AppConfig.App_api+AppConfig.URL_SubCat+id;
    Log.d("check1",""+url);

    final ProgressDialog loading = ProgressDialog.show(getContext(), "Please wait...","Fetching data...",false,false);


    final StringRequest jsonObjReq = new StringRequest(Request.Method.GET,url, new Response.Listener<String>() {

           @Override
public void onResponse( String response) {
               loading.dismiss();

        try {

            String jsonObjReq = null;
            JSONObject obj = new JSONObject(String.valueOf(response));
            String status = obj.getString("status");
            String message =obj.getString("message");
            Log.d(TAG, "Register Response11: " + status);
            Log.d(TAG, "Register Response22: " + message);
            JSONObject obj1=new JSONObject(String.valueOf(obj));
            JSONObject result = obj.getJSONObject("result");
            Log.d(TAG, "Register Response33: " + result);
            JSONArray category=result.getJSONArray("category");
            Log.d(TAG, "Register Response44: " + category);
if (category.length()==0)
{
    Toast.makeText(getContext(), "No Merchant registered for selected category with FeeDeposit", Toast.LENGTH_SHORT).show();
    Fragment fragment = new GridCateFragment();
    FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.frame_content, fragment);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();

}
            for(int i=0;i<category.length();i++) {
                JSONObject object = category.getJSONObject(i);
                Log.d(TAG, "Register Response54: " + object);
                String k = object.getString("image");
                j = object.getString("id");
                String l = (object.getString("name"));
                Log.d("frray", " " + k);
                Log.d("Array1", " " + l);
                Log.d("iss", "" + j);
                //getting image url and title from json object
                names.add(l);
                images.add(k);


                // institutionAdapter.notifyDataSetChanged();
            }
        }catch (JSONException e){
        e.printStackTrace();
        }


           institutionAdapter = new CustomListAdapter(getContext(), names, images);


           //Adding adapter to gridview
           listView.setAdapter(institutionAdapter);
        }

        }, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
        Toast.makeText(getContext(), "Error", Toast.LENGTH_SHORT).show();
        }
        });
        Appcontrol.getInstance().addToRequestQueue(jsonObjReq,tag_string_req);
        }


    public void filter(String charText) {
        charText = charText.toLowerCase(Locale.getDefault());
       names .clear();
        if (charText.length() == 0) {
            names.add(l);
        } else {
           // for (listView wp : names) {
                /*if (names.toLowerCase(Locale.getDefault())
                        .contains(charText)) {names.add(l);
                }*/
          //  }
        }
        institutionAdapter.notifyDataSetChanged();
        //notifyDataSetChanged();
    }

        }

Адаптер

public class CustomListAdapter extends BaseAdapter {
    int count;
    ArrayList<Movie> institutions;
    private Context context;
    private ArrayList<String> names;
    private ArrayList<String> images;
    ImageLoader imageLoader = Appcontrol.getInstance().getImageLoader();

    public CustomListAdapter(Context context, ArrayList<String> names, ArrayList<String> images) {
        this.context = context;
        this.names = names;
        this.images = images;
    }



    @Override
    public int getCount() {
    return  images.size();
    }

    @Override
    public Object getItem(int position) {
        return images.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

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

        LinearLayout linearLayout = new LinearLayout(context);
        //l1.setOrientation(SquareLayout)
        linearLayout.setOrientation(LinearLayout.HORIZONTAL);

        //Creating a textview to show the title
        TextView textView = new TextView(context);
        textView.setText(names.get(position));



        //NetworkImageView
        NetworkImageView networkImageView = new NetworkImageView(context);

        //networkImageView.setImageResource(mThumbIds[position]);
        networkImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        networkImageView.setLayoutParams(new GridView.LayoutParams(200, 200));

        //Initializing ImageLoader
        imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
        imageLoader.get(images.get(position), ImageLoader.getImageListener(networkImageView, R.mipmap.ic_launcher, android.R.drawable.ic_dialog_alert));

        //Setting the image url to load
        networkImageView.setImageUrl(images.get(position),imageLoader);
        linearLayout.addView(networkImageView);
        linearLayout.addView(textView);
        return linearLayout;
    }






}
...