java - 为什么 Recyclerview 列表在所有位置返回相同的项目?

标签 java android collections android-recyclerview

在我的 Android 应用程序中,我使用回收器 View 来显示项目。

(注意:这不是重复的问题,因为我尝试了 stackoverflow 中的许多答案,但没有解决方案。)

我的问题
显示重复项目的回收器 View 。单个项目重复多次,即使它在源数据库中仅出现一次。

我检查了原因,并注意到 Adapter 类中的 List 对象在所有迭代中返回相同的值。但是将 List 对象发送到具有唯一值的适配器类的 Fragment。

但只有接收到List对象后的适配器类包含重复项

我尝试过的解决方案

  • 我检查了 Stackoverflow 并在适配器类中添加了 getItemId(intposition) 和 getItemViewType(intposition) 但没有解决方案

  • 我检查了数据库和 ListView 发送类都没有重复的项目。

我的代码:

InboxHostFragment.java = 该类将List对象发送到回收器 View 的适配器类:

public class HostInboxFragment extends Fragment {

 View hostinbox;
 Toolbar toolbar;
 ImageView archive, alert, search;
 TextView blank;
 Bundle args = new Bundle();

 private static final String TAG = "Listinbox_host";

 private InboxHostAdapter adapter;
 String Liveurl = "";
 RelativeLayout layout, host_inbox;
 String country_symbol;
 String userid;
 String login_status, login_status1;

 ImageButton back;

 String roomid;
 RecyclerView listView;
 String name = "ramesh";

 private int start = 1;

 private List < ListFeed > movieList = new ArrayList < > ();
 String currency1;
 // RecyclerView recyclerView;
 public HostInboxFragment() {

 }

 public void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

 }

 @RequiresApi(api = Build.VERSION_CODES.M)
 public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
  Bundle savedInstanceState) {

  hostinbox = inflater.inflate(R.layout.fragment_host_inbox, container, false);

  FontChangeCrawler fontChanger = new FontChangeCrawler(getContext().getAssets(), getString(R.string.app_font));
  fontChanger.replaceFonts((ViewGroup) hostinbox);

  SharedPreferences prefs = getActivity().getSharedPreferences(Constants.MY_PREFS_NAME, MODE_PRIVATE);
  userid = prefs.getString("userid", null);
  currency1 = prefs.getString("currenycode", null);

  toolbar = (Toolbar) hostinbox.findViewById(R.id.toolbar);
  archive = (ImageView) hostinbox.findViewById(R.id.archive);
  alert = (ImageView) hostinbox.findViewById(R.id.alert);
  search = (ImageView) hostinbox.findViewById(R.id.search);
  blank = (TextView) hostinbox.findViewById(R.id.blank);

  host_inbox = (RelativeLayout) hostinbox.findViewById(R.id.host_inbox);

  layout.setVisibility(View.INVISIBLE);
  start = 1;

  final String url = Constants.DETAIL_PAGE_URL + "payment/host_reservation_inbox?userto=" + userid + "&start=" + start + "&common_currency=" + currency1;
  //*******************************************ListView code start*****************************************************
  System.out.println("url in Inbox page===" + url);

  movieList.clear();
  JsonObjectRequest movieReq = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener < JSONObject > () {
    @SuppressWarnings("deprecation")
    @Override
    public void onResponse(JSONObject response) {
     //  progressBar.setVisibility(View.GONE);

     // Parsing json
     // for (int i = 0; i < response.length(); i++) {
     try {

      JSONArray contact = response.getJSONArray("contact");
      obj_contact = contact.optJSONObject(0);

      login_status1 = obj_contact.getString("Status");


      // progressBar.setVisibility(View.VISIBLE);
      layout.setVisibility(View.INVISIBLE);
      listView.setVisibility(View.VISIBLE);
      host_inbox.setBackgroundColor(Color.parseColor("#FFFFFF"));

      ListFeed movie = new ListFeed();
      for (int i = 0; i < contact.length(); i++) {
       JSONObject obj1 = contact.optJSONObject(i);


       movie.getuserby(obj1.getString("userby"));
       movie.resid(obj1.getString("reservation_id"));
       movie.setresidinbox(obj1.getString("reservation_id"));
       System.out.println("reservation iddgdsds" + obj1.getString("reservation_id"));
       movie.setuserbys(obj1.getString("userby"));
       movie.setuserto(obj1.getString("userto"));
       movie.setid(obj1.getString("room_id"));
       movie.getid1(obj1.getString("id"));
       movie.userto(obj1.getString("userto"));
       movie.isread(obj1.getString("isread"));
       movie.userbyname(obj1.getString("userbyname"));
       country_symbol = obj1.getString("currency_code");
       Currency c = Currency.getInstance(country_symbol);
       country_symbol = c.getSymbol();
       movie.setsymbol(country_symbol);


       movie.setTitle(obj1.getString("title"));
       movie.setThumbnailUrl(obj1.getString("profile_pic"));
       movie.setstatus(obj1.getString("status"));
       movie.setcheckin(obj1.getString("checkin"));
       movie.setcheckout(obj1.getString("checkout"));
       movie.setcreated(obj1.getString("created"));
       movie.guest(obj1.getString("guest"));
       movie.userbyname(obj1.getString("username"));
       movie.getprice(obj1.getString("price"));
       String msg = obj1.getString("message");
       msg = msg.replaceAll("<b>You have a new contact request from  ", "");
       msg = msg.replaceAll("</b><br><br", "");
       msg = msg.replaceAll("\\w*\\>", "");
       movie.message(msg);

       movieList.add(movie);
       System.out.println(movieList.get(i).message()); // returning unique values

       adapter.notifyDataSetChanged();

      }
     }

    } catch (JSONException e) {
     e.printStackTrace();
     // progressBar.setVisibility(View.GONE);
    }


    adapter.notifyDataSetChanged();
   }
  }, new Response.ErrorListener() {
   @Override
   public void onErrorResponse(VolleyError error) {

    stopAnim();
    //progressBar.setVisibility(View.GONE);
    if (error instanceof NoConnectionError) {
     Toast.makeText(getActivity(),
      "Check your Internet Connection",
      Toast.LENGTH_LONG).show();
    }
    //progressBar.setVisibility(View.GONE);

   }
  });

 // Adding request to request queue
 AppController.getInstance().addToRequestQueue(movieReq);
 movieReq.setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

 return hostinbox;
}

