Advertisement
RakaArdiansyah

Glide

Jun 9th, 2019
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 23.18 KB | None | 0 0
  1.  
  2.  
  3. public class ChatActivity extends AppCompatActivity implements View.OnClickListener {
  4. private RecyclerView recyclerChat;
  5. public static final int VIEW_TYPE_USER_MESSAGE = 0;
  6. public static final int VIEW_TYPE_FRIEND_MESSAGE = 1;
  7.  
  8. private FirebaseAuth mAuth;
  9.  
  10. private ListMessageAdapter adapter;
  11. private String roomId;
  12. private ArrayList<CharSequence> idFriend;
  13. private Consersation consersation;
  14. private ImageButton btnSend;
  15. private EditText editWriteMessage;
  16. private LinearLayoutManager linearLayoutManager;
  17. public static HashMap<String, Bitmap> bitmapAvataFriend;
  18. public Bitmap bitmapAvataUser;
  19.  
  20. // Storage Permissions
  21. private static final int REQUEST_EXTERNAL_STORAGE = 1;
  22. private static String[] PERMISSIONS_STORAGE = {
  23. android.Manifest.permission.READ_EXTERNAL_STORAGE,
  24. android.Manifest.permission.WRITE_EXTERNAL_STORAGE
  25. };
  26.  
  27. FirebaseStorage storage = FirebaseStorage.getInstance();
  28.  
  29. private static final int IMAGE_GALLERY_REQUEST = 1;
  30. private static final int IMAGE_CAMERA_REQUEST = 2;
  31.  
  32. //File
  33. private File filePathImageCamera;
  34.  
  35. static final String TAG = ChatActivity.class.getSimpleName();
  36.  
  37. //Progress Upload
  38. private ProgressDialog mProgressDialog;
  39.  
  40. @Override
  41. protected void onCreate(Bundle savedInstanceState) {
  42. super.onCreate(savedInstanceState);
  43. setContentView(R.layout.activity_chat);
  44. Intent intentData = getIntent();
  45. idFriend = intentData.getCharSequenceArrayListExtra(StaticConfig.INTENT_KEY_CHAT_ID);
  46. roomId = intentData.getStringExtra(StaticConfig.INTENT_KEY_CHAT_ROOM_ID);
  47. String nameFriend = intentData.getStringExtra(StaticConfig.INTENT_KEY_CHAT_FRIEND);
  48.  
  49. mProgressDialog = new ProgressDialog(this);
  50.  
  51. consersation = new Consersation();
  52. btnSend = (ImageButton) findViewById(R.id.btnSend);
  53. btnSend.setOnClickListener(this);
  54.  
  55. String base64AvataUser = SharedPreferenceHelper.getInstance(this).getUserInfo().avata;
  56. if (!base64AvataUser.equals(StaticConfig.STR_DEFAULT_BASE64)) {
  57. byte[] decodedString = Base64.decode(base64AvataUser, Base64.DEFAULT);
  58. bitmapAvataUser = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
  59. } else {
  60. bitmapAvataUser = null;
  61. }
  62.  
  63. editWriteMessage = findViewById(R.id.editWriteMessage);
  64.  
  65. if (idFriend != null && nameFriend != null) {
  66. getSupportActionBar().setTitle(nameFriend);
  67. linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
  68. recyclerChat = findViewById(R.id.recyclerChat);
  69. recyclerChat.setLayoutManager(linearLayoutManager);
  70. adapter = new ListMessageAdapter(this, consersation, bitmapAvataFriend,
  71. bitmapAvataUser);
  72. FirebaseDatabase.getInstance().getReference().child("message/" + roomId)
  73. .addChildEventListener
  74. (new ChildEventListener() {
  75. @Override
  76. public void onChildAdded(DataSnapshot dataSnapshot, String s) {
  77.  
  78. if (dataSnapshot.getValue() != null) {
  79. HashMap mapMessage = (HashMap) dataSnapshot.getValue();
  80. Message newMessage = new Message();
  81. newMessage.idSender = (String) mapMessage.get("idSender");
  82. newMessage.idReceiver = (String) mapMessage.get("idReceiver");
  83. newMessage.text = (String) mapMessage.get("text");
  84. newMessage.timestamp = (Long) mapMessage.get("timestamp");
  85. consersation.getListMessageData().add(newMessage);
  86. adapter.notifyDataSetChanged();
  87. linearLayoutManager.scrollToPosition(consersation
  88. .getListMessageData().size() - 1);
  89. }
  90. }
  91.  
  92. @Override
  93. public void onChildChanged(DataSnapshot dataSnapshot, String s) {
  94. }
  95.  
  96. @Override
  97. public void onChildRemoved(DataSnapshot dataSnapshot) {
  98. }
  99.  
  100. @Override
  101. public void onChildMoved(DataSnapshot dataSnapshot, String s) {
  102. }
  103.  
  104. @Override
  105. public void onCancelled(DatabaseError databaseError) {
  106.  
  107. }
  108. });
  109. recyclerChat.setAdapter(adapter);
  110. }
  111. }
  112.  
  113. @Override
  114. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  115. super.onActivityResult(requestCode, resultCode, data);
  116. //TODO:INI YANG DI CARI URL IMAGE
  117. StorageReference storageRef = storage.getReferenceFromUrl(Util.URL_STORAGE_REFERENCE)
  118. .child(Util.FOLDER_STORAGE_IMG);
  119.  
  120. if (requestCode == IMAGE_GALLERY_REQUEST && resultCode == RESULT_OK) {
  121. Uri selectedImageUri = data.getData();
  122. if (selectedImageUri != null) {
  123. sendImageFirebase(storageRef, selectedImageUri);
  124. } else {
  125. //URI IS NULL
  126. }
  127. } else if (requestCode == IMAGE_CAMERA_REQUEST) {
  128. if (resultCode == RESULT_OK) {
  129. if (filePathImageCamera != null && filePathImageCamera.exists()) {
  130. StorageReference imageCameraRef = storageRef.child(filePathImageCamera.getName() + ".jpg");
  131. sendCameraFirebase(imageCameraRef, filePathImageCamera);
  132. } else {
  133. //IS NULL
  134. }
  135. }
  136. }
  137. }
  138.  
  139. @Override
  140. public boolean onCreateOptionsMenu(Menu menu) {
  141. getMenuInflater().inflate(R.menu.menu_chat, menu);
  142. return true;
  143. }
  144.  
  145. public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
  146. Log.d(TAG, "onConnectionFailed:" + connectionResult);
  147. Util.initToast(this, "Google Play Services error.");
  148. }
  149.  
  150. public void clickImageChat(View view, int position, String nameUser, String urlPhotoUser, String urlPhotoClick) {
  151. Intent intent = new Intent(this, FullScreenImageActivity.class);
  152. intent.putExtra("nameUser", nameUser);
  153. intent.putExtra("urlPhotoUser", urlPhotoUser);
  154. intent.putExtra("urlPhotoClick", urlPhotoClick);
  155. startActivity(intent);
  156. }
  157.  
  158. private void sendImageFirebase(StorageReference storageReference, final Uri file) {
  159. if (storageReference != null) {
  160. final String name = DateFormat.format("yyyy-MM-dd_hhmmss", new Date()).toString();
  161. final StorageReference imageGalleryRef = storageReference.child(name + "_gallery");
  162. UploadTask uploadTask = imageGalleryRef.putFile(file);
  163. mProgressDialog.setMessage("Uploading...");
  164. mProgressDialog.setCanceledOnTouchOutside(false);
  165. mProgressDialog.show();
  166. uploadTask.addOnFailureListener(new OnFailureListener() {
  167. @Override
  168. public void onFailure(@NonNull Exception e) {
  169. Log.e(TAG, "onFailure sendFileFirebase " + e.getMessage());
  170. }
  171. })
  172. .addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
  173. @Override
  174. public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
  175. //TODO:INI YANG DI CARI URL IMAGE
  176. if (task.isSuccessful()) {
  177. String download_url = task.getResult().getDownloadUrl().toString();
  178.  
  179. Message newMessage = new Message();
  180. newMessage.text = download_url;
  181. newMessage.idSender = StaticConfig.UID;
  182. newMessage.idReceiver = roomId;
  183. newMessage.timestamp = System.currentTimeMillis();
  184. FirebaseDatabase.getInstance().getReference().child("message/" + roomId).push().setValue(newMessage);
  185. mProgressDialog.dismiss();
  186. Toast.makeText(ChatActivity.this, "pesan gambar terkirim", Toast.LENGTH_SHORT).show();
  187. }
  188. }
  189. });
  190.  
  191. } else {
  192. //IS NULL
  193. }
  194.  
  195. }
  196.  
  197. private void sendCameraFirebase(StorageReference storageReference, final File file) {
  198. if (storageReference != null) {
  199. Uri photoURI = FileProvider.getUriForFile(ChatActivity.this,
  200. BuildConfig.APPLICATION_ID + ".provider", file);
  201.  
  202. UploadTask uploadTask = storageReference.putFile(photoURI);
  203. mProgressDialog.setMessage("Uploading...");
  204. mProgressDialog.setCanceledOnTouchOutside(false);
  205. mProgressDialog.show();
  206. uploadTask.addOnFailureListener(new OnFailureListener() {
  207. @Override
  208. public void onFailure(@NonNull Exception e) {
  209. Log.e(TAG, "onFailure sendFileFirebase " + e.getMessage());
  210. }
  211. }).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
  212. @Override
  213. public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
  214. //TODO:INI YANG DI CARI URL IMAGE
  215. if (task.isSuccessful()) {
  216. String download_url = task.getResult().getDownloadUrl().toString();
  217.  
  218. Message newMessage = new Message();
  219. newMessage.text = download_url;
  220. newMessage.idSender = StaticConfig.UID;
  221. newMessage.idReceiver = roomId;
  222. newMessage.timestamp = System.currentTimeMillis();
  223. FirebaseDatabase.getInstance().getReference().child("message/" + roomId)
  224. .push().setValue(newMessage);
  225. mProgressDialog.dismiss();
  226. Toast.makeText(ChatActivity.this, "pesan gambar terkirim",
  227. Toast.LENGTH_SHORT).show();
  228. }
  229. }
  230. });
  231.  
  232. } else {
  233. //IS NULL
  234. }
  235.  
  236. }
  237.  
  238. private void photoCameraIntent() {
  239. String nomeFoto = DateFormat.format("yyyy-MM-dd_hhmmss", new Date()).toString();
  240. filePathImageCamera = new File(Environment.getExternalStoragePublicDirectory(Environment
  241. .DIRECTORY_PICTURES),
  242. nomeFoto + "1234");
  243. Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  244. Uri photoURI = FileProvider.getUriForFile(ChatActivity.this,
  245. BuildConfig.APPLICATION_ID + ".provider",
  246. filePathImageCamera);
  247. it.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
  248. startActivityForResult(it, IMAGE_CAMERA_REQUEST);
  249. }
  250.  
  251. private void photoGalleryIntent() {
  252. Intent intent = new Intent();
  253. intent.setType("image/*");
  254. intent.setAction(Intent.ACTION_GET_CONTENT);
  255. startActivityForResult(Intent.createChooser(intent, getString(R.string.select_picture_title)),
  256. IMAGE_GALLERY_REQUEST);
  257. }
  258.  
  259. public void verifyStoragePermissions() {
  260. // Check if we have write permission
  261. int permission = ActivityCompat.checkSelfPermission(ChatActivity.this,
  262. android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
  263.  
  264. if (permission != PackageManager.PERMISSION_GRANTED) {
  265. // We don't have permission so prompt the user
  266. ActivityCompat.requestPermissions(
  267. ChatActivity.this,
  268. PERMISSIONS_STORAGE,
  269. REQUEST_EXTERNAL_STORAGE
  270. );
  271. } else {
  272. // we already have permission, lets go ahead and call camera intent
  273. photoCameraIntent();
  274. }
  275. }
  276.  
  277. @Override
  278. public boolean onOptionsItemSelected(MenuItem item) {
  279. if (item.getItemId() == android.R.id.home) {
  280. Intent result = new Intent();
  281. result.putExtra("idFriend", idFriend.get(0));
  282. setResult(RESULT_OK, result);
  283. this.finish();
  284. }
  285. switch (item.getItemId()) {
  286. case R.id.sendPhotoGallery:
  287. photoGalleryIntent();
  288. break;
  289. case R.id.sendCamera:
  290. verifyStoragePermissions();
  291. photoCameraIntent();
  292. break;
  293. }
  294. return true;
  295. }
  296.  
  297. @Override
  298. public void onBackPressed() {
  299. Intent result = new Intent();
  300. result.putExtra("idFriend", idFriend.get(0));
  301. setResult(RESULT_OK, result);
  302. this.finish();
  303. }
  304.  
  305. @Override
  306. public void onClick(View view) {
  307. if (view.getId() == R.id.btnSend) {
  308. String content = editWriteMessage.getText().toString().trim();
  309. if (content.length() > 0) {
  310. editWriteMessage.setText("");
  311. Message newMessage = new Message();
  312.  
  313. try {
  314. String kunci = "kibo11" + roomId;
  315. Log.d("kunci", "" + kunci);
  316.  
  317. newMessage.text = content;
  318. newMessage.idSender = StaticConfig.UID;
  319. newMessage.idReceiver = roomId;
  320. newMessage.timestamp = System.currentTimeMillis();
  321. FirebaseDatabase.getInstance().getReference().child("message/" + roomId)
  322. .push().setValue(newMessage);
  323. Toast.makeText(this, "pesan terkirim", Toast.LENGTH_SHORT).show();
  324. } catch (Exception e) {
  325. e.printStackTrace();
  326. }
  327. }
  328. }
  329. }
  330. }
  331.  
  332. class ListMessageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
  333.  
  334. private Context context;
  335. private Image image;
  336. private Consersation consersation;
  337. private HashMap<String, Bitmap> bitmapAvata;
  338. private HashMap<String, DatabaseReference> bitmapAvataDB;
  339. private Bitmap bitmapAvataUser;
  340.  
  341. public ListMessageAdapter(Context context, Consersation consersation,
  342. HashMap<String, Bitmap> bitmapAvata, Bitmap bitmapAvataUser) {
  343. this.context = context;
  344. this.image = image;
  345. this.consersation = consersation;
  346. this.bitmapAvata = bitmapAvata;
  347. this.bitmapAvataUser = bitmapAvataUser;
  348. bitmapAvataDB = new HashMap<>();
  349. }
  350.  
  351. @Override
  352. public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
  353. if (viewType == ChatActivity.VIEW_TYPE_FRIEND_MESSAGE) {
  354. View view = LayoutInflater.from(context).inflate(R.layout.rc_item_message_friend, parent, false);
  355. return new ItemMessageFriendHolder(view);
  356. } else if (viewType == ChatActivity.VIEW_TYPE_USER_MESSAGE) {
  357. View view = LayoutInflater.from(context).inflate(R.layout.rc_item_message_user, parent, false);
  358. return new ItemMessageUserHolder(view);
  359. }
  360. return null;
  361. }
  362.  
  363. @Override
  364. public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
  365.  
  366. if (holder instanceof ItemMessageFriendHolder) {
  367. if (consersation.getListMessageData().get(position).text.length() == 169) {
  368. ((ItemMessageFriendHolder) holder).ivContent.setVisibility(View.VISIBLE);
  369. ((ItemMessageFriendHolder) holder).txtContent.setVisibility(View.GONE);
  370.  
  371. Glide.with(context)
  372. .load(consersation.getListMessageData()
  373. .get(position).text)
  374. .placeholder(R.mipmap.uploadfotoicon)
  375. .error(R.drawable.bt_shape_2)
  376. .into(((ItemMessageFriendHolder) holder).ivContent);
  377.  
  378. Log.d("TEST", "TEST PRE");
  379.  
  380. ((ItemMessageFriendHolder) holder).ivContent.setOnClickListener(new View.OnClickListener() {
  381. @Override
  382. public void onClick(View view) {
  383. Log.d("TEST", "TEST FRIEND" + holder.getAdapterPosition());
  384. Intent toFullScreen = new Intent(context, FullScreenImageActivity.class);
  385. toFullScreen.putExtra("imgkey", toFullScreen);
  386. context.startActivity(toFullScreen);
  387. }
  388. });
  389.  
  390. } else {
  391. ((ItemMessageFriendHolder) holder).ivContent.setVisibility(View.GONE);
  392. ((ItemMessageFriendHolder) holder).txtContent.setVisibility(View.VISIBLE);
  393.  
  394. try {
  395. String kunci = "kibo11" + consersation.getListMessageData().get(position).idReceiver;
  396. Log.d("kunci", "" + kunci);
  397. String pesandekrip = consersation.getListMessageData().get(position).text;
  398.  
  399. ((ItemMessageFriendHolder) holder).txtContent.setText(pesandekrip);
  400. } catch (Exception e) {
  401. e.printStackTrace();
  402. }
  403. }
  404. Bitmap currentAvata = bitmapAvata.get(consersation.getListMessageData().get(position).idSender);
  405. if (currentAvata != null) {
  406. ((ItemMessageFriendHolder) holder).avata.setImageBitmap(currentAvata);
  407. } else {
  408. final String id = consersation.getListMessageData().get(position).idSender;
  409. if (bitmapAvataDB.get(id) == null) {
  410. bitmapAvataDB.put(id, FirebaseDatabase.getInstance().getReference().child("user/" + id + "/avata"));
  411. bitmapAvataDB.get(id).addListenerForSingleValueEvent(new ValueEventListener() {
  412. @Override
  413. public void onDataChange(DataSnapshot dataSnapshot) {
  414. if (dataSnapshot.getValue() != null) {
  415. String avataStr = (String) dataSnapshot.getValue();
  416. if (!avataStr.equals(StaticConfig.STR_DEFAULT_BASE64)) {
  417. byte[] decodedString = Base64.decode(avataStr, Base64.DEFAULT);
  418. ChatActivity.bitmapAvataFriend.put(id, BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length));
  419. } else {
  420. ChatActivity.bitmapAvataFriend.put(id, BitmapFactory.decodeResource(context.getResources(), R.drawable.default_avata));
  421. }
  422. notifyDataSetChanged();
  423. }
  424. }
  425.  
  426. @Override
  427. public void onCancelled(DatabaseError databaseError) {
  428. }
  429. });
  430. }
  431. }
  432. } else if (holder instanceof ItemMessageUserHolder) {
  433. if (consersation.getListMessageData().get(position).text.length() == 169) {
  434. ((ItemMessageUserHolder) holder).ivContent.setVisibility(View.VISIBLE);
  435. ((ItemMessageUserHolder) holder).txtContent.setVisibility(View.GONE);
  436.  
  437. Glide.with(context)
  438. .load(consersation.getListMessageData()
  439. .get(position).text)
  440. .placeholder(R.mipmap.uploadfotoicon)
  441. .error(R.drawable.bt_shape_2)
  442. .into(((ItemMessageFriendHolder) holder).ivContent);
  443.  
  444. Log.d("TEST", "TEST PRE USERRR" + holder.getAdapterPosition());
  445.  
  446. ((ItemMessageUserHolder) holder).ivContent.setOnClickListener(new View.OnClickListener() {
  447. @Override
  448. public void onClick(View view) {
  449. Log.d("TEST", "TEST FRIEND");
  450. Intent toFullScreen = new Intent(context, FullScreenImageActivity.class);
  451. toFullScreen.putExtra("imgkey", toFullScreen);
  452. context.startActivity(toFullScreen);
  453. }
  454. });
  455.  
  456. } else {
  457. ((ItemMessageUserHolder) holder).ivContent.setVisibility(View.GONE);
  458. ((ItemMessageUserHolder) holder).txtContent.setVisibility(View.VISIBLE);
  459.  
  460. try {
  461. String kunci = "kibo11" + consersation.getListMessageData().get(position).idReceiver;
  462. Log.d("kunci", "" + kunci);
  463. String pesandekrip = consersation.getListMessageData().get(position).text;
  464.  
  465.  
  466. ((ItemMessageUserHolder) holder).txtContent.setText(pesandekrip);
  467. } catch (Exception e) {
  468. e.printStackTrace();
  469. }
  470. }
  471. if (bitmapAvataUser != null) {
  472. ((ItemMessageUserHolder) holder).avata.setImageBitmap(bitmapAvataUser);
  473. }
  474. }
  475. }
  476.  
  477. @Override
  478. public int getItemViewType(int position) {
  479. if (consersation.getListMessageData().get(position).idSender.equals(StaticConfig.UID)) {
  480. return ChatActivity.VIEW_TYPE_USER_MESSAGE;
  481. } else {
  482. return ChatActivity.VIEW_TYPE_FRIEND_MESSAGE;
  483. }
  484. }
  485.  
  486. @Override
  487. public int getItemCount() {
  488. return consersation.getListMessageData().size();
  489. }
  490. }
  491.  
  492. class ItemMessageUserHolder extends RecyclerView.ViewHolder {
  493. public TextView txtContent, pengirim2, waktu2;
  494. public ImageView ivContent;
  495. public CircleImageView avata;
  496.  
  497. public ItemMessageUserHolder(View itemView) {
  498. super(itemView);
  499. pengirim2 = itemView.findViewById(R.id.nameContentUser2);
  500. waktu2 = itemView.findViewById(R.id.waktuContentUser2);
  501. txtContent = itemView.findViewById(R.id.textContentUser);
  502. avata = itemView.findViewById(R.id.imageView2);
  503. ivContent = itemView.findViewById(R.id.ivImage);
  504. }
  505. }
  506.  
  507. class ItemMessageFriendHolder extends RecyclerView.ViewHolder {
  508. public TextView txtContent, pengirim1, waktu1;
  509. public CircleImageView avata;
  510. public ImageView ivContent;
  511.  
  512. public ItemMessageFriendHolder(View itemView) {
  513. super(itemView);
  514. pengirim1 = itemView.findViewById(R.id.nameChatFriend);
  515. waktu1 = itemView.findViewById(R.id.waktuChatFriend);
  516. txtContent = itemView.findViewById(R.id.textContentFriend);
  517. avata = itemView.findViewById(R.id.imageView3);
  518. ivContent = itemView.findViewById(R.id.ivImage);
  519. }
  520. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement