0

I am creating a chatting android application.In this app there is a function JSON_DATA_WEB_CALL which extracts data from a url using volley library and then displays it in this recyclerview.In the onCreate() method there is a thread which repeatedly runs JSON_DATA_WEB_CALL() method.This is how reloading of messages takes place after every 1 second but when i scroll the recyclerview it comes back to the same position(top) so scrolling is not working.

messages.java

public class messages extends Activity {
    TextView mTitle;
    List<ConversationsList> conversationsList;
    RecyclerView recyclerView;
    RecyclerView.LayoutManager recyclerViewlayoutManager;
    RecyclerView.Adapter recyclerViewadapter;
    ProgressBar progressBar;

    String HTTP_JSON_URL = "http://xxx.xx/conversate.php";
    String GET_JSON_FROM_SERVER_NAME = "my_name";
    String GET_JSON_FROM_SERVER_NAME2 = "imageurl";
    String GET_JSON_FROM_SERVER_NAME3 = "friend_uid";
    String GET_JSON_FROM_SERVER_NAME4 = "friend_name";
    String GET_JSON_FROM_SERVER_NAME5 = "time";
    String GET_JSON_FROM_SERVER_NAME6 = "my_uid";
    String GET_JSON_FROM_SERVER_NAME7 = "message";
    JsonArrayRequest jsonArrayRequest ;
    ScrollView scrollView;
    Context context;
    Intent intent;
    RequestQueue requestQueue ;
    int count = 1;
    ArrayList<String> FriendNames;
    ImageButton sendbutton;
    EditText edit;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message);
        mTitle = findViewById(R.id.profiletitle);
        edit = findViewById(R.id.message);
        Typeface face = Typeface.createFromAsset(getAssets(),
                "fonts/epimodem.ttf");
        Typeface face2 = Typeface.createFromAsset(getAssets(),
                "fonts/epimodem2.ttf");
        edit.setTypeface(face);
        mTitle.setTypeface(face2);
        conversationsList = new ArrayList<>();
        progressBar = findViewById(R.id.progressBarc);

        recyclerView = findViewById(R.id.recyclerViewc);

        progressBar.setVisibility(View.VISIBLE);

        recyclerView.setHasFixedSize(true);

        recyclerViewlayoutManager = new LinearLayoutManager(this);

        recyclerView.setLayoutManager(recyclerViewlayoutManager);
        // **********************************************************************
        FriendNames = new ArrayList<>();
        Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    while (!isInterrupted()) {
                        Thread.sleep(1000);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                JSON_DATA_WEB_CALL();
                                conversationsList.clear();
                            }
                        });
                    }
                } catch (InterruptedException e) {
                }
            }
        };
        if(!conversationsList.isEmpty()){
            recyclerView.scrollToPosition(conversationsList.size() - 1);
        }
        t.start();

        }


    public void JSON_DATA_WEB_CALL() {

        jsonArrayRequest = new JsonArrayRequest(HTTP_JSON_URL,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        progressBar.setVisibility(View.GONE);
                        JSON_PARSE_DATA_AFTER_WEBCALL(response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });

        requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(jsonArrayRequest);
    }

    public void JSON_PARSE_DATA_AFTER_WEBCALL(final JSONArray array){
                        try {
                            recyclerView.getRecycledViewPool().clear();
                            for (int i = 0; i < array.length(); i++) {
                                ConversationsList GetDataAdapter1 = new ConversationsList();
                                JSONObject json;
                                json = array.getJSONObject(i);
                                FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
                                String my_uid = user.getUid();
                                intent = getIntent();
                                String check = json.getString(GET_JSON_FROM_SERVER_NAME3);
                                String check2 = json.getString(GET_JSON_FROM_SERVER_NAME6);
                                String friend_uid = intent.getExtras().getString("Uid");
                                if ((check.contains(friend_uid) && my_uid.contains(check2)) || (check.contains(my_uid) && check2.contains(friend_uid)) && !"".equals(json.getString(GET_JSON_FROM_SERVER_NAME7))) {
                                    GetDataAdapter1.setmy_name(json.getString(GET_JSON_FROM_SERVER_NAME));
                                    GetDataAdapter1.setfriend_name(json.getString(GET_JSON_FROM_SERVER_NAME4));
                                    GetDataAdapter1.setmy_uid(json.getString(GET_JSON_FROM_SERVER_NAME6));
                                    GetDataAdapter1.setfriend_uid(json.getString(GET_JSON_FROM_SERVER_NAME3));
                                    GetDataAdapter1.setimageurl(json.getString(GET_JSON_FROM_SERVER_NAME2));
                                    GetDataAdapter1.setmessage(json.getString(GET_JSON_FROM_SERVER_NAME7));
                                    GetDataAdapter1.settime(json.getString(GET_JSON_FROM_SERVER_NAME5));
                                    FriendNames.add(json.getString(GET_JSON_FROM_SERVER_NAME));
                                    FriendNames.add(json.getString(GET_JSON_FROM_SERVER_NAME7));
                                    FriendNames.add(json.getString(GET_JSON_FROM_SERVER_NAME2));
                                    FriendNames.add(json.getString(GET_JSON_FROM_SERVER_NAME3));
                                    FriendNames.add(json.getString(GET_JSON_FROM_SERVER_NAME4));
                                    FriendNames.add(json.getString(GET_JSON_FROM_SERVER_NAME5));
                                    FriendNames.add(json.getString(GET_JSON_FROM_SERVER_NAME6));
                                    conversationsList.add(GetDataAdapter1);
                                    recyclerViewadapter = new ConversationsRecyclerAdapter(conversationsList, context);
                                    recyclerView.setAdapter(recyclerViewadapter);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }


    public void send_messages(View v)
    {   Intent intent = getIntent();
        String imageurl ="";
        String friend_name=intent.getExtras().getString("Name");
        String friend_uid =intent.getExtras().getString("Uid");
        EditText et;
        et = findViewById(R.id.message);
        String message = et.getText().toString();
        String time = DateFormat.getDateTimeInstance().format(new Date());
        imageurl =intent.getExtras().getString("Imageurl");
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        if (user != null) {
            String my_name = user.getDisplayName();
                    if("".equals(my_name)){
                String mEmail = user.getEmail();
                        int iend = mEmail.indexOf("@");
                        if(iend != -1)
                        {
                            my_name = mEmail.substring(0,iend);
                        }
                    }
            String my_uid = user.getUid();
            String method = "message";
            backgroundtask bgtask = new backgroundtask(this);
            bgtask.execute(method,my_name,my_uid,friend_name,friend_uid,imageurl,time,message);
            recyclerView.scrollToPosition(conversationsList.size() - 1);
        }
    }
}

MessagesRecyclerAdapter.java

public class MessagesRecyclerAdapter extends RecyclerView.Adapter<MessagesRecyclerAdapter.ViewHolder1>{
    Context context;
    Context ctx;
    List<MessagesList>  MessagesList;

    public MessagesRecyclerAdapter(List<MessagesList> getDataAdapter1, Context context){
        super();
        this.MessagesList = getDataAdapter1;
        this.context = context;
    }
    @Override
    public ViewHolder1 onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_messages, parent, false);
        return new ViewHolder1(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder1 holder, int position) {
        ImageView ImageUrl1 = holder.ImageUrl;
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        MessagesList getDataAdapter1 =  MessagesList.get(position);
        final String Name = getDataAdapter1.getFriend_name();
        final String Uid = getDataAdapter1.getfrienduid();
        final String Imageurlserver = getDataAdapter1.getImageurl();
        final String Imageurlserve = user.getPhotoUrl().toString();
        holder.FriendName.setText(getDataAdapter1.getFriend_name());
        if(!"".equals(Imageurlserver))
        {Picasso.with(context).load(Imageurlserver).into(ImageUrl1);}
        else{
            ImageUrl1.setImageResource(R.drawable.profile);
        }
        holder.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent;
                intent = new Intent(context, messages.class);
                intent.putExtra("Name", Name);
                intent.putExtra("Uid",Uid);
                intent.putExtra("Imageurl",Imageurlserve);
                context.startActivity(intent);
            }
            });
        }
    @Override
    public int getItemCount() {
        return MessagesList.size();
    }

    class ViewHolder1 extends RecyclerView.ViewHolder{

        public TextView FriendName;
        public ImageView ImageUrl;
        public Button button;

        public ViewHolder1(View itemView) {
            super(itemView);
            Typeface face = Typeface.createFromAsset(itemView.getContext().getAssets(),
                    "fonts/epimodem.ttf");
            Typeface face2 = Typeface.createFromAsset(itemView.getContext().getAssets(),
                    "fonts/epimodem2.ttf");
            FriendName = itemView.findViewById(R.id.MessageCard6);  this.FriendName.setTypeface(face);
            ImageUrl = itemView.findViewById(R.id.Messagepic);
            button = itemView.findViewById(R.id.send_message);
        }
    }
}
ColdFire
  • 6,764
  • 6
  • 35
  • 51
  • 4
    Possible duplicate of [RecyclerView: Inconsistency detected. Invalid item position](https://stackoverflow.com/questions/30220771/recyclerview-inconsistency-detected-invalid-item-position) – Vishal Yadav Mar 14 '18 at 07:04
  • I have seen this question but this question is not discussing about recyclerview and so it is not a duplicate.This exception is probably occuring because of scrolling without saving previous scrolling instance but i don't know how can i achieve this. @V.Y. – Vishal Rajput Mar 14 '18 at 07:11
  • The whole discussion is about **RecyclerView** please check once again... – Vishal Yadav Mar 14 '18 at 07:25
  • yup i saw one of the answer which says: recyclerView.getRecycledViewPool().clear(); recyclerViewadapter.notifyDataSetChanged(); this removes the error but recycerview skips to the top position after every refresh it is not going to the previous saved scrolling state!! @V.Y. – Vishal Rajput Mar 14 '18 at 07:30

2 Answers2

0

clear conversationsList before the call JSON_DATA_WEB_CALL()

   public void run() {
          conversationsList.clear();
          JSON_DATA_WEB_CALL();
   }
Sagar Jethva
  • 986
  • 12
  • 26
  • Nope it doesn't work!!! i am getting the same error!! i think it is not working because after scrolling and clearing the position of the item in the viewholder gets changed there is some inconsistency so i want to know how can i change the previous scrolling state before clearing the list and then displaying the recyclerview with the same scrolling state. – Vishal Rajput Mar 14 '18 at 07:24
0

Don't set new adapter everytime you refresh data. Create adapter once and then set conversationsList in this adapter and call notifyDataSetChanged

RadekJ
  • 2,835
  • 1
  • 19
  • 25
  • Didn't work! notifyDataSetChanged() gives a null pointer exception. – Vishal Rajput Mar 14 '18 at 10:54
  • inside your adapter write method `setConversationsList(list)`, inside that method call `notifyDataSetChanged()` – RadekJ Mar 14 '18 at 10:57
  • how are you calling `notifyDataSetChanged()` now? Can you show the code? – RadekJ Mar 14 '18 at 11:08
  • I have called it after the line recyclerview.setAdapter() method. – Vishal Rajput Mar 14 '18 at 11:10
  • set adapter only once in onCreate, then keep reference to that adapater and whenever you refresh list just pass new data to existing adapter and call notifyDataSetChanged – RadekJ Mar 14 '18 at 11:15
  • Thank You!! It worked..I was creating a new object of adapter instead of referencing to the adapter. Whenever I found that new data is available I cleared the conversationsList and added new data and called notifyDataSetChanged which worked!! – Vishal Rajput Nov 24 '20 at 08:29