Salutation

J'éssaye d'avoir une liste de groupe message en passant par un recyclerView dans un fragment, Nb: je débute en Android et Java, voici mon code


Code de mon fragment (Discution Fragment)

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
package com.kirinno.maligaclassique;
 
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
 
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
 
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Toast;
 
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
 
import java.util.ArrayList;
 
 
public class DiscutionFragment extends Fragment {
 
    private static final String TAG = "DiscutionFragment";
    ChatRoomRepository chatRoomRepository;
    private RecyclerView chatRooms;
 
    private View discutionFragmentView;
    private RecyclerView myDiscutionList;
 
    //private ListView listView;
    private ArrayAdapter<String> adapter;
    ArrayList<String> boutiques;
    String idBoutique;
    // private ChatRoomsAdapter adapter;
 
    private static final String CURRENT_USER_KEY = "CURRENT_USER_KEY";
    public static final String CURRENT_USER_PHONE= "CURRENT_USER_PHONE";
 
    AuthenticationRepository authentication;
 
    public static String phone = "";
    private Object ChatBoutiquesAdapter;
 
    public DiscutionFragment () {
 
    }
 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 
        discutionFragmentView = inflater.inflate(R.layout.activity_discution, container, false);
 
        myDiscutionList = (RecyclerView) discutionFragmentView.findViewById(R.id.discution_list);
        myDiscutionList.setLayoutManager(new LinearLayoutManager(getContext()));
 
        return discutionFragmentView;
 
    }
 
 
 
 
 
@Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
 
 
 
    /*
         * If the device is having android oreo we will create a notification channel
         * */
 
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager mNotificationManager =
                    (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = new NotificationChannel(ChannelInfo.CHANNEL_ID, ChannelInfo.CHANNEL_NAME, importance);
            mChannel.setDescription(ChannelInfo.CHANNEL_DESCRIPTION);
            mChannel.enableLights(true);
            mChannel.setLightColor(Color.BLUE);
            mChannel.enableVibration(true);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            mNotificationManager.createNotificationChannel(mChannel);
        }
 
        Bundle extras = getActivity().getIntent().getExtras();
        if (extras != null) {
            phone = extras.getString(CURRENT_USER_PHONE, "");
        }
        Toast.makeText(getActivity(), phone, Toast.LENGTH_SHORT).show();
 
        chatRoomRepository = new ChatRoomRepository(FirebaseFirestore.getInstance());
        authentication = new AuthenticationRepository(FirebaseFirestore.getInstance());
 
        // listView = view.findViewById(R.id.list_item);
        //chatRooms = view.findViewById(R.id.list_of_pseudo);
 
        //initUI();
        //getChatRooms();
        //getChatBoutiques();
        authenticate();
 
        /*listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
 
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                // TODO Auto-generated method stub
                String text = (String) listView.getItemAtPosition(arg2);
                getBoutiqueId(text);
                Intent intent = new Intent(getActivity(), ChatRoomActivity.class);
                intent.putExtra(ChatRoomActivity.CHAT_ROOM_ID, idBoutique);
                intent.putExtra(ChatRoomActivity.CHAT_ROOM_NAME, text);
                startActivity(intent);
                //Toast.makeText(getActivity(), idBoutique, Toast.LENGTH_SHORT).show();
 
            }
        });*/
 
 
 
}
 
    private void getChatBoutiques(){
        chatRoomRepository.getBoutiques(phone, new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(QuerySnapshot snapshots, FirebaseFirestoreException e) {
                if (e != null) {
                    Log.e("DiscutionFragment", "Listen failed.", e);
                    return;
                }
 
                boutiques = new ArrayList<>();
                for (QueryDocumentSnapshot doc : snapshots) {
                    boutiques.add(doc.getString("nom_boutique"));
 
                }
               /* adapter = new ChatBoutiquesAdapter(getActivity(), R.layout.item_boutique_listview, boutiques);
                listView.setAdapter(adapter);*/
            }
        });
    }
 
    public void getBoutiqueId(String text){
 
        chatRoomRepository.getBoutiquesId(text, new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(QuerySnapshot snapshots, FirebaseFirestoreException e) {
                if (e != null) {
                    Log.e("DiscutionFragment", "Listen failed.", e);
                    return;
                }
 
                for (QueryDocumentSnapshot doc : snapshots) {
                    idBoutique = doc.getId();
                }
 
            }
        });
    }
 
   /*
    private void initUI() {
        chatRooms.setLayoutManager(new LinearLayoutManager(getActivity()));
    }
    private void getChatRooms() {
        chatRoomRepository.getRooms(new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(QuerySnapshot snapshots, FirebaseFirestoreException e) {
                if (e != null) {
                    Log.e("DiscutionFragment", "Listen failed.", e);
                    return;
                }
 
                List<ChatRoom> rooms = new ArrayList<>();
                for (QueryDocumentSnapshot doc : snapshots) {
                    rooms.add(new ChatRoom(doc.getId(), doc.getString("name")));
                }
 
                adapter = new ChatRoomsAdapter(rooms, listener);
                chatRooms.setAdapter(adapter);
            }
        });
    }
 
    ChatRoomsAdapter.OnChatRoomClickListener listener = new ChatRoomsAdapter.OnChatRoomClickListener() {
        @Override
        public void onClick(ChatRoom chatRoom) {
            Intent intent = new Intent(getActivity(), ChatRoomActivity.class);
            intent.putExtra(ChatRoomActivity.CHAT_ROOM_ID, chatRoom.getId());
            intent.putExtra(ChatRoomActivity.CHAT_ROOM_NAME, chatRoom.getName());
            startActivity(intent);
        }
    };
*/
 
 
    private void authenticate() {
        String currentUserKey = getCurrentUserKey();
        if (currentUserKey.isEmpty())
        {
            authentication.createNewUser(
                    new OnSuccessListener<DocumentReference>() {
                        @Override
                        public void onSuccess(DocumentReference documentReference) {
                            saveCurrentUserKey(documentReference.getId());
                            Toast.makeText(getActivity(), "New user created", Toast.LENGTH_SHORT).show();
                        }
                    },
                    new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast.makeText(
                                    getActivity(),
                                    "Error creating user. Check your internet connection",
                                    Toast.LENGTH_SHORT)
                                    .show();
                        }
                    }
            );
        } else {
            authentication.login(
                    currentUserKey,
                    new OnSuccessListener<DocumentReference>() {
                        @Override
                        public void onSuccess(DocumentReference documentReference) {
                            Toast.makeText(getActivity(), "Logged in", Toast.LENGTH_SHORT).show();
                        }
                    },
                    new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast.makeText(
                                    getActivity(),
                                    "Error signing in. Check your internet connection",
                                    Toast.LENGTH_SHORT)
                                    .show();
                        }
                    }
            );
        }
    }
 
    private String getCurrentUserKey() {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getContext());
        return preferences.getString(CURRENT_USER_KEY, "");
 
    }
 
    private void saveCurrentUserKey(String key) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getContext());
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(CURRENT_USER_KEY, key);
        editor.apply();
    }
}

