从String提取数据并填充RecyclerView

时间:2018-09-20 14:44:35

标签: java android android-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。

您能帮我将我的想法转换为代码还是提出更简单的方法吗?

非常感谢您

1 个答案:

答案 0 :(得分:1)

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]);
    }

   }
}