简体   繁体   English

用房间数据库填充微调器

[英]Fill Spinner with Room Database

I am making my first app.我正在制作我的第一个应用程序。 (with lots of google and tutorials). (有很多谷歌和教程)。

I made a Room Database with the following table.我用下表制作了一个房间数据库。

在此处输入图像描述

Now I want to fill a Spinner with the Strings of the column "team_name".现在我想用“team_name”列的字符串填充 Spinner。

On Spinner Selection the "team_url" should be put in a variable.在微调器选择中,“team_url”应该放在一个变量中。

Cant find out how.无法找出如何。

Thanks for helping.感谢您的帮助。

Greetings!问候!

Update:更新:

    Spinner league = findViewById(R.id.league);
    tableDAO = TeamDatabase.getInstance(this).getTableDAO();

    List<Team> allTable = tableDAO.getTable();

    ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, new ArrayList<String>());
    spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    league.setAdapter(spinnerAdapter);

    spinnerAdapter.addAll(allTable);
    spinnerAdapter.notifyDataSetChanged();

I assume you are using Java and have some code similar to this to initialize the Spinner .我假设您使用的是 Java 并且有一些类似于此的代码来初始化Spinner

Spinner spinner = (Spinner)findViewById(R.id.mySpinner);
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, new ArrayList<>());  
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerAdapter);

what you need to do is fetch the data from DB using Room and add them to the adapter您需要做的是使用 Room 从数据库中获取数据并将它们添加到适配器

spinnerAdapter.addAll(yourList);
spinnerAdapter.notifyDataSetChanged();

and once the user clicks any items, you can use the callback function to get the team name and use Room to fetch the corresponding team_url.一旦用户点击任何项目,您可以使用回调 function 获取团队名称并使用 Room 获取相应的团队 URL。

The Dao of your Room may look like this你房间的道可能看起来像这样

@Dao
public interface TeamDao {
    @Query("SELECT * FROM team")
    List<Team> getAll();

    @Query("SELECT team_name FROM team")
    List<String> getAllTeamName();

    @Query("SELECT team_url FROM team WHERE team_name = :name")
    public abstract List<String> findURLByName(String name);

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM