Advertisement
Guest User

Untitled

a guest
Apr 24th, 2018
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.49 KB | None | 0 0
  1. package com.example.filip.unibook;
  2.  
  3. import android.content.Context;
  4. import android.content.DialogInterface;
  5. import android.content.Intent;
  6. import android.content.pm.PackageManager;
  7. import android.graphics.Bitmap;
  8. import android.graphics.BitmapFactory;
  9. import android.net.Uri;
  10. import android.support.annotation.NonNull;
  11. import android.support.v4.app.ActivityCompat;
  12. import android.support.v4.content.ContextCompat;
  13. import android.support.v7.app.AlertDialog;
  14. import android.support.v7.app.AppCompatActivity;
  15. import android.os.Bundle;
  16. import android.util.Log;
  17. import android.view.View;
  18. import android.widget.ImageView;
  19. import android.widget.ProgressBar;
  20. import android.widget.TextView;
  21. import android.widget.Button;
  22. import android.widget.Toast;
  23. import android.Manifest;
  24.  
  25. import com.google.android.gms.tasks.OnCompleteListener;
  26. import com.google.android.gms.tasks.OnFailureListener;
  27. import com.google.android.gms.tasks.OnSuccessListener;
  28. import com.google.android.gms.tasks.Task;
  29. import com.google.firebase.auth.FirebaseAuth;
  30. import com.google.firebase.auth.FirebaseUser;
  31. import com.google.firebase.firestore.CollectionReference;
  32. import com.google.firebase.firestore.DocumentReference;
  33. import com.google.firebase.firestore.DocumentSnapshot;
  34. import com.google.firebase.firestore.EventListener;
  35. import com.google.firebase.firestore.FirebaseFirestore;
  36. import com.google.firebase.firestore.FirebaseFirestoreException;
  37. import com.google.firebase.firestore.Query;
  38. import com.google.firebase.firestore.QuerySnapshot;
  39. import com.google.firebase.firestore.WriteBatch;
  40. import com.google.firebase.storage.FirebaseStorage;
  41. import com.google.firebase.storage.StorageException;
  42. import com.google.firebase.storage.StorageReference;
  43.  
  44. import org.w3c.dom.Document;
  45.  
  46. import java.lang.ref.Reference;
  47. import java.util.Collection;
  48. import java.util.HashMap;
  49. import java.util.List;
  50. import java.util.Map;
  51.  
  52. public class ChosenAdForSale extends AppCompatActivity {
  53.  
  54. public static final String TAG = "message";
  55. TextView title, pris, info, program, kurs, seller, chosenAdId;
  56. ImageView pic;
  57. User user;
  58. Button favoriteBtn, btnCallAd, btnReportAd;
  59. ProgressBar progressBar;
  60. Context context;
  61. String sellerId, sellerPhone, adId, id, sellerName, imageId;
  62. FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
  63. FirebaseAuth mAuth = FirebaseAuth.getInstance();
  64. FirebaseStorage storage = FirebaseStorage.getInstance();
  65. FirebaseUser loggenIn = mAuth.getCurrentUser();
  66. private int CALL_PERMISSION_CODE = 1;
  67.  
  68. @Override
  69. protected void onCreate(Bundle savedInstanceState) {
  70. super.onCreate(savedInstanceState);
  71. setContentView(R.layout.activity_chosen_ad_for_sale);
  72.  
  73. title = findViewById(R.id.chosenAdTitle);
  74. pris = findViewById(R.id.chosenAdPrice);
  75. info = findViewById(R.id.chosenAdDescription);
  76. program = findViewById(R.id.chosenAdProgramName);
  77. kurs = findViewById(R.id.chosenAdCourseName);
  78. pic = findViewById(R.id.chosenAdImg);
  79. seller = findViewById(R.id.chosenAdSellerName);
  80. favoriteBtn = findViewById(R.id.btnAddToFavorites);
  81. btnCallAd = findViewById(R.id.btnChosenAdCall);
  82. btnReportAd = findViewById(R.id.btnReportAd);
  83. progressBar = findViewById(R.id.progressBarChosenAd);
  84.  
  85. progressBar.setVisibility(View.VISIBLE);
  86.  
  87. Intent intent = getIntent();
  88. id = intent.getStringExtra("id");
  89.  
  90. DocumentReference docRef = rootRef.collection("Ads").document(id);
  91.  
  92. docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
  93. @Override
  94. public void onComplete(@NonNull Task<DocumentSnapshot> task) {
  95. if (task.isSuccessful()) {
  96. DocumentSnapshot document = task.getResult();
  97. if (document != null && document.exists()) {
  98.  
  99. title.setText(document.getString("title"));
  100. pris.setText(document.getString("price") + " :-");
  101. info.setText(document.getString("info"));
  102. kurs.setText(document.getString("course"));
  103. program.setText(document.getString("program"));
  104. sellerId = document.getString("sellerId");
  105. adId = document.getId();
  106. imageId = document.getString("imageId");
  107.  
  108. setImage(imageId);
  109.  
  110. checkFavourites(adId);
  111.  
  112. getSeller(sellerId);
  113.  
  114. progressBar.setVisibility(View.INVISIBLE);
  115. Log.d(TAG, "DocumentSnapshot data: " + document.getData());
  116. } else {
  117. Log.d(TAG, "No such document");
  118. }
  119. } else {
  120. Log.d(TAG, "get failed with ", task.getException());
  121. }
  122. }
  123. });
  124.  
  125. favoriteBtn.setOnClickListener(new View.OnClickListener() {
  126. @Override
  127. public void onClick(View v) {
  128.  
  129. CollectionReference favouritesRef = rootRef.collection("Favourites");
  130.  
  131. if(favoriteBtn.getText().toString().toLowerCase().equals("lägg till favorit")){
  132.  
  133. Map<String, Object> map = new HashMap<>();
  134. map.put("userId", loggenIn.getUid().toString());
  135. map.put("adId", adId);
  136.  
  137. favouritesRef.document()
  138. .set(map)
  139. .addOnSuccessListener(new OnSuccessListener<Void>() {
  140. @Override
  141. public void onSuccess(Void aVoid) {
  142. Toast.makeText(ChosenAdForSale.this, "Favorit tillagd",
  143. Toast.LENGTH_LONG).show();
  144.  
  145. favoriteBtn.setText("Ta bort favorit");
  146. Log.d(TAG, "DocumentSnapshot successfully written!");
  147. }
  148. })
  149. .addOnFailureListener(new OnFailureListener() {
  150. @Override
  151. public void onFailure(@NonNull Exception e) {
  152. Log.w(TAG, "Error writing document", e);
  153. }
  154. });
  155. }else{
  156.  
  157. removeFavourite(adId);
  158. }
  159. }
  160. });
  161.  
  162. btnReportAd.setOnClickListener(new View.OnClickListener() {
  163. @Override
  164. public void onClick(View v) {
  165. Intent intent = new Intent(ChosenAdForSale.this, ReportAd.class);
  166. intent.putExtra("id", adId);
  167. startActivity(intent);
  168. }
  169. });
  170.  
  171.  
  172. btnCallAd.setOnClickListener(new View.OnClickListener() {
  173. @Override
  174. public void onClick(View v) {
  175. if(ContextCompat.checkSelfPermission(ChosenAdForSale.this,
  176. Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
  177. //Toast.makeText(ChosenAdForSale.this, "You have already granted this permission", Toast.LENGTH_SHORT).show();
  178.  
  179. Intent callIntent = new Intent(Intent.ACTION_CALL);
  180. callIntent.setData(Uri.parse("tel:" + sellerPhone));
  181. startActivity(callIntent);
  182. }else{
  183. requestCallPermission();
  184. }
  185. }
  186. });
  187. }
  188.  
  189. public void setImage(String imageId){
  190.  
  191. StorageReference storageRef = storage.getReferenceFromUrl(imageId);
  192.  
  193. /*
  194. FirebaseStorage storage = FirebaseStorage.getInstance();
  195. StorageReference storageRef = storage.getReference().child("images/152a1281-2366-4f3a-a50e-7d7c1e7019b4");
  196. */
  197.  
  198. final long ONE_MEGABYTE = 1024 * 1024;
  199.  
  200. storageRef.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
  201. @Override
  202. public void onSuccess(byte[] bytes) {
  203. // Data for "images/island.jpg" is returns, use this as needed
  204. Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
  205. pic.setImageBitmap(bitmap);
  206. }
  207. }).addOnFailureListener(new OnFailureListener() {
  208. @Override
  209. public void onFailure(@NonNull Exception exception) {
  210. // Handle any errors
  211. }
  212. });
  213. }
  214.  
  215. public void getSeller(String sellerId){
  216.  
  217. DocumentReference userRef = rootRef.collection("Users").document(sellerId);
  218. userRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
  219. @Override
  220. public void onComplete(@NonNull Task<DocumentSnapshot> task) {
  221. if (task.isSuccessful()) {
  222. DocumentSnapshot document = task.getResult();
  223. if (document != null && document.exists()) {
  224.  
  225. sellerPhone = document.getString("phone");
  226. sellerName = document.getString("name") + " " + document.getString("surname");
  227. seller.setText(sellerName);
  228.  
  229. Log.d(TAG, "DocumentSnapshot data: " + document.getData());
  230. } else {
  231. Log.d(TAG, "No such document");
  232. }
  233. } else {
  234. Log.d(TAG, "get failed with ", task.getException());
  235. }
  236. }
  237. });
  238. }
  239.  
  240. public void checkFavourites(final String adId){
  241.  
  242. CollectionReference favouritesRef = rootRef.collection("Favourites");
  243. Query query = favouritesRef.whereEqualTo("userId", loggenIn.getUid().toString());
  244. query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
  245. @Override
  246. public void onComplete(@NonNull Task<QuerySnapshot> task) {
  247. if (task.isSuccessful()) {
  248.  
  249. List<DocumentSnapshot> list = task.getResult().getDocuments();
  250. for (DocumentSnapshot document : list) {
  251.  
  252. if (document.getString("adId").equals(adId)) {
  253. favoriteBtn.setText("Ta bort favorit");
  254. }
  255. }
  256. }else{
  257. Log.d(TAG, "Error getting documents: ", task.getException());
  258. }
  259. }
  260. });
  261. }
  262.  
  263. public void removeFavourite(final String adId){
  264.  
  265. final CollectionReference favouritesRef = rootRef.collection("Favourites");
  266. Query query = favouritesRef.whereEqualTo("userId", loggenIn.getUid().toString());
  267. query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
  268. @Override
  269. public void onComplete(@NonNull Task<QuerySnapshot> task) {
  270. if (task.isSuccessful()) {
  271.  
  272. List<DocumentSnapshot> list = task.getResult().getDocuments();
  273. for (DocumentSnapshot document : list) {
  274.  
  275. if (document.getString("adId").equals(adId)) {
  276. favouritesRef.document(document.getId()).delete();
  277. Toast.makeText(ChosenAdForSale.this, "Favorit borttagen",
  278. Toast.LENGTH_LONG).show();
  279. favoriteBtn.setText("Lägg till favorit");
  280. }
  281. }
  282. }else{
  283. Log.d(TAG, "Error getting documents: ", task.getException());
  284. }
  285. }
  286. });
  287. }
  288.  
  289. private void requestCallPermission(){
  290. if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CALL_PHONE)) {
  291.  
  292. new AlertDialog.Builder(this)
  293. .setTitle("Permission needed")
  294. .setMessage("This permission is needed to make calls from application")
  295. .setPositiveButton("ok", new DialogInterface.OnClickListener() {
  296. @Override
  297. public void onClick(DialogInterface dialog, int which) {
  298. ActivityCompat.requestPermissions(ChosenAdForSale.this, new String[]{Manifest.permission.CALL_PHONE}, CALL_PERMISSION_CODE);
  299. }
  300. })
  301. .setNegativeButton("cancel", new DialogInterface.OnClickListener() {
  302. @Override
  303. public void onClick(DialogInterface dialog, int which) {
  304. dialog.dismiss();
  305. }
  306. })
  307. .create().show();
  308. }else {
  309. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, CALL_PERMISSION_CODE);
  310. }
  311. }
  312.  
  313. @Override
  314. public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
  315. if(requestCode == CALL_PERMISSION_CODE) {
  316. if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  317. Toast.makeText(this, "Permission GRANTED", Toast.LENGTH_SHORT).show();
  318. }else {
  319. Toast.makeText(this, "Permission DENIED", Toast.LENGTH_SHORT).show();
  320. }
  321. }
  322. }
  323. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement