отображать данные о последних данных json согласно идентификатору пользователя - PullRequest
0 голосов
/ 04 мая 2018

Я не хочу отображать список чатов клиентов. Данные поступают из JSON, последнее сообщение чата отображается в чате. но оно отображает все сообщения всех клиентов в списке. like

enter image description here

вот моя активность ListMessage.class

public class ListMessage extends AppCompatActivity implements View.OnClickListener {
ImageButton btnFooter_Home, btnFooter_Message, btnFooter_Notification, btnFooter_More;
EditText textUser;
List<Msg_data> msgList;
ListView lv;
String uri = "http://staging.talentslist.com/api/user/23/chat";
LinearLayout linear_Home, linear_Message, linear_Notification, linear_More;
GlobalClass myGlog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list_message);
    myGlog = new GlobalClass(getApplicationContext());
    setFooter();
    lv = (ListView) findViewById(R.id.listView);
    textUser = (EditText) findViewById(R.id.textUser);
    //       textUser.isFocused()
    boolean inConnected = myGlog.isNetworkConnected();
    if (inConnected) {
         requestData(uri);
    }

}

public void requestData(String uri) {

    StringRequest request = new StringRequest(uri,

            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    msgList = MsgJSONParser.parseData(response);
                    MsgAdapter adapter = new MsgAdapter(ListMessage.this, msgList);
                    lv.setAdapter(adapter);

                }
            },

            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                    Toast.makeText(ListMessage.this, error.getMessage().toString(), Toast.LENGTH_SHORT).show();
                }
            });

    RequestQueue queue = Volley.newRequestQueue(this);
    queue.add(request);
}
}  

MsgAdapter.java class

public class MsgAdapter extends BaseAdapter{

private Context context;
private List<Msg_data> nList;
private LayoutInflater inflater = null;

private LruCache<Integer, Bitmap> imageCache;
private RequestQueue queue;
String isread;

public MsgAdapter(Context context, List<Msg_data> list) {

    this.context = context;
    this.nList = list;
    inflater = LayoutInflater.from(context);

    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    final int cacheSize = maxMemory / 8;
    imageCache = new LruCache<>(cacheSize);

    queue = Volley.newRequestQueue(context);
}

public class ViewHolder {

    TextView __isread;
    TextView _username;
    TextView _detais;
    TextView _time;

    ImageView _image;

}

@Override
public int getCount() {
    return nList.size();
}

@Override
public Object getItem(int position) {

    return nList.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup viewGroup) {

    final Msg_data msg = nList.get(position);
    final ViewHolder holder;
    isread = msg.getIs_read();
    if (convertView == null) {

        convertView = inflater.inflate(R.layout.list_item_notification, null);
        if (isread.equals("0")) {
            convertView.setBackgroundColor(Color.parseColor("#009999"));
        }
        holder = new ViewHolder();
        holder._username = (TextView) convertView.findViewById(R.id.tvtitle);
        holder._detais = (TextView) convertView.findViewById(R.id.tvdesc);
        holder.__isread = (TextView) convertView.findViewById(R.id.tvplateform);
        holder._time = (TextView) convertView.findViewById(R.id.createdTime);

        convertView.setTag(holder);
    } else {

        holder = (ViewHolder) convertView.getTag();
    }

    holder._username.setText(msg.getUser_name().toString());
    holder._detais.setText(msg.getMessage().toString());
    holder._time.setText(msg.getCreated_at().toString());
    //   holder.__isread.setText(notifi.getIs_read().toString());
    holder._image = (ImageView) convertView.findViewById(R.id.gameImage);

    Glide.with(context)
            .load(msg.getImage_link().toString())                     // Set image url
            .diskCacheStrategy(DiskCacheStrategy.ALL)   // Cache for image
            .into(holder._image);
    return convertView;
}
}

Msg_data.java class

public class Msg_data {
public int id;
public String user_id;
public String user_name;
public String message;
public String is_read;
public String image_link;
public String created_at;
public String from;
public String to;


public String getFrom() {
    return from;
}

public void setFrom(String from) {
    this.from = from;
}

public String getTo() {
    return to;
}

public void setTo(String to) {
    this.to = to;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}


public String getUser_id() {
    return user_id;
}

public void setUser_id(String user_id) {
    this.user_id = user_id;
}


public String getUser_name() {
    return user_name;
}

public void setUser_name(String user_name) {
    this.user_name = user_name;
}


public String getMessage() {
    return message;
}

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


public String getIs_read() {
    return is_read;
}

public void setIs_read(String is_read) {
    this.is_read = is_read;
}


public String getImage_link() {
    return image_link;
}

public void setImage_link(String image_link) {
    this.image_link = image_link;
}

public String getCreated_at() {
    return created_at;
}

public void setCreated_at(String created_at) {
    this.created_at = created_at;
}

public Msg_data() {
}

public Msg_data(int id) {
    this.id = id;
}
}

