简体   繁体   中英

update RecyclerView after fetching data from server

I´ve got a problem with my RecyclerView. I want to update the Cards (inside the RecyclerView) after fetching the data from the server. First I thought there´sa problem with fetching or parsing the JSON-data, or sending the data via EventBus to the Fragment but when I display the parsed Objects in a TextView in the Fragment, everything is shown up. So the real problem is the RecyclerView / Adapter. I´ve initialized the RecyclerView with an empty ArrayList, but when and HOW do I have to update the data for the RecyclerView? I´ve also read some Posts here on Stackoverflow, but I found no suitable solution...

This is the onCreateView from UserFragment

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    // Inflate the layout for this fragment
    View mView = inflater.inflate(R.layout.fragment_users, container, false);
    mRecyclerView = (RecyclerView) mView.findViewById(R.id.rv_user);
    //set LayoutManager for View
    mLayoutManager = new LinearLayoutManager(getActivity());
    mRecyclerView.setLayoutManager(mLayoutManager);

    //set Adapter for View
    mAdapter = new UserAdapter(userList);
    mRecyclerView.setAdapter(mAdapter);
    Log.d(TAG, "onCreateView");
    return mView;
}

and this is my UserAdapter

public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ViewHolder> {

public static final String TAG = "UserAdapter";

private ArrayList<User> mUser;

public UserAdapter(ArrayList<User> user) {
    mUser = user;
}

public static class ViewHolder extends RecyclerView.ViewHolder {
    public CardView cv;
    public TextView user_name;
    public TextView user_lastName;

    public TextView user_city;
    public ViewHolder(View itemView) {
        super(itemView);
        cv = (CardView) itemView.findViewById(R.id.rv_user);
        user_name = (TextView) itemView.findViewById(R.id.tv_user_name);
        user_lastName = (TextView) itemView.findViewById(R.id.tv_user_lastname);
        user_city = (TextView) itemView.findViewById(R.id.tv_user_city);
        Log.d(TAG, "Viewholder");
    }

}

//initialize Viewholder
@Override
public UserAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
    View mView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_layout_person, viewGroup, false);
    Log.d(TAG, "onCreateViewHolder");
    return new ViewHolder(mView);
}

//Bind data to view
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    holder.user_name.setText(mUser.get(position).getUser().getFirstname());
    holder.user_lastName.setText(mUser.get(position).getUser().getLastname());
    holder.user_city.setText(mUser.get(position).getUser().getCity());
    Log.d(TAG, "onBindViewHolder");
}

public void setUserList(ArrayList<User> user){
    this.mUser = user;
    notifyItemRangeChanged(0, user.size());
    notifyDataSetChanged();
}

public void updateData(ArrayList<User> userList) {
    mUser.clear();
    mUser.addAll(userList);
    notifyDataSetChanged();
}

public void removeItem(int position) {
    mUser.remove(position);
    notifyItemRemoved(position);
}

@Override
public int getItemCount() {
    Log.d(TAG, "getItemCount");
    if (mUser == null) {
        return 0;
    } else {
        return mUser.size();
    }
}   }

This is the onResponse in the MainActivity:

public void onResponse(Call call, Response response) throws IOException {
            if (response.isSuccessful()) {
                String responseStr = response.body().string();
                Gson gson = new Gson();
                Type userListType = new TypeToken<ArrayList<User>>() {
                }.getType();
                final ArrayList<User> userList = gson.fromJson(responseStr, userListType);
                CustomMessageEvent event = new CustomMessageEvent();
                event.setUserList(userList);
                EventBus.getDefault().post(event);
                System.out.print(responseStr);
                response.body().close();
            }
        }

UPDATE

XML-File (CardView)

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
                                xmlns:app="http://schemas.android.com/apk/res-auto"
                                xmlns:tools="http://schemas.android.com/tools"
                                android:id="@+id/rv_user"
                                android:layout_width="match_parent"
                                android:layout_height="120dp"
                                android:layout_margin="3dp"
                                android:elevation="11dp"
                                android:foregroundGravity="center_horizontal"
                                android:scrollbars="vertical"
                                android:theme="@style/AppThemeFSF"
                                app:cardBackgroundColor="@color/cardview_light_background"
                                app:cardCornerRadius="4dp"
                                app:cardElevation="4dp"
>

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <android.support.v7.widget.AppCompatImageView
        android:id="@+id/iv_profile_picture"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_gravity="center_vertical"
        android:layout_marginBottom="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_weight="1"
        android:src="@mipmap/ic_launcher"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="30dp"
            android:layout_marginBottom="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:layout_weight="1"
            android:gravity="left|center"
            android:text="Name"/>

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="30dp"
            android:layout_marginBottom="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginStart="8dp"
            android:layout_weight="1"
            android:gravity="left|center"
            android:text="Nachname"/>

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="30dp"
            android:layout_marginBottom="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginStart="8dp"
            android:layout_weight="1"
            android:gravity="left|center"
            android:text="Stadt"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android:id="@+id/tv_user_name"
            android:layout_width="wrap_content"
            android:layout_height="30dp"
            android:layout_marginBottom="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:layout_weight="1"
            android:gravity="left|center"
            android:text="Name"
            android:textAppearance="?android:textAppearanceLarge"
            android:textSize="14sp"/>

        <TextView
            android:id="@+id/tv_user_lastname"
            android:layout_width="wrap_content"
            android:layout_height="30dp"
            android:layout_marginBottom="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginStart="8dp"
            android:layout_weight="1"
            android:gravity="left|center"
            android:text="Nachname"
            android:textAppearance="?android:textAppearanceLarge"
            android:textSize="14sp"/>

        <TextView
            android:id="@+id/tv_user_city"
            android:layout_width="wrap_content"
            android:layout_height="30dp"
            android:layout_marginBottom="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginStart="8dp"
            android:layout_weight="1"
            android:gravity="left|center"
            android:text="Stadt"
            android:textAppearance="?android:textAppearanceLarge"
            android:textSize="14sp"
            />

    </LinearLayout>

</LinearLayout>

来自 AS 的片段

来自 Logcat 的片段

Thanks in advance guys, have a great day!

The problem is that you are not subscribing to receive you event back. So, when you call:

EventBus.getDefault().post(event);

No one is getting the event! And you are not populating you list. So your adapter has nothing to show.

Subscribe for the event like this:

@Subscribe
public void receiveEvent(CustomMessageEvent event){
    mAdapter.updateData(event.getUserList())
}

This method should be in your fragments. If you put this inside your adapter you are going to violate the single responsibility principle. The only responsibility that your adapter should have is to link the list to the RecyclerView.

Happy coding!

Ok guys... I´ve got the solution! And this drives me a bit crazy... The problem was not the Adapter or the ViewHolder or anything inside the Fragment. The "real" problem was the text-size from the TextView inside the CardView-Elements. I deleted this properties and now every single dataset is available! Thank you so much for your help and your tips! You´re great!

HAPPY coding ;)

Try to change this

public void setUserList(ArrayList<User> user){
    this.mUser = user;
    notifyItemRangeChanged(0, user.size());
    notifyDataSetChanged();
}

to this

 public void setUserList(ArrayList<User> user){
        mUser.add(user);
        notifyItemInserted(user.size());
        notifyDataSetChanged();
    }

Then in your fragment, call

mAdapter.setUserList(userList);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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