@Override
public void onStop() {
 Log.w(TAG, "App stopped");

 super.onStop();
}

@Override
public void onDestroy() {
 super.onDestroy();
}


public boolean isOnline(Context c) {
 ConnectivityManager cm = (ConnectivityManager) c
  .getSystemService(Context.CONNECTIVITY_SERVICE);
 NetworkInfo ni = cm.getActiveNetworkInfo();

 return ni != null && ni.isConnected();
}



@Override
public void onActivityCreated(Bundle savedInstanceState) {
 super.onActivityCreated(savedInstanceState);
}
} 

In the above code , System.out.println(movieList.get(i).message()); returning unique values without any problem.




Inboxhostadapter.java = 这是recycleview的适配器

public class InboxHostAdapter extends RecyclerView.Adapter < InboxHostAdapter.CustomViewHolder > {
 private List < ListFeed > feedItemList;
 private ListFeed listFeed = new ListFeed();
 String userid = "",
 tag,
 str_currency;
 String reservation_id,
 Liveurl,
 india2 = "0";
 ImageLoader imageLoader = AppController.getInstance().getImageLoader();
 String currency1;
 String status1;
 //private Activity activity;
 public Context activity;
 public InboxHostAdapter(Context activity, List < ListFeed > feedItemList, String tag) {
  SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity);
  Liveurl = sharedPreferences.getString("liveurl", null);
  userid = sharedPreferences.getString("userid", null);
  currency1 = sharedPreferences.getString("currenycode", null);

  this.feedItemList = feedItemList; // returning duplicate items

