如何在单个字符串中存储id

时间:2016-02-27 06:08:06

标签: android button

我试图按照复选框选择获取id,使用模型类,但我想将单个id存储在单个字符串中,用户选择复选框然后单击按钮,在按钮上单击i用户将获得string中的ID。它不能正常工作,我的代码可以帮助我吗?

 @Override
        public void onClick(View v) {
            String data = "";

            tet=new ArrayList<String>();

            for (int i = 0; i < aList.size(); i++) {
                 singleStudent = aList.get(i);
                if (singleStudent.isselected() == true) {
                    data = data + "\n" + singleStudent.getPOOJA_LISTING_ID().toString();


                    tet.add(singleStudent.getPOOJA_LISTING_ID());

                    System.out.println("firstid" + tet);
                }
            }

            try {
                for(int j=0; j<tet.size(); j++)
                {
                    Toast.makeText(PoojaSelection.this,
                            "Selected Pooja: \n" + tet.get(j), Toast.LENGTH_LONG)
                            .show();
                    String oneid=tet.get(0);
                    String secid=tet.get(1);
                    String thirdid=tet.get(2);
                    String fourthid=tet.get(3);
                    String fifthid=tet.get(4);
                    System.out.println("tetaray" + oneid+secid+thirdid+fourthid+fifthid);
                }
            }
            catch (Exception e)
            {

            }



        }

2 个答案:

答案 0 :(得分:1)

将其更改为...您正在根据索引(例如.. 1,2,3)访问列表而不是列表的循环索引(如get(j))..

String oneid="",secid="", thirdid="" ,fourthid="", fifthid="";

for(int j=0; j<tet.size(); j++)
{
    Toast.makeText(PoojaSelection.this,
            "Selected Pooja: \n" + tet.get(j), Toast.LENGTH_LONG)
            .show();
    if(0==j){
        oneid=tet.get(j);
    }else if(1==j){
        secid=tet.get(j);
    }else if(2==j){
        thirdid=tet.get(j);
    }else if(3==j){
        fourthid=tet.get(j);
    }else if(4==j){
        fifthid=tet.get(j);
    } 
}

Log.e("All strings ", ""+ oneid+" , "+secid+" , "+thirdid+" , "+fourthid+" , "+fifthid);

答案 1 :(得分:1)

给出了IndexOutOfBoundsException,因为您试图使用tet.get(index)检索项目而不知道tet.size()是否与索引一样大。

这意味着例如在tet.get(4);时尝试tet.size()等于3。 这可以解决您的问题:

String ids = "";
String secondId;
for(int j=0; j<tet.size(); j++) {
                    Toast.makeText(PoojaSelection.this,
                            "Selected Pooja: \n" + tet.get(j), Toast.LENGTH_LONG)
                            .show();
                    id=id+tet.get(j);

                     //only log the id string after looping all tet
                    if(j==tet.size()-1){
                       Log.d("id","tetaray: " + id +" ");
                    }
                    // edit: save second id
                    if(j==2){
                       Log.d("Second","Second id " + j );
                       secondId=""+j;
                    }
                }