Tomasz Okraszewski Tomasz Okraszewski - 2 months ago 8
SQL Question

why values in tab2[] are the same, when tab[] are difrent

I'm triyng to populate spinner from sql db:
So far in tab[] i'm getting all what I need + null values at some elements.
So I'm trying to rewrite array to new array without null elements.
But so far I managed populate spinner with first value from tab[].
I mean tab2[] has correct size but all elemnts are copy of tab[0].
what's wrong ?

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


}

Answer

Your problem is here:

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];
            }
        }
    }
}

The inner loop is not necessary. In the first run of the outer loop (k==0), the inner loop will begin with l=0 and as all values are null, it will fill tab2 with tab[0].

The solution is to make a separate counter for tab that is manually incremented every time you assign one of the values:

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