  this.activity = activity;
  listFeed = new ListFeed();
  this.tag = tag;
  SharedPreferences prefs1 = activity.getSharedPreferences(Constants.MY_PREFS_LANGUAGE, MODE_PRIVATE);
  str_currency = prefs1.getString("currencysymbol", null);
  if (str_currency == null) {
   str_currency = "$";
  }
 }

 @Override
 public InboxHostAdapter.CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
  View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.hostinbox, parent, false);
  FontChangeCrawler fontChanger = new FontChangeCrawler(activity.getAssets(), activity.getString(R.string.app_font_light));
  fontChanger.replaceFonts((ViewGroup) view);
  return new CustomViewHolder(view);

 }

 @Override
 public void onBindViewHolder(InboxHostAdapter.CustomViewHolder holder, int position) {

  // This block returning duplicate items

  listFeed = feedItemList.get(position); // This list feedItemList returning duplicate items

  reservation_id = listFeed.getid();
  System.out.println("reservation id after getting in inbox adapter" + reservation_id);
  System.out.println("check out after getting" + listFeed.getcheckout());
  System.out.println("message after getting in inbox adapter" + listFeed.getTitle());
  System.out.println("symbol after getting" + listFeed.getsymbol());
  System.out.println("username after getting" + listFeed.getaddress());
  System.out.println("price after getting" + listFeed.getprice());
  System.out.println("status after getting" + listFeed.getstatus());
  System.out.println("check in after getting" + listFeed.getcheckin());
  System.out.println("check out after getting" + listFeed.getcheckout());
  System.out.println("userby  after getting====" + listFeed.getuserby());
  System.out.println("message  after getting====" + listFeed.message());
  String msg;
  msg = listFeed.message();

  holder.name.setText(listFeed.userbyname());
  holder.time.setText(listFeed.getcreated());
  holder.date1.setText(listFeed.getcheckin());
  holder.date2.setText(listFeed.getcheckout());

  if (listFeed.guest().equals("1")) {
   holder.guest.setText(listFeed.guest() + activity.getResources().getString(R.string.guests));
  } else {
   holder.guest.setText(listFeed.guest() + activity.getResources().getString(R.string.guests));

  }

  if (tag.equals("Listinbox_service_host")) {
   holder.guest.setText("");
   holder.ttt.setVisibility(View.INVISIBLE);
  } else {
   holder.guest.setText(listFeed.guest() + activity.getResources().getString(R.string.guests));
  }

  //  holder.status.setText(listFeed.getstatus());
  holder.title.setText(listFeed.getTitle());
  status1 = listFeed.getstatus();
  if (status1.equals("Accepted")) {
   holder.status.setText(activity.getResources().getString(R.string.accepted_details));
  }
 } else if (status1.equals("Contact Host")) {
  holder.status.setText(activity.getResources().getString(R.string.Contact_Host));
  holder.guestmsg.setText(listFeed.message());

 } else {
  holder.status.setText(status1);
 }

 if (currency1 == null) {
  currency1 = "$";
 }
 if (listFeed.getprice() != null && !listFeed.getprice().equals("null")) {
  DecimalFormat money = new DecimalFormat("00.00");
  money.setRoundingMode(RoundingMode.UP);
  india2 = money.format(new Double(listFeed.getprice()));
  holder.currency.setText(listFeed.getsymbol() + " " + india2);
  holder.currency.addTextChangedListener(new NumberTextWatcher(holder.currency));

 }
 //view.imgViewFlag.setImageResource(listFlag.get(position));
 System.out.println("listview price" + listFeed.getprice());
 System.out.println("listview useds" + listFeed.getresidinbox());
 System.out.println("listview dffdd" + listFeed.getuserbys());
 System.out.println("listview dfffdgjf" + listFeed.getuserto());

 //holder.bucket.setTag(position);
 System.out.println("Activity name" + tag);
 holder.inbox.setTag(position);
 holder.inbox.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {

   int position = (int) v.getTag();
   Intent search = new Intent(activity, Inbox_detailshost.class);
   search.putExtra("userid", userid);
   search.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   activity.startActivity(search);
   System.out.println("listview useds" + listFeed.getresidinbox());
   System.out.println("listview dffdd" + listFeed.getuserbys());
   System.out.println("listview dfffdgjf" + listFeed.getuserto());

  }
 });

}


@Override
public long getItemId(int position) {
 // TODO Auto-generated method stub
 return position;
}

@Override
public int getItemCount() {
 System.out.println("list item size" + feedItemList.size());
 return (null != feedItemList ? feedItemList.size() : 0);
}


@Override
public int getItemViewType(int position) {
 return position;
}

class CustomViewHolder extends RecyclerView.ViewHolder {
 ImageView thumbNail;
 TextView name, time, date1, date2, currency, guest, status, title, ttt, guestmsg;
 RelativeLayout inbox;

 CustomViewHolder(View view) {
  super(view);
  if (imageLoader == null)
   imageLoader = AppController.getInstance().getImageLoader();
  this.thumbNail = (ImageView) view.findViewById(R.id.list_image);
  this.name = (TextView) view.findViewById(R.id.title2);
  this.time = (TextView) view.findViewById(R.id.TextView4);
  this.date1 = (TextView) view.findViewById(R.id.TextView2);
  this.date2 = (TextView) view.findViewById(R.id.TextView22);
  this.currency = (TextView) view.findViewById(R.id.TextView23);
  this.guest = (TextView) view.findViewById(R.id.TextView25);
  this.ttt = (TextView) view.findViewById(R.id.TextView24);
  this.status = (TextView) view.findViewById(R.id.TextView26);
  this.title = (TextView) view.findViewById(R.id.TextView28);
  this.inbox = (RelativeLayout) view.findViewById(R.id.inbox);
  this.guestmsg = (TextView) view.findViewById(R.id.guestmessage);
 }
}
public class NumberTextWatcher implements TextWatcher {