Mon adaptateur (ChatBoutiqueAdapter) :

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
package com.kirinno.maligaclassique;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
 
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
 
import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;
 
import java.util.List;
 
import de.hdodenhof.circleimageview.CircleImageView;
 
 
 
public class ChatBoutiquesAdapter extends RecyclerView.ViewHolder
{
    TextView BoutiqueName, BeforelastMessage, LastMessage;
    CircleImageView profileImage;
    ImageView onlineIcon;
ListView boutiqueName;
ListView beforeLastMessage;
ListView lastMessage;
 
    public ChatBoutiquesAdapter(@NonNull View itemView)
    {
        super(itemView);
 
        boutiqueName = itemView.findViewById(R.id.boutique_name);
        beforeLastMessage = itemView.findViewById(R.id.Before_last_message);
        lastMessage = itemView.findViewById(R.id.Last_message);
        profileImage = itemView.findViewById(R.id.users_profile_image);
        onlineIcon = (ImageView) itemView.findViewById(R.id.user_online_status);
    }
 
 
 
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_boutique_listview, parent, false);
 
        return new ViewHolder(itemView);
    }
 
public  class ViewHolder extends RecyclerView.ViewHolder {
    ImageView onlineIcon;
    ImageView profileImage;
    TextView boutiqueName;
    TextView beforeLastMessage;
    TextView lastMessage;
 
    public ViewHolder(View view) {
        super(view);
 
        onlineIcon = (ImageView)view.findViewById(R.id.user_online_status);
        profileImage = (ImageView)view.findViewById(R.id.users_profile_image);
        boutiqueName = (TextView )view.findViewById(R.id.boutique_name);
        beforeLastMessage = (TextView )view.findViewById(R.id.Before_last_message);
        lastMessage  = (TextView )view.findViewById(R.id.Last_message);
 
    }
 
}};
 
 
 
 
 
 
 
 
 