MsgJSONParser.java class

public class MsgJSONParser {
static List<Msg_data> notiList;

public static List<Msg_data> parseData(String content) {

    JSONArray noti_arry = null;
    Msg_data noti = null;
    try {
        JSONObject jsonObject = new JSONObject(content);
        noti_arry = jsonObject.getJSONArray("data");
        notiList = new ArrayList<>();

        for (int i = 0; i < noti_arry.length(); i++) {
            JSONObject obj = noti_arry.getJSONObject(i);

            //JSONObject obj = noti_arry.getJSONObject(i);
            noti = new Msg_data();

            noti.setId(obj.getInt("id"));
            noti.setMessage(obj.getString("message"));
            noti.setUser_name(obj.getString("user_name"));
            noti.setFrom(obj.getString("from"));
            noti.setTo(obj.getString("to"));
            noti.setCreated_at(obj.getString("created_at"));
            noti.setImage_link(obj.getString("image_link"));
            noti.setIs_read(obj.getString("is_read"));

            notiList.add(noti);
        }
        return notiList;

    } catch (JSONException ex) {
        ex.printStackTrace();
        return null;
    }
}
}

пожалуйста, дайте мне некоторое представление о том, что и как делать

1 Ответ

0 голосов
/ 04 мая 2018

я думаю, вы должны заменить

msgList = MsgJSONParser.parseData(response);
MsgAdapter adapter = new MsgAdapter(ListMessage.this, msgList);

с

msgList = MsgJSONParser.parseData(response);
ArrayList<Msg_data> userList=new ArrayList();
for (int i=0;i<msgList.size();i++){
    if (!userList.contains(msgList.get(i)))
        userList.add(msgList.get(i));
    else {
        int index=userList.indexOf(msgList.get(i));
        if (userList.get(index).compareTo(msgList.get(i))>0)
            userList.add(msgList.get(i));
    }
}
MsgAdapter adapter = new MsgAdapter(ListMessage.this, userList);`

и реализуйте метод Comparable и override equals в вашем классе Msg_data

public class Msg_data implements Comparable {
public int id;
public String user_id;
public String user_name;
public String message;
public String is_read;
public String image_link;
public String created_at;
public String from;
public String to;


public String getFrom() {
    return from;
}

public void setFrom(String from) {
    this.from = from;
}

public String getTo() {
    return to;
}

public void setTo(String to) {
    this.to = to;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}


public String getUser_id() {
    return user_id;
}

public void setUser_id(String user_id) {
    this.user_id = user_id;
}


public String getUser_name() {
    return user_name;
}

public void setUser_name(String user_name) {
    this.user_name = user_name;
}


public String getMessage() {
    return message;
}

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


public String getIs_read() {
    return is_read;
}

public void setIs_read(String is_read) {
    this.is_read = is_read;
}


public String getImage_link() {
    return image_link;
}

public void setImage_link(String image_link) {
    this.image_link = image_link;
}

public String getCreated_at() {
    return created_at;
}

public void setCreated_at(String created_at) {
    this.created_at = created_at;
}

public Msg_data() {
}

public Msg_data(int id) {
    this.id = id;
}



  @Override
    public boolean equals(Object obj) {  
     try
{
    return (this.getUser_id().equals(( (Msg_data)obj).getUser_id()));
    }
    catch(NullPointerException e){
    return false;
    }
        }

@Override
public int compareTo(@NonNull Object o) {
    SimpleDateFormat simpleDateFormat=new SimpleDateFormat("your pattern here");
    try {
        Date date=simpleDateFormat.parse(created_at);
        Date dateOtherObject=simpleDateFormat.parse(((Msg_data)o).getCreated_at());
        return  date.compareTo(dateOtherObject);
    }
    catch (ParseException e){
        return -1;
    }
}

как-то так :) Не забудьте заменить простой формат даты в методе сравнения

...