如何解决java.lang.IndexOutOfBoundsException:无效的索引0,大小为0? [英] how to solve java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0?

查看:1156
本文介绍了如何解决java.lang.IndexOutOfBoundsException:无效的索引0,大小为0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个autocompletetextviews,在第一个autocompletetextview中,我正在使用json从服务器获取项目,以下是对此的响应

I have two autocompletetextviews,in first autocompletetextview i am getting items from server using json,the following is response for that

{"status":"success","clientlist":[{"cid":"1","name":"margi"},{"cid":"2","name":"steven"}],"productboxtype":[{"pbxid":"1","pbxname":"1 Dozen","qtyperbox":"12"},{"pbxid":"2","pbxname":"2 Dozens","qtyperbox":"24"},{"pbxid":"3","pbxname":"3 Dozens","qtyperbox":"36"}]}

我能够在我的第一个自动填充中获得姓名,并且可以正常工作

i am able to get names in my first autocomplete and it works fine,

现在的问题是假设用户选择项目"margi",其cid为1,因此我再次向服务器发送请求并尝试获取"margi"的产品名称,其响应为

Now issue is suppose user select item "margi" and its cid is 1,so again i am sending request to server and trying to get productnames of 'margi',and its response is

{"status":"success","clientproduct":[{"pid":"4","name":"kangan pair","unitprice":"1500","boxqty":"1","bulkprice":[{"minqty":"10","price":"1500"},{"minqty":"15","price":"1470"},{"minqty":"20","price":"1460"}]}]}

MAniActivity

