Advertisement
RakaArdiansyah

Glide(image bisa)

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