【问题标题】:why values in tab2[] are the same, when tab[] are difrent为什么选项卡 2[] 中的值相同,而选项卡 [] 不同
【发布时间】:2017-01-29 21:30:59
【问题描述】:

我正在尝试从 sql db 填充微调器: 到目前为止,在 tab[] 中,我得到了我需要的所有内容 + 某些元素的 null 值。 所以我试图将数组重写为没有空元素的新数组。 但到目前为止,我设法使用来自 tab[] 的第一个值填充微调器。 我的意思是 tab2[] 的大小正确,但所有元素都是 tab[0] 的副本。 怎么了?

public void zrob(){
Spinner spinner= (Spinner) findViewById(R.id.spinner2);
Spinner spinner1= (Spinner) findViewById(R.id.spinner);
String string = spinner.getSelectedItem().toString();
String string1= new String();
String string2= new String();
DataBaseHelper dataBaseHelper= new DataBaseHelper(this);
Cursor cursor= dataBaseHelper.getReadableDatabase().rawQuery("SELECT * FROM BusPlan",null);
int count= cursor.getCount();
String tab []= new String[count];

cursor.moveToFirst();
for (int i =0;count>i;i++) {
    string1 = cursor.getString(cursor.getColumnIndex("Linie_Nummer"));
    if (string.equals(string1)) {
        tab[i] = cursor.getString(cursor.getColumnIndex("Bushaltestelle"));
        cursor.moveToNext();
    } else {
        cursor.moveToNext();
    }
}
cursor.close();
dataBaseHelper.close();
int c=0;
for (int j=0; count>j;j++){
    if (tab[j]!=null){c=c+1;}
}
String tab2 []= new String[c];
for (int k=0; count>k;k++){
    if (tab[k]!=null){
        for (int l=0;l<c;l++)
            if (tab2[l]==null){
                tab2[l]=tab[k];
            }
    }
}
TextView tv =(TextView) findViewById(R.id.textView);
tv.setText(tab2[3]);

List<String> stringList = new ArrayList<String>(Arrays.asList(tab2));
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(Bodo.this, android.R.layout.simple_spinner_item, tab2); //selected item will look like a spinner set from XML
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(spinnerArrayAdapter);

}

【问题讨论】:

    标签: android sql arrays arraylist spinner


    【解决方案1】:

    你的问题在这里:

    for (int k=0; count>k;k++){
        if (tab[k]!=null){
            for (int l=0;l<c;l++)
                if (tab2[l]==null){
                    tab2[l]=tab[k];
                }
            }
        }
    }
    

    内部循环不是必需的。在外循环的第一次运行 (k==0) 中,内循环将从 l=0 开始,并且由于所有值都是 null,它将用 tab[0] 填充 tab2。

    解决方案是为选项卡创建一个单独的计数器,每次分配其中一个值时手动递增:

    int counter = 0;
    for (int k=0; count>k;k++){
        if (tab[k]!=null) {
            tab2[counter] = tab[k];
            counter++;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-03
      • 1970-01-01
      • 2013-12-20
      • 1970-01-01
      • 2011-09-13
      • 2011-06-17
      • 2014-09-18
      • 1970-01-01
      相关资源
      最近更新 更多