2016-09-21 39 views
0

我triyng從SQL數據庫填充微調: 迄今在tab []我得到所有我需要的+ null值在一些元素。 所以我試圖重寫數組到無空元素的新數組。 但是到目前爲止我已經用tab []的第一個值填充微調器。 我的意思是tab2 []具有正確的大小,但所有元素都是選項卡[0]的副本。 有什麼不對?爲什麼tab2 []中的值是相同的,當tab []是不同的

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); 

}

回答

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,它將使用製表符[0]填充製表符2。

的解決方案是讓對標籤單獨計數器,手動遞增每次分配值的一個時間:

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

3天我試圖找到問題。它正在工作thx。 –

相關問題