【问题标题】:Add data into RecyclerView from MySQL database将数据从 MySQL 数据库添加到 RecyclerView
【发布时间】:2018-04-16 10:50:24
【问题描述】:

我正在尝试从 MySQL 数据库中填充 RecylerView。我能够使用 volley 库(使用 Toast 测试)正确地从数据库中获取数据,但它没有显示在 RecyclerView 中。我的代码到现在为止。

fragment_notification.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="in.techbash.androidhiverecyclerview.NotificationFragment">

<!-- TODO: Update blank fragment layout -->
<RelativeLayout
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical" />

</RelativeLayout>

</FrameLayout>

我的 NotificationFragment 类

NotificationFragment.java

public class NotificationFragment extends Fragment {

private List<Notification> notificationList = new ArrayList<>();
private RecyclerView recyclerView;
NotificationsAdapter notificationsAdapter;
private View rootView;
private RecyclerView.LayoutManager mLayoutManager;


public NotificationFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    rootView = inflater.inflate(R.layout.fragment_notification, container, false);

    recyclerView = rootView.findViewById(R.id.recycler_view);

    getNotifications();

    return rootView;
}


private void getNotifications() {

    final String get_notifications = "http://192.168.1.102/notification/get_notifications.php";

    final String user_id = "327875";


    Map<String, String> parameters = new HashMap<String, String>();
    parameters.put("user_id", user_id);

    JSONObject jsonObj = new JSONObject(parameters);


    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
            get_notifications, jsonObj, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {

                JSONArray jsonArray = response.getJSONArray("result");

                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);

                    //adding the product to product list
                    notificationList.add(new Notification(
                            jsonObject.getString("msg_title"),
                            jsonObject.getString("message"),
                            jsonObject.getString("sender_name")
                    ));
                }
                //creating adapter object and setting it to recyclerview
                NotificationsAdapter adapter = new NotificationsAdapter(getActivity(), notificationList);
                recyclerView.setAdapter(adapter);


            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    }) {
        @Override
        public String getBodyContentType() {
            return "application/json; charset=utf-8";
        }
    };

    MySingleton.getInstance(getActivity()).addToRequestQueue(jsonObjectRequest);

}

}

我的 notification_list_row.xml 文件

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/selectableItemBackground"
android:clickable="true"
android:focusable="true"
android:orientation="vertical"
android:paddingBottom="@dimen/row_padding_vertical"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/row_padding_vertical">

<TextView
    android:id="@+id/title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:textColor="@color/title"
    android:textSize="16dp"
    android:textStyle="bold" />

<TextView
    android:id="@+id/message"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/title" />

<TextView
    android:id="@+id/sender"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:textColor="@color/year" />

</RelativeLayout>

NotificationsAdapter.java

public class NotificationsAdapter extends 
RecyclerView.Adapter<NotificationsAdapter.MyViewHolder> {

private List<Notification> notificationsList;
private Context mCtx;

public NotificationsAdapter(Context mCtx, List<Notification> notificationsList){
    this.mCtx = mCtx;
    this.notificationsList = notificationsList;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    //inflating and returning our view holder
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.notification_list_row, parent, false);
    return new MyViewHolder(view);
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {

    Notification notification = notificationsList.get(position);
    holder.title.setText(notification.getTitle());
    holder.message.setText(notification.getMessage());
    holder.sender.setText(notification.getSender());

}

@Override
public int getItemCount() {
    return notificationsList.size();
}

public class MyViewHolder extends RecyclerView.ViewHolder {

    public TextView title, message, sender;

    public MyViewHolder(View itemView) {
        super(itemView);

        title = (TextView) itemView.findViewById(R.id.title);
        message = (TextView) itemView.findViewById(R.id.message);
        sender = (TextView) itemView.findViewById(R.id.sender);
    }
}
}

我的通知获取器/设置器

public class Notification {

String sender, title, message;

public Notification(String title, String message, String sender){
    this.title = title;
    this.message = message;
    this.sender = sender;
}

public String getSender() {
    return sender;
}

public void setSender(String sender) {
    this.sender = sender;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getMessage() {
    return message;
}

public void setMessage(String message) {
    this.message = message;
}
}

我是安卓新手。请帮我解决这个问题。

【问题讨论】:

  • 面临什么问题?
  • @VishalG.Gohel 数据未显示在 RecyclerView 中。但用 Toast 测试,它显示在里面。
  • 缺少布局管理器。
  • 向我们展示 logcat 。

标签: android mysql android-volley


【解决方案1】:

您尚未为回收站视图设置布局管理器。在设置适配器之前在 getNotifications() 中进行此更改:

LinearLayoutManager linear = new LinearLayoutManager(getActivity());
linear.setOrientation(LinearLayoutManager.VERTICAL);// If you want a vertical recycler view
recyclerView.setLayoutManager(linear);
NotificationsAdapter adapter = new NotificationsAdapter(getActivity(), notificationList);
recyclerView.setAdapter(adapter);

希望这能解决您的问题!

【讨论】:

    【解决方案2】:

    进行一些更改设置回收器视图滚动布局,如下面使用的代码..

            recyclerview.setLayoutManager(new LinearLayoutManager(this));
    

    【讨论】:

      【解决方案3】:

      首先在onCreate()方法中加入这个linearlayoutmanager。

      LinearLayoutManager linearLayout = new LinearLayoutManager(getActivity());
      linearLayout .setOrientation(LinearLayoutManager.VERTICAL);
      recyclerView.setLayoutManager(linearLayout );    
      

      然后在for循环中添加notifyDataSetChanged()。

      for (int i = 0; i < jsonArray.length(); i++) {
                      JSONObject jsonObject = jsonArray.getJSONObject(i);
      
                      //adding the product to product list
                      notificationList.add(new Notification(
                              jsonObject.getString("msg_title"),
                              jsonObject.getString("message"),
                              jsonObject.getString("sender_name")
                      ));
      NotificationsAdapter adapter = new NotificationsAdapter(getActivity(),notificationList);
      recyclerView.setAdapter(adapter);
      adapter.notifyDataSetChanged();
                  }
                  //creating adapter object and setting it to recyclerview
      

      【讨论】:

      • 谢谢。问题解决了。但是是否有必要 adapter.notifyDataSetChanged(); 即使没有它,数据也会显示出来。
      • adapter.notifyDataSetChanged() 仅应在您更改传递给 recycler view 的数据时使用。第一次设置适配器时不需要。将其用于数据的后续更改
      • @Rahul 是的,新数据是必须的。
      猜你喜欢
      • 2017-01-15
      • 2017-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-28
      • 1970-01-01
      • 2017-07-14
      相关资源
      最近更新 更多