使用arraylist将sqlite中的现有数据填充到微调器中

时间:2018-11-24 08:38:01

标签: android sqlite arraylist android-sqlite

嗨,我很难将现有数据从sqlite绑定到微调器。我必须申请arraylist吗?如果是这样,我该怎么做?请帮助我,我还是新手,这是我的项目。

这是从数据库中获取数据的方式:

public Cursor alldata()
{

  ArrayList<String> values = new ArrayList<String>();
  SQLiteDatabase db = this.getReadableDatabase();
  Cursor cursor = db.rawQuery("Select * from shop", null);
  return cursor;
}

这是应该用来接收数据并在微调器上显示它的编码,但是我不知道要这样做:

SpListofShop = (Spinner) findViewById(R.id.SpListofShop);

    Cursor cursor = db.alldata();
    if(cursor.getCount()==0)
    {
        Toast.makeText(getApplicationContext(), "NO DATA", Toast.LENGTH_SHORT).show();
    }
    else
    {
        while(cursor.moveToNext())
        {

        }

    }

我真的希望你们中的任何一个都能帮助我,我太绝望了

编码以调用公共arraylist函数

这是在databasehelper.java中调用公共数组列表的编码:

Spinner SpListofShop = findViewById(R.id.SpListofShop);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),  android.R.layout.simple_spinner_dropdown_item, db.alldata());
    adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item);

    SpListofShop.setAdapter(adapter);

1 个答案:

答案 0 :(得分:0)

1.change alldata如下:

public ArrayList<String> alldata()
{

    ArrayList<String> values = new ArrayList<String>();
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery("Select * from shop", null);
    for (int i=0;i<cursor.getCount();i++){
        values.add(cursor.getString(cursor.getColumnIndex("row_name")));
        //edit, change row_name with your row
    }
    cursor.close();
    return values;
}

2。像这样更改微调器代码:

Spinner SpListofShop = findViewById(R.id.SpListofShop);
ArrayAdapter<String> adapter = new ArrayAdapter<>(getApplicationContext(),  android.R.layout.simple_spinner_dropdown_item, alldata());
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item);

SpListofShop.setAdapter(adapter);