/*public class ChatBoutiquesAdapter extends ArrayAdapter<String> {
 
    private Context activity;
    private List<String> boutiqueList;
 
    public ChatBoutiquesAdapter(Context context, int resource, List<String> objects) {
        super(context, resource, objects);
        this.activity = context;
        this.boutiqueList = objects;
    }
 
    @Override
    public int getCount() {
        return boutiqueList.size();
    }
 
    @Override
    public String getItem(int position) {
        return boutiqueList.get(position);
    }
 
    @Override
    public long getItemId(int position) {
        return position;
    }
 
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        // If holder not exist then locate all view from UI file.
        if (convertView == null) {
            // inflate UI from XML file
            convertView = inflater.inflate(R.layout.item_boutique_listview, parent, false);
            // get all UI view
            holder = new ViewHolder(convertView);
            // set tag for holder
            convertView.setTag(holder);
        } else {
            // if holder created, get tag from view
            holder = (ViewHolder) convertView.getTag();
        }
 
        holder.boutiqueName.setText(getItem(position));
 
        //get first letter of each String item
        String firstLetter = String.valueOf(getItem(position).charAt(0));
 
        ColorGenerator generator = ColorGenerator.MATERIAL; // or use DEFAULT
        // generate random color
        int color = generator.getColor(getItem(position));
        //int color = generator.getRandomColor();
 
        TextDrawable drawable = TextDrawable.builder()
                .buildRound(firstLetter, color); // radius in px
 
        holder.imageView.setImageDrawable(drawable);
 
        return convertView;
    }
 
    private class ViewHolder {
        private ImageView imageView;
        private TextView boutiqueName;
 
        public ViewHolder(View v) {
            imageView = (ImageView) v.findViewById(R.id.image_view);
            boutiqueName = (TextView) v.findViewById(R.id.text);
        }
    }
}*/
 
 
 
 
 
 
/*import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
 
import androidx.recyclerview.widget.RecyclerView;
 
import java.util.List;
 
public class ChatRoomsAdapter extends RecyclerView.Adapter<ChatRoomsAdapter.ChatRoomViewHolder> {
 
    interface OnChatRoomClickListener {
        void onClick(ChatRoom chatRoom);
    }
 
    private OnChatRoomClickListener listener;
 
        private List<ChatRoom> chatRooms;
 
 
    public ChatRoomsAdapter(List<ChatRoom> chatRooms, OnChatRoomClickListener listener) {
        this.chatRooms = chatRooms;
        this.listener = listener;
    }
 
    public ChatRoomsAdapter(List<ChatRoom> chatRooms) {
        this.chatRooms = chatRooms;
    }
 
    @Override
    public ChatRoomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(
                R.layout.item_chat_room,
                parent,
                false
        );
        return new ChatRoomViewHolder(view);
    }
 
    @Override
    public void onBindViewHolder(ChatRoomViewHolder holder, int position) {
        holder.bind(chatRooms.get(position));
    }
 
    @Override
    public int getItemCount() {
        return chatRooms.size();
    }
 
    class ChatRoomViewHolder extends RecyclerView.ViewHolder {
        TextView name;
        ChatRoom chatRoom;
 
        public ChatRoomViewHolder(View itemView) {
            super(itemView);
            name = itemView.findViewById(R.id.item_chat_room_name);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    listener.onClick(chatRoom);
                }
            });
        }
 
        public void bind(ChatRoom chatRoom) {
            this.chatRoom = chatRoom;
            name.setText(chatRoom.getName());
        }
    }
}*/

Ma classe java (Boutique.java)

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package com.kirinno.maligaclassique;
 
public class Boutique {
    public String boutique, before_last_message, last_message,image;
 
 
 
    public Boutique(String boutique, String before_last_message, String last_message,String image) {
        this.boutique = boutique;
        this.before_last_message = before_last_message;
        this.last_message = last_message;
        this.image = image;
    }
 
    public String getBoutique() {
        return boutique;
    }
 
    public void setBoutique(String boutique) {
        this.boutique = boutique;
    }
 
    public String getBefore_last_message() {
        return before_last_message;
    }
 
    public void setBefore_last_message(String before_last_message) {
        this.before_last_message = before_last_message;
    }
 
    public String getLast_message() {
        return last_message;
    }
 
    public void setLast_message(String last_message) {
        this.last_message = last_message;
    }
 
 
    public String getImage() {
        return image;
    }
 
    public void setImage(String image) {
        this.image = image;
    }
}