首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >android整型列表中未添加数据

android整型列表中未添加数据
EN

Stack Overflow用户
提问于 2018-02-20 20:23:01
回答 2查看 65关注 0票数 0

我有来自webservice的json数据,应该存储在两个列表中,String列表和Integer列表。用于字符串的文件可以很好地存储数据,但是用于整数的文件不能很好地存储数据。它会提示错误消息java.lang.IndexOutOfBoundsException: Index: 0,Size: 0

下面是完整的代码

代码语言:javascript
运行
复制
 public class Setup extends AppCompatActivity {
Button save;
EditText schoolPK;
String schoolname, classname, cityname, school_id,class_id;
ImageView logout;
GridView grid;
String cityid,classid;
int schoolid;
ArrayList<String> CityName, CityId;
private List<Integer> classID=new ArrayList<Integer>();
private List<String> listschools = new ArrayList<String>();
private List<String> listclasses = new ArrayList<String>();

Spinner schoolspinner;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String classnames = "classname";
public static final String schoolnames = "schoolname";
public static final String Email = "emailKey";
SharedPreferences sharedpreferences;

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



    CityName=new ArrayList<>();
    CityId = new ArrayList<>();
    //classID = new ArrayList<>();
   // schoolID = new ArrayList<>();

    schoolPK = (EditText) findViewById(R.id.schoolPK);


    final Spinner city = (Spinner) findViewById(R.id.city);
   final Spinner classspinner = (Spinner) findViewById(R.id.classname);
    String URL_countries="http://192.168.0.148/Election/api/school";
    JsonArrayRequest items = new JsonArrayRequest(URL_countries, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {
            for (int i = 0;i<response.length();i++){
                try {
                    JSONObject obj = response.getJSONObject(i);

                    String country=obj.getString("name_Ar");
                    String cityid = obj.getString("pK_ID");
                    CityId.add(cityid);
                    CityName.add(country);
                }


                catch (JSONException e) {
                    e.printStackTrace();
                }
                city.setAdapter(new ArrayAdapter<String>(Setup.this, android.R.layout.select_dialog_item, CityName));
            }
            //to get me the



        }
    }, new Response.ErrorListener(){

        @Override
        public void onErrorResponse(VolleyError error) {
            AlertDialog.Builder add = new AlertDialog.Builder(Setup.this);
            add.setMessage(error.getMessage()).setCancelable(true);
            AlertDialog alert = add.create();
            alert.setTitle("error");
            alert.show();
        }
    } );


    Controller.getInstance(Setup.this).addToRequestque(items);
    city.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            cityname = parent.getItemAtPosition(position).toString();

            cityid = CityId.get(position).toString();
            //CityId.clear();
            listclasses.clear();
            getclasses();

        } // to close the onItemSelected

        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

    classspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            classname = parent.getItemAtPosition(position).toString();


                class_id = classID.get(position).toString();

        }
        // to close the onItemSelected

        public void onNothingSelected(AdapterView<?> parent) {

        }
    });


    save = (Button) findViewById(R.id.save);
    save.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            sharedpreferences = getSharedPreferences("Settings", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedpreferences.edit();
            Intent intent =  new Intent(getApplicationContext(), Vote.class);

            editor.putString("schoolname", cityname);
            editor.putString("schoolid", cityid);
            editor.putString("classname", classname);
            editor.putString("classid", class_id);


            editor.apply();
        }
    });
}


public void getschools(){

    try {

        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
        String URL = "http://192.168.0.148/Election/api/School";
        JSONObject jsonBody = new JSONObject();
        // jsonBody.put("tblRegisteredUsers_nickName", username.getText().toString().trim());
        jsonBody.put("cityFK_ID", cityid);



        final String requestBody = jsonBody.toString();

        StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                //my response later should be changed

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("VOLLEY", error.toString());
            }
        })

        {
            @Override
            public String getBodyContentType() {
                return "application/json; charset=utf-8";
            }

            @Override
            public byte[] getBody() throws AuthFailureError {
                try {
                    return requestBody == null ? null : requestBody.getBytes("utf-8");
                } catch (UnsupportedEncodingException uee) {
                    VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
                    return null;
                }
            }
            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                String responseString;
                String json = null;
                try {
                    json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                responseString = String.valueOf(json).trim();
                ArrayList<Schoolresponse> list_response = new ArrayList<Schoolresponse>();
                Type listType = new TypeToken<List<Schoolresponse>>() {}.getType();
                list_response = new Gson().fromJson(responseString, listType);
               // schoolID= new ArrayList<>();
                for (int i = 0; i < list_response.size(); i++) {
                    School listItemData = new School();
                    listItemData.setName(list_response.get(i).getNameAr());
                    listItemData.setId(list_response.get(i).getPKID());

                    //schoolID.add(listItemData.getId());
                    listschools.add(listItemData.getName());
                }

                // i should have this piece of code for methods that are running in the background
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        schoolspinner.setAdapter(new ArrayAdapter<String>(Setup.this, android.R.layout.select_dialog_item, listschools));
                    }
                });


                return Response.success(list_response.toString(), HttpHeaderParser.parseCacheHeaders(response));
            }
        };

        requestQueue.add(stringRequest);
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }





