从文本文件中读取列表并将列表添加到无线电组 - Android

问题描述

美好的一天

我正在构建一个 Android 应用程序来阅读食谱。我想将食谱存储在文本文件中并能够检索它们。我将有一个文件 recipes.txt 来列出所有可用的食谱。我想读取 recipes.txt 并将列表添加到数组中(以便再次轻松访问食谱),然后依次添加一个单选组,以便用户可以选择食谱,但我也希望能够轻松添加一个带有另一个配方的文本文件(因此文本文件必须存储在 Android 文件管理器可以访问的位置)

这是我到目前为止的代码

public int getnorecipes(){
    InputStream inputStream = getResources().openRawResource(R.raw.recipes);
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    //StringBuilder sb = new StringBuilder();
    int Nolines = 0;
    while (true){
        try {
            if (bufferedReader.readLine() == null) break;
        } catch (IOException e) {
            e.printstacktrace();
        }
        Nolines++; }
    return Nolines;
}
//Read recipes.txt
public ArrayList<String> getRecipeList() {
    int norecipes = getnorecipes();
    ArrayList<String> Recipe_List = new ArrayList<String>();
    InputStream inputStream = getResources().openRawResource(R.raw.recipes);
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    for(int i = 0; i < norecipes; i++){
        try {
            Recipe_List.add(bufferedReader.readLine());
        } catch (IOException e) {
            e.printstacktrace();
        }
    }
    if (inputStream != null){
        try {
            inputStream.close();
        } catch (IOException e) {
            e.printstacktrace();
        }
    }
    return Recipe_List;
}

RadioGroup radgrpRecipes;
ArrayList<String> Recipe_List = new ArrayList<String>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_recipe__select);
    radgrpRecipes = findViewById(R.id.radgrpRecipes);
    try {
        addRadioButtons();
    } catch (IOException e) {
        e.printstacktrace();
    }
}

public void addRadioButtons() throws IOException {
    Recipe_List = getRecipeList();
    radgrpRecipes.setorientation(LinearLayout.HORIZONTAL);
    //Add Recipes
    for (int i =1; i<=Recipe_List.size(); i++){
        RadioButton rdbtn = new RadioButton(this);
        rdbtn.setId(View.generateViewId());
        rdbtn.setText(Recipe_List.get(i-1));
        rdbtn.setonClickListener((View.OnClickListener) this);
        radgrpRecipes.addView(rdbtn);
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)