MAniActivity

   public class MainActivity extends Activity {

    private AutoCompleteTextView acTextView;

    private String catidtemp;
    private String catid;

    JSONParser jsonParser = new JSONParser();
    private AutoCompleteTextView autoproduct;
    private static final String FEEDBACK_URL = "";
    private static final String FEEDBACK_SUCCESS = "status";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        acTextView = (AutoCompleteTextView) findViewById(R.id.autocmplte_clorder_clname);
        acTextView.setAdapter(new SuggestionAdapterClientList(this,acTextView.getText().toString()));

        autoproduct=(AutoCompleteTextView)findViewById(R.id.autocmplte_clorder_product);
        autoproduct.setAdapter(new SuggestionAdapterClientProduct(this, autoproduct.getText().toString()));

        acTextView.setOnItemClickListener(new OnItemClickListener() {


            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // TODO Auto-generated method stub


                JsonParseClientProduct jp=new JsonParseClientProduct();
                List<SuggestGetSetClientProduct> list1 = new ArrayList<SuggestGetSetClientProduct>();
                list1 =jp.getParseJsonWCF(autoproduct.getText().toString());
                if(position < list1.size())
                new AttemptLogin(Integer.parseInt(list1.get(position).getId())).execute();
            }
        });

    }

      class AttemptLogin extends AsyncTask<String, String, String> {

        boolean failure = false;
        private ProgressDialog pDialog;

        private int selected_cid=1;
        AttemptLogin(int selected_cid){
        this.selected_cid=selected_cid;
        }


        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Sending..");
            pDialog.setIndeterminate(true);
          //  pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @SuppressWarnings("unused")
        @Override
        protected String doInBackground(String...args) {
            //Check for success tag
            //int success;
            Looper.prepare();



             try {

                 JsonParseClientList jp=new JsonParseClientList();
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                 List<SuggestGetSetClientList> list =jp.getParseJsonWCF(acTextView.getText().toString());

                     for(int i = 0;i<list.size();i++)
                     {
                       if(list.get(i).getName().equals(acTextView.getText().toString()))
                       // params.add(new BasicNameValuePair("cid",list.get(i).getId()));

                           params.add(new BasicNameValuePair("cid",String.valueOf(selected_cid)));

                         //  catid=list.get(i).getId();
                      // catidtemp=list.get(i).getId();


                     }

                    catidtemp=String.valueOf(selected_cid);
                // catidtemp=list.get(i).getId();
                 System.out.println("cattttttiiiiddd????"+catidtemp);
                 params.add(new BasicNameValuePair("action", "clientproduct"));

                 System.out.println("su gayu server ma????"+params);

                 Log.d("request!", "starting");
                 // getting product details by making HTTP request
                 JSONObject json = jsonParser.makeHttpRequest (
                     FEEDBACK_URL, "POST", params);
                 //check your log for json response
                 Log.d("Login attempt", json.toString());

                 JSONObject jobj = new JSONObject(json.toString());
                 final String msg = jobj.getString("msg");




                 return json.getString(FEEDBACK_SUCCESS);

             }catch (JSONException e) {
                 e.printStackTrace();
             }
             return null;
        }

        // After completing background task Dismiss the progress dialog

        protected void onPostExecute(String file_url) {
            //dismiss the dialog once product deleted
            pDialog.dismiss();

            //parentcat.getText().clear();
    }}
      public class SuggestGetSetClientProduct {

            String id,name;
            public SuggestGetSetClientProduct(String id, String name){
                this.setId(id);
                this.setName(name);
            }
            public String getId() {
                return id;
            }

            public void setId(String id) {
                this.id = id;
            }

            public String getName() {
                return name;
            }

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

       public class JsonParseClientProduct {


            double current_latitude,current_longitude;
            public JsonParseClientProduct(){}
            public JsonParseClientProduct(double current_latitude,double current_longitude){
                this.current_latitude=current_latitude;
                this.current_longitude=current_longitude;
            }
            public List<SuggestGetSetClientProduct> getParseJsonWCF(String sName)
               {
                List<SuggestGetSetClientProduct> ListData = new ArrayList<SuggestGetSetClientProduct>();
                try {
                   String temp=sName.replace(" ", "%20");


                   System.out.println("what the...."+js);
                   URLConnection jc = js.openConnection();
                   BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));
                   String line = reader.readLine();
                   JSONObject jsonResponse = new JSONObject(line);
                   Log.d("test", "Response : " +jsonResponse);
                   JSONArray jsonArray = jsonResponse.getJSONArray("clientproduct");
                   for(int i = 0; i < jsonArray.length(); i++){
                       JSONObject r = jsonArray.getJSONObject(i);
                       ListData.add(new SuggestGetSetClientProduct(r.getString("pid"),r.getString("name")));
                   }


               } catch (Exception e1) {
                   // TODO Auto-generated catch block
                   e1.printStackTrace();
               }
                return ListData;

               }
        }
        public class SuggestionAdapterClientProduct extends ArrayAdapter<String>{


            protected static final String TAG = "SuggestionAdapter";
            List<String> suggestions = new ArrayList<String>();
           // private List<String> suggestions;
            public SuggestionAdapterClientProduct(Activity context, String nameFilter) {
                super(context, android.R.layout.simple_dropdown_item_1line);
                suggestions = new ArrayList<String>();
            }

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

            @Override
            public String getItem(int index) {
                return suggestions.get(index);
            }

            @Override
            public Filter getFilter() {
                Filter myFilter = new Filter() {
                    @Override
                    protected FilterResults performFiltering(CharSequence constraint) {
                        FilterResults filterResults = new FilterResults();
                        JsonParseClientProduct jp=new JsonParseClientProduct();
                        if (constraint != null) {
                            // A class that queries a web API, parses the data and
                            // returns an ArrayList<GoEuroGetSet>

                            List<SuggestGetSetClientProduct> new_suggestions = new ArrayList<SuggestGetSetClientProduct>();
                            new_suggestions =jp.getParseJsonWCF(constraint.toString());
                            Log.d("test", "Size of array : " +new_suggestions.size());
                          //List<SuggestGetSetClientProduct> new_suggestions =jp.getParseJsonWCF(constraint.toString());
                            suggestions.clear();
                            /*for (int i=0;i<new_suggestions.size();i++) {
                            suggestions.add(new_suggestions.get(i).getName());
                        }*/

                        for (int i=0;i<new_suggestions.size();i++) {
                            String name=new_suggestions.get(i).getName();
                            String id=new_suggestions.get(i).getId();
                            System.out.println("checis id"+id);
                            if(name.contains(constraint)){
                            suggestions.add(new_suggestions.get(i).getName());


                               }   
                        }
                            // Now assign the values and count to the FilterResults
                            // object
                            filterResults.values = suggestions;
                            filterResults.count = suggestions.size();
                        }
                        return filterResults;
                    }

                    @Override
                    protected void publishResults(CharSequence contraint,
                            FilterResults results) {
                        if (results != null && results.count > 0) {
                            notifyDataSetChanged();
                        } else {
                            notifyDataSetInvalidated();
                        }
                    }
                };
                return myFilter;
            }
        }
}

推荐答案

java.lang.IndexOutOfBoundsException:无效的索引0,大小为0,位于 java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)

java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)

我相信问题就在这里,

 List<SuggestGetSetClientProduct> new_suggestions =jp.getParseJsonWCF(constraint.toString());

您初始化了ArrayList吗?

List<SuggestGetSetClientProduct> new_suggestions = new ArrayList<SuggestGetSetClientProduct>;

在进入For循环之前,先检查ArrayList的大小.

Check the size of the ArrayList first before it goes to For loop.

您的代码应类似于

                if (constraint != null) {

                   List<SuggestGetSetClientProduct> new_suggestions = new ArrayList<SuggestGetSetClientProduct>();
                   new_suggestions =jp.getParseJsonWCF(constraint.toString());
                   Log.d("test", "Size of array : " +new_suggestions.size());

               // rest code here..//

此外,您没有在SuggestionAdapterClientProduct类中初始化列表,

Also, you didn't initialize your list in SuggestionAdapterClientProduct class,

 private List<String> suggestions;

通过以下方式初始化您的arrayList

Initialize your arrayList by,

List<String> suggestions = new ArrayList<String>();

在那个班上.

这篇关于如何解决java.lang.IndexOutOfBoundsException:无效的索引0,大小为0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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