public void getclasses(){

    final  Spinner classspinner = (Spinner) findViewById(R.id.classname);
    try {

        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
        String URL = "http://192.168.0.148/Election/api/classes";
        JSONObject jsonBody = new JSONObject();
        // jsonBody.put("tblRegisteredUsers_nickName", username.getText().toString().trim());
        jsonBody.put("SchoolFK_ID", cityid);



        final String requestBody = jsonBody.toString();

        StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                //my response later should be changed

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("VOLLEY", error.toString());
            }
        })

        {
            @Override
            public String getBodyContentType() {
                return "application/json; charset=utf-8";
            }

            @Override
            public byte[] getBody() throws AuthFailureError {
                try {
                    return requestBody == null ? null : requestBody.getBytes("utf-8");
                } catch (UnsupportedEncodingException uee) {
                    VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
                    return null;
                }
            }
            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                String responseString;
                String json = null;
                try {
                    json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                responseString = String.valueOf(json).trim();
                ArrayList<ClassResponse> list_response = new ArrayList<ClassResponse>();
                Type listType = new TypeToken<List<ClassResponse>>() {}.getType();
                list_response = new Gson().fromJson(responseString, listType);
                for (int i = 0; i < list_response.size(); i++) {
                    School listItemData = new School();
                    listItemData.setName(list_response.get(i).getNameAr());
                    listItemData.setId(list_response.get(i).getPKID());

                    classID.add(listItemData.getId());
                    listclasses.add(listItemData.getName());
                }

                // i should have this piece of code for methods that are running in the background
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        classspinner.setAdapter(new ArrayAdapter<String>(Setup.this, android.R.layout.select_dialog_item, listclasses));
                    }
                });
                // String Check =  yourModel.getMessagetitle();

                return Response.success(list_response.toString(), HttpHeaderParser.parseCacheHeaders(response));
            }
        };

        requestQueue.add(stringRequest);
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

这里是我正在讨论的区域,只有字符串列表(listclasses)存储数据,而整数(classID)列表不存储数据

代码语言:javascript
运行
复制
        protected Response<String> parseNetworkResponse(NetworkResponse response) {
                String responseString;
                String json = null;
                try {
                    json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                responseString = String.valueOf(json).trim();
                ArrayList<ClassResponse> list_response = new ArrayList<ClassResponse>();
                Type listType = new TypeToken<List<ClassResponse>>() {}.getType();
                list_response = new Gson().fromJson(responseString, listType);
                for (int i = 0; i < list_response.size(); i++) {
                    School listItemData = new School();
                    listItemData.setName(list_response.get(i).getNameAr());
                    listItemData.setId(list_response.get(i).getPKID());

                    classID.add(listItemData.getId());
                    listclasses.add(listItemData.getName());
                }

                // i should have this piece of code for methods that are running in the background
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        classspinner.setAdapter(new ArrayAdapter<String>(Setup.this, android.R.layout.select_dialog_item, listclasses));
                    }
                });
                // String Check =  yourModel.getMessagetitle();

                return Response.success(list_response.toString(), HttpHeaderParser.parseCacheHeaders(response));
            }
        };

希望我能得到正确的答案,谢谢!

EN

回答 2

Stack Overflow用户

发布于 2018-02-20 20:29:20

java.lang.IndexOutOfBoundsException:索引: 0,大小:0

表示您的array为空,并且您正在尝试从空数组访问数组元素。

您可以设置一个条件来检查数组长度是否大于0,然后继续使用它,如下所示:

代码语言:javascript
运行
复制
if(array != null && array.length > 0){
   // do parsing

}
票数 2
EN

Stack Overflow用户

发布于 2018-02-20 20:55:49

确保您的类School包含名为pK_ID的变量。仔细查看变量名中的大小写。

如果变量名与JSON标记不匹配,那么这将导致从JSON获取的内容为空,即使根据您的注释从URL获取了有效的JSON。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48885225

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档