无法从适配器更新我的arraylist

时间:2018-03-05 06:17:08

标签: android

我正在处理这个聊天应用程序。在那,我想在回收站视图中搜索特定的消息。为此,我使用Filterable接口。当我尝试使用arraylist更新notifydatasetchange()时,它不会更改arraylist项。它保持不变。

这是我的适配器代码。

MessageAdapter.java

package com.android.customizedchat;
import java.lang.*;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import android.widget.BaseAdapter;
import android.widget.ArrayAdapter;
import android.app.Activity;
import android.content.Context;
import android.widget.Filter;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.*;


public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.ViewHolder> implements Filterable {

    List<Message> filteredmessageList;
    List<Message> messages;


    public MessageAdapter(List<Message> objects){
        this.messages = objects;
        this.filteredmessageList = objects;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_message,parent,false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Message message = messages.get(position);
        boolean myMsg=message.getIsMe();
        setAlingnment(holder,myMsg);
        holder.message.setText(message.getText());
        holder.user.setText(message.getName());
        holder.timestamp.setText(message.getTimestamp());
        System.out.println("From Holder: "+holder.message.getText());
    }


    public void setAlingnment(ViewHolder holder,boolean isMe){
        if(!isMe){

            holder.message.setGravity(Gravity.LEFT);
            holder.user.setGravity(Gravity.LEFT);
            holder.timestamp.setGravity(Gravity.LEFT);

        }else {

            holder.message.setGravity(Gravity.RIGHT);
            holder.user.setGravity(Gravity.RIGHT);
            holder.timestamp.setGravity(Gravity.RIGHT);


        }
    }

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

    public class ViewHolder extends RecyclerView.ViewHolder{
        public TextView message;
        public TextView user;
        public TextView timestamp;
        public ImageView message_image;

        public ViewHolder(View view){
            super(view);
            message = (TextView) view.findViewById(R.id.messageTextView);
            user = (TextView)view.findViewById(R.id.nameTextView);
            timestamp = (TextView) view.findViewById(R.id.messageTimeStamp);
            message_image = (ImageView) view.findViewById(R.id.messageImageView);
        }

    }

    public Filter getFilter(){
        return new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                System.out.println("Enter Filtering");
                String charString = constraint.toString();
                if(charString.isEmpty()){
                    filteredmessageList = messages;
                }
                else{
                    List<Message> filterlist = new ArrayList<>();
                    for(Message row : messages){
                        if(row.getText().toLowerCase().contains(charString.toLowerCase())){
                            filterlist.add(row);
                        }
                    }
                    filteredmessageList = filterlist;
                }
                FilterResults filterResults = new FilterResults();
                filterResults.values = filteredmessageList;
                System.out.println(filterResults.values.toString());
                return filterResults;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                filteredmessageList = (ArrayList<Message>) results.values;
                for (int i = 0; i < filteredmessageList.size(); i++) {
                    System.out.println(filteredmessageList.get(i).getText());
                }
              //  notifyDataSetChanged();
            }
        };
    }


}

这是我的主要活动文件

MainActivity.java

package com.android.customizedchat;

import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.*;
import android.widget.*;
import android.support.v7.widget.SearchView;

import java.net.URISyntaxException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import android.view.*;


