首页 > 解决方案 > “如何将字符串生成器转换为数组?”

问题描述

我在代码中犯了什么样的错误?

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.update_activity);

etEname = findViewById(R.id.etEname);
etSalary = findViewById(R.id.etSalary);
rbMale = findViewById(R.id.rbMale);
rbFemale = findViewById(R.id.rbFemale);
cbWork = findViewById(R.id.cbWork);
spEno = findViewById(R.id.spEno);
//creation
helper = new DBHelper(this);
Cursor cursor = helper.readAll();
String arr [] = new String[0];

StringBuilder builder=new StringBuilder();


    while(cursor.moveToNext()){
        builder.append(cursor.getString(0)+"   "+cursor.getString(1));
    }
    try {
    for (int i = 0 ; i < cursor.getCount(); i++)
        arr[i] = builder.toString();
ArrayAdapter<String> adapter = new ArrayAdapter<String>
        (this, R.layout.custom, R.id.textView2,arr );
// Add adapter to spinner
spEno.setAdapter(adapter);
}

简单的说就是我想把具体的数据从数据库名和id加到spinner中,有什么办法呢?

标签: android

解决方案


你不需要StringBuilder

int i = 0;
while(cursor.moveToNext()){
    arr[i++] = String.format("%s %s", cursor.getString(0), cursor.getString(1));
}

ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, R.layout.custom, R.id.textView2,arr);
spEno.setAdapter(adapter);

推荐阅读