嗨我有String []数组,包含重复数据。 我想将这个数组重写为新的String [] array2,没有重复。
Cursor c;
c= myDbHelper.getReadableDatabase().rawQuery("SELECT * FROM BusPlan", null);
c.moveToFirst();
int columnCnt = c.getCount();
String[] stringArray = new String[columnCnt]; //deklaracja tablicy stringArray
String[] stringArray2 = new String[columnCnt];
for(int i = 0; i < columnCnt ; i++){
String variable= new String();
variable=c.getString(c.getColumnIndex("Bushaltestelle"));
stringArray2[i] = c.getString(c.getColumnIndex("Bushaltestelle"));
c.moveToNext();
for (int j=0;j< columnCnt;j++){
if(!variable.equals(stringArray2[j].toString())){
stringArray[j]= c.getString(c.getColumnIndex("Bushaltestelle"));
}
}
}
我做错了什么? 如何使它工作?
我使用Hashset解决了问题,但我对此并不满意。
Spinner spinner= (Spinner) findViewById(R.id.spinner);
Cursor c;
c= myDbHelper.getReadableDatabase().rawQuery("SELECT * FROM BusPlan", null);
c.moveToFirst();
int columnCnt = c.getCount();
String[] stringArray = new String[columnCnt]; //deklaracja tablicy stringArray
String[] stringArray2 = new String[columnCnt];
for(int i = 0; i < columnCnt ; i++){
stringArray[i] = c.getString(c.getColumnIndex("Bushaltestelle"));
c.moveToNext();}
stringArray2 = new HashSet<String>(Arrays.asList(stringArray)).toArray(new String[0]);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(Bodo.this, android.R.layout.simple_spinner_item,stringArray2); //selected item will look like a spinner set from XML
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerArrayAdapter);
TextView tv = (TextView) findViewById(R.id.textView);
tv.setText(stringArray[16]);
如果有人知道如何使用数组工作,我会很高兴收到信息
答案 0 :(得分:0)
在你的for(int j循环中,你覆盖所有不等于新数据的数据。试试这个:
Cursor c;
c= myDbHelper.getReadableDatabase().rawQuery("SELECT * FROM BusPlan", null);
c.moveToFirst();
int columnCnt = c.getCount();
String[] stringArray = new String[columnCnt]; //deklaracja tablicy stringArray
String[] stringArray2 = new String[columnCnt];
for(int i = 0; i < columnCnt ; i++){
String variable = c.getString(c.getColumnIndex("Bushaltestelle"));
stringArray[i] = variable;
c.moveToNext();
if (variable == null)
continue;
for (int j=0;j< columnCnt;j++){
if (stringArray2[j] != null && variable.equals(stringArray2[j].toString())) {
break; // duplicate so ignore
}
if (stringArray2[j] == null) {
stringArray2[j]= variable; // new empty slot, all already added data has already been passed by the loop
break;
}
}
}