import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.github.nkzawa.emitter.Emitter;
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {

    public RecyclerView messageListView;
    public MessageAdapter messageAdapter;
    public EditText messageEditText;
    public Button messageSendButton;
    String TimeStamp="";
    public List<Message> message;

    private Socket socket;{
        try{
            socket = IO.socket("http://192.168.137.1:3000");
           // socket = IO.socket("https://customizedchat.herokuapp.com");
        }
        catch (URISyntaxException e){
            throw new RuntimeException(e);
        }
    }

    public String username;
    //public String url_connect ="http://192.168.137.1/test/retrivemessage.php";
    public String url_connect = "http://wallstreet.000webhostapp.com/retrivemessage.php";
    //public String url_insert = "http://192.168.137.1/test/insertmessage.php";
    public String url_insert = "http://wallstreet.000webhostapp.com/insertmessage.php";
    public String uname,msgs,tstamp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Bundle bundle = getIntent().getExtras();
        String GroupID = bundle.getString("GroupID");
        final String GroupName = bundle.getString("GroupName");
        Toast.makeText(this, "ID"+GroupID+"Name"+GroupName, Toast.LENGTH_SHORT).show();
        setTitle(GroupName);

        socket.connect();
        socket.emit("subscribe",GroupName);

        socket.on("newM",handleIncomingMessages);

        SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref",0);
        username=pref.getString("uname",null);

        messageListView=(RecyclerView)findViewById(R.id.messageListView);
        messageListView.setLayoutManager(new LinearLayoutManager(this));
        messageEditText=(EditText)findViewById(R.id.messageEditText);
        messageSendButton=(Button)findViewById(R.id.messageSendButton);

        message =new ArrayList<>();
        messageAdapter=new MessageAdapter(message);
        messageListView.setAdapter(messageAdapter);

        messageSendButton.setEnabled(true);

        StringRequest stringRequest = new StringRequest(Request.Method.POST, url_connect, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try{
                    String res = response;
                    JSONArray msgs = new JSONArray(res);
                    for(int i=0;i<msgs.length();i++){
                        JSONObject msg =(JSONObject) msgs.get(i);
                        String status = msg.getString("code");
                        if(status.equals("success")){
                            String mesg = msg.getString("Message");
                            String uname = msg.getString("Username");
                            String tstamp = msg.getString("TimeStamp");
                            Message message1 = new Message(mesg,uname,tstamp);
                            if(uname.equals(username))
                                message1.setMe(true);
                            addMessage(message1);
                        }
                        else{
                            Toast.makeText(MainActivity.this, "The table for this group has been created in database", Toast.LENGTH_SHORT).show();
                        }
                    }

                }catch (JSONException e){
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this, ""+error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> params=new HashMap<String,String>();
                params.put("grpname",GroupName);
                return params;
            }
        };
        Connection.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);


        messageSendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!(messageEditText.getText().toString().trim().equals(""))) {
                   // final String time = DateFormat.getTimeInstance(DateFormat.SHORT).format(new Date());\
                    Date dt = new Date();
                    long time = dt.getTime();
                    if (android.text.format.DateFormat.is24HourFormat(MainActivity.this)) {
                        TimeStamp =  new SimpleDateFormat("hh:mm a", Locale.US).format(new Date(time));
                    }
                    else{
                        TimeStamp = DateFormat.getTimeInstance(DateFormat.SHORT).format(new Date());
                    }
                    final String msg =messageEditText.getText().toString().trim();
                    Message message = new Message(msg, username,TimeStamp);
                    message.setMe(true);
                   StringRequest insert = new StringRequest(Request.Method.POST, url_insert, new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            Toast.makeText(MainActivity.this, ""+response, Toast.LENGTH_SHORT).show();
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(MainActivity.this, ""+error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }){
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String,String> params=new HashMap<String,String>();
                            params.put("grpname",GroupName);
                            params.put("message",msg);
                            params.put("username",username);
                            params.put("timestamp",TimeStamp);
                            return params;
                        }
                    };
                    Connection.getInstance(getApplicationContext()).addToRequestQueue(insert);
                    String MESSAGGE = messageEditText.getText().toString().trim();
                    addMessage(message);
                    messageEditText.setText("");
                    try {
                        JSONObject object = new JSONObject();
                        object.put("message", MESSAGGE);
                        object.put("userid", username);
                        object.put("timestamp",TimeStamp);
                        object.put("room",GroupName);
                        socket.emit("newM", object);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                else
                    Toast.makeText(MainActivity.this, "Enter text", Toast.LENGTH_SHORT).show();
            }
        });

    }

    //for handeling incoming messages
    private Emitter.Listener handleIncomingMessages = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    JSONObject data=(JSONObject) args[0];
                    String message,uname,tstamp;
                    try {
                        message=data.getString("message").toString().trim();
                        uname = data.getString("uname").toString();
                        tstamp = data.getString("tstamp").toString();
                        //System.out.println("------------------------------------------------------"+uname+" : "+message);
                        Message msg=new Message(message,uname,tstamp);
                        msg.setMe(false);
                        addMessage(msg);
                    }catch (JSONException e){
                        return;
                    }
                }
            });
        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        socket.disconnect();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu,menu);
        MenuItem item = menu.findItem(R.id.actionSearch);
        //SearchView searchView = (SearchView) item.getActionView();
        android.support.v7.widget.SearchView searchView = (android.support.v7.widget.SearchView) item.getActionView();
        searchView.setOnQueryTextListener(new android.support.v7.widget.SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                messageAdapter.getFilter().filter(newText);
                messageAdapter.notifyDataSetChanged();
                return false;
            }
        });
        return super.onCreateOptionsMenu(menu);
    }

    public String getUsername(){
        return username;
    }

    public void addMessage(Message m){
        message.add(m);
        messageAdapter = new MessageAdapter(message);
        messageAdapter.notifyItemInserted(0);
        messageListView.scrollToPosition(messageAdapter.getItemCount()-1);
    }
}

当我在控制台上打印过滤后的值时,它打印完美。但它并没有更新回收者视图的列表。

如果有人能够帮助我找到解决方案,那将会非常有帮助。

1 个答案:

答案 0 :(得分:0)

在通知适配器之前,您必须更新message列表,此方法如下:

  @Override
        public boolean onQueryTextChange(String newText) {
            messageAdapter.getFilter().filter(newText);
            messageAdapter.notifyDataSetChanged();
            return false;
        }