 private DecimalFormat df;
 private DecimalFormat dfnd;
 private boolean hasFractionalPart;

 private TextView et;

 public NumberTextWatcher(TextView et) {
  df = new DecimalFormat("#,###");
  df.setDecimalSeparatorAlwaysShown(true);
  dfnd = new DecimalFormat("#,###.##");
  this.et = et;
  hasFractionalPart = false;
 }

 @SuppressWarnings("unused")
 private static final String TAG = "NumberTextWatcher";

 @Override
 public void afterTextChanged(Editable s) {
  et.removeTextChangedListener(this);

  try {
   int inilen, endlen;
   inilen = et.getText().length();

   String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "");
   Number n = df.parse(v);
   int cp = et.getSelectionStart();
   if (hasFractionalPart) {
    et.setText(df.format(n));
   } else {
    et.setText(dfnd.format(n));
   }
   endlen = et.getText().length();
   int sel = (cp + (endlen - inilen));
   if (sel > 0 && sel <= et.getText().length()) {
    et.setSelected(true);
   }
  } catch (NumberFormatException nfe) {
   // do nothing?
  } catch (ParseException e) {
   // do nothing?
  }

  et.addTextChangedListener(this);
 }

 @Override
 public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

 @Override
 public void onTextChanged(CharSequence s, int start, int before, int count) {
  if (s.toString().contains(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator()))) {
   hasFractionalPart = true;
  } else {
   hasFractionalPart = false;
  }
 }

}
}

In the above code , feedItemList returning duplicate values eventhogh the movieList list from source clas Inboxfragment.java contains unique values.



请帮我解决这个问题。我在 Stackoverflow 中尝试了很多答案,但找不到解决方案。我无法找出问题所在。

最佳答案

使用此代码

  for (int i = 0; i < contact.length(); i++) {
   JSONObject obj1 = contact.optJSONObject(i);
   ListFeed movie = new ListFeed();

   movie.getuserby(obj1.getString("userby"));
   movie.resid(obj1.getString("reservation_id"));
   movie.setresidinbox(obj1.getString("reservation_id"));
   System.out.println("reservation iddgdsds" + obj1.getString("reservation_id"));
   movie.setuserbys(obj1.getString("userby"));
   movie.setuserto(obj1.getString("userto"));
   movie.setid(obj1.getString("room_id"));
   movie.getid1(obj1.getString("id"));
   movie.userto(obj1.getString("userto"));
   movie.isread(obj1.getString("isread"));
   movie.userbyname(obj1.getString("userbyname"));
   country_symbol = obj1.getString("currency_code");
   Currency c = Currency.getInstance(country_symbol);
   country_symbol = c.getSymbol();
   movie.setsymbol(country_symbol);


   movie.setTitle(obj1.getString("title"));
   movie.setThumbnailUrl(obj1.getString("profile_pic"));
   movie.setstatus(obj1.getString("status"));
   movie.setcheckin(obj1.getString("checkin"));
   movie.setcheckout(obj1.getString("checkout"));
   movie.setcreated(obj1.getString("created"));
   movie.guest(obj1.getString("guest"));
   movie.userbyname(obj1.getString("username"));
   movie.getprice(obj1.getString("price"));
   String msg = obj1.getString("message");
   msg = msg.replaceAll("<b>You have a new contact request from  ", "");
   msg = msg.replaceAll("</b><br><br", "");
   msg = msg.replaceAll("\\w*\\>", "");
   movie.message(msg);

   movieList.add(movie);
   System.out.println(movieList.get(i).message()); // returning unique value

  }

声明ListFeed movie = new ListFeed();进入for Loop 并删除 adapter.notifyDataSetChanged();来自for Loop .

我认为这对你有帮助。

关于java - 为什么 Recyclerview 列表在所有位置返回相同的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47466445/

相关文章:

java - 如何根据 ArrayListMultiMap 值的大小将键添加到列表中?

java - 自定义三项ListView适配器

java - MIUI推送通知没有声音

java - 为什么 List 不简单地定义为抽象类而不是接口(interface)?

java hashmap无法转换对象

java - 使用多维数组进行计数

java - 通过 Activity 快捷方式启动时,如何在字段中设置数据库中的特定数据?

java - 对不同的列名重复使用 resultMap

android - 添加适用于 Android 的 Google 云消息传递 (FCM) - 注册过程

java - 按升序对字母数字数组列表进行排序