首页 > 解决方案 > 从 String 中获取数据并填充 RecyclerView

问题描述

我有一个格式如下的字符串:

Recipe{id=someID, title=someTitle, image='LINK', usedIngredientCount=SomeNumber, missedIngredientCount=SomeNumber2, likes=SomeNumber3}Recipe{id=someID, title=someTitle, image='LINK', usedIngredientCount=SomeNumber, missedIngredientCount=SomeNumber2, likes=SomeNumber3}

请注意,在上面的示例中,字符串包含 2 个食谱,但它实际上可以包含任意数量的食谱。我想把我拥有的任何数量的食谱放在 RecyclerView 中,我想知道最简单的方法是什么。我在想的是每次找到单词时将主字符串拆分为子字符串,Recipe然后从每个子字符串中提取someID LINK SomeNumber1 SomeNumber2 SomeNumber3,最后使用这些值填充 RecyclerView。

你能帮我把我的想法转换成代码还是想出更简单的方法来做这件事?

太感谢了

标签: javaandroidandroid-recyclerview

解决方案


class MainActivity extends AppCompatActivity 
{
    public RecyclerView recyclerView;
    private RecyclerView.LayoutManager layoutManager;
    public RecyclerAdapter adapterD;
    ArrayList<String> id;
    ArrayList<String> title;
    ArrayList<String> image;
    ArrayList<String> usedIngredientCount;
    ArrayList<String> missedIngredientCount;
    ArrayList<String> likes;

    void onCreate()
    {
    id= new ArrayList<>();
    title = new ArrayList<>();
    image = new ArrayList<>();
    likes = new ArrayList<>(); 
    usedIngredientCount= new ArrayList<>();
    missedIngredientCount = new usedIngredientCountArrayList<>();

    // your recipe string here
    String recipe = "id title image usedIngredientCount missedIngredientCount likes" ;

    // break the string 
    dataSplit(recipe)

    // call the recyclerview adapter
            recyclerView=(RecyclerView)findViewById(R.id.recycler_view);
            layoutManager=new LinearLayoutManager(this);
            recyclerView.setLayoutManager(layoutManager);
            recyclerView.setHasFixedSize(true);

            adapterD = new RecyclerAdapter(MainActivity.this, id, title, image, 
                              usedIngredientCount, missedIngredientCount, likes);


            recyclerView.setAdapter(adapterD);

    }

     void dataSplit(String recipe)
    {
        // Split String when there is space
        String parts[] = recipe.split(" ");

        id.add( parts[0] );
        title.add(parts[1]);
        image.add(parts[2]);
        usedIngredientCount.add(parts[3]);
        missedIngredientCount.add(parts[4]);
        likes.add(parts[5]);
    }

   }
}

推荐阅读