Advertisement
kitlolz012

photo handling 4

Sep 29th, 2023
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 20.09 KB | None | 0 0
  1. package com.example.gypsy;
  2.  
  3. import static android.content.ContentValues.TAG;
  4.  
  5. import android.Manifest;
  6. import android.app.Activity;
  7. import android.content.Intent;
  8. import android.content.pm.PackageManager;
  9. import android.net.Uri;
  10. import android.os.Bundle;
  11. import android.provider.MediaStore;
  12. import android.util.Log;
  13. import android.widget.Button;
  14. import android.widget.EditText;
  15. import android.widget.ImageView;
  16. import android.widget.LinearLayout;
  17.  
  18. import androidx.activity.result.ActivityResultLauncher;
  19. import androidx.activity.result.contract.ActivityResultContracts;
  20. import androidx.annotation.NonNull;
  21. import androidx.appcompat.app.AppCompatActivity;
  22. import androidx.core.app.ActivityCompat;
  23. import androidx.core.content.ContextCompat;
  24. import androidx.viewpager2.widget.ViewPager2;
  25.  
  26. import com.google.firebase.auth.FirebaseAuth;
  27. import com.google.firebase.auth.FirebaseUser;
  28. import com.google.firebase.database.DatabaseReference;
  29. import com.google.firebase.database.FirebaseDatabase;
  30. import com.google.firebase.database.Query;
  31. import com.google.firebase.database.ValueEventListener;
  32. import com.google.firebase.storage.FirebaseStorage;
  33. import com.google.firebase.storage.StorageReference;
  34. import com.google.firebase.storage.UploadTask;
  35.  
  36. import java.util.ArrayList;
  37. import java.util.HashMap;
  38. import java.util.List;
  39. import java.util.Map;
  40. import java.util.concurrent.atomic.AtomicBoolean;
  41. import java.util.concurrent.atomic.AtomicInteger;
  42.  
  43. public class EditRestoActivity extends AppCompatActivity {
  44.  
  45.     private FirebaseStorage storage;
  46.     private StorageReference storageReference;
  47.     private FirebaseDatabase database;
  48.     private DatabaseReference databaseReference;
  49.     private FirebaseAuth auth;
  50.     private FirebaseUser currentUser;
  51.     private List<Uri> imageUris = new ArrayList<>();
  52.     private ActivityResultLauncher<Intent> galleryLauncher;
  53.     private Button uploadButton;
  54.     private EditText restoNameEditText;
  55.     private EditText restoAddressEditText;
  56.     private EditText restoDescriptionEditText;
  57.     private EditText restoContactEditText;
  58.     private EditText restoEmailEditText;
  59.     private EditText cancellationPolicyEditText;
  60.     private EditText amenityEditText;
  61.     private Button postButton;
  62.     private String userId;
  63.     private RestoImageSliderAdapter adapter;
  64.     private ViewPager2 viewPager;
  65.     private LinearLayout dotsLayout;
  66.     private ImageView[] dots;
  67.  
  68.     private static final int REQUEST_PERMISSION_CODE = 123;
  69.  
  70.     @Override
  71.     protected void onCreate(Bundle savedInstanceState) {
  72.         super.onCreate(savedInstanceState);
  73.         setContentView(R.layout.activity_edit_resto);
  74.  
  75.         viewPager = findViewById(R.id.viewPager);
  76.         dotsLayout = findViewById(R.id.dotsLayout);
  77.         uploadButton = findViewById(R.id.uploadButton);
  78.         restoNameEditText = findViewById(R.id.restoNameEditText);
  79.         restoAddressEditText = findViewById(R.id.restoAddressEditText);
  80.         restoDescriptionEditText = findViewById(R.id.restoDescriptionEditText);
  81.         restoContactEditText = findViewById(R.id.restoContactEditText);
  82.         restoEmailEditText = findViewById(R.id.restoEmailEditText);
  83.         amenityEditText = findViewById(R.id.amenityEditText);
  84.         cancellationPolicyEditText = findViewById(R.id.cancellationPolicyEditText);
  85.         postButton = findViewById(R.id.postButton);
  86.  
  87.         auth = FirebaseAuth.getInstance();
  88.         currentUser = auth.getCurrentUser();
  89.         userId = currentUser.getUid();
  90.  
  91.         storage = FirebaseStorage.getInstance();
  92.         storageReference = storage.getReference();
  93.         database = FirebaseDatabase.getInstance();
  94.         databaseReference = database.getReference();
  95.  
  96.         adapter = new RestoImageSliderAdapter(this, imageUris, viewPager, dotsLayout);
  97.         viewPager.setAdapter(adapter);
  98.  
  99.         dotsLayout = findViewById(R.id.dotsLayout);
  100.         RestoImageSliderAdapter adapter = new RestoImageSliderAdapter(this, imageUris, viewPager, dotsLayout);
  101.         viewPager.setAdapter(adapter);
  102.  
  103.         viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
  104.             @Override
  105.             public void onPageSelected(int position) {
  106.                 super.onPageSelected(position);
  107.                 adapter.updateDotsIndicator(position);
  108.             }
  109.         });
  110.  
  111.         adapter.updateDotsIndicator(0);
  112.  
  113.         galleryLauncher = registerForActivityResult(
  114.                 new ActivityResultContracts.StartActivityForResult(),
  115.                 result -> {
  116.                     if (result.getResultCode() == Activity.RESULT_OK) {
  117.                         Intent data = result.getData();
  118.                         if (data != null && data.getData() != null) {
  119.                             Uri imageUri = data.getData();
  120.                             imageUris.add(imageUri); // Add the selected URI to the list
  121.                             adapter.notifyDataSetChanged();
  122.                         }
  123.                     }
  124.                 }
  125.         );
  126.  
  127.         uploadButton.setOnClickListener(v -> {
  128.             // Check permissions before opening the gallery
  129.             checkPermissions();
  130.         });
  131.  
  132.         postButton.setOnClickListener(v -> {
  133.             String restoName = restoNameEditText.getText().toString();
  134.             String restoAddress = restoAddressEditText.getText().toString();
  135.             String restoDescription = restoDescriptionEditText.getText().toString();
  136.             String restoContact = restoContactEditText.getText().toString();
  137.             String restoEmail = restoEmailEditText.getText().toString();
  138.             String cancellationPolicy = cancellationPolicyEditText.getText().toString();
  139.             String amenitiesRestro = amenityEditText.getText().toString();
  140.  
  141.             checkIfExists(userId, restoName, restoAddress, restoDescription, restoContact, restoEmail, cancellationPolicy, imageUris, amenitiesRestro);
  142.  
  143.             Intent intent = new Intent(this, MainActivity3.class);
  144.             intent.putExtra("frag", "RestoEditFragment");
  145.             startActivity(intent);
  146.         });
  147.  
  148.         retrieve(userId);
  149.  
  150.         dots(0);
  151.         viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
  152.             @Override
  153.             public void onPageSelected(int position) {
  154.                 super.onPageSelected(position);
  155.                 dots(position);
  156.             }
  157.         });
  158.         Log.d(TAG, "Image upload is triggered.");
  159.     }
  160.  
  161.  
  162.  private void openGallery() {
  163.         Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
  164.         galleryLauncher.launch(galleryIntent);
  165.     }
  166.  
  167.     private void checkPermissions() {
  168.         if (ContextCompat.checkSelfPermission(this,
  169.                 Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
  170.             ActivityCompat.requestPermissions(this,
  171.                     new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
  172.                     REQUEST_PERMISSION_CODE);
  173.         } else {
  174.             openGallery();
  175.         }
  176.     }
  177.    @Override
  178.     public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
  179.         if (requestCode == REQUEST_PERMISSION_CODE) {
  180.             if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  181.                 openGallery();
  182.             } else {
  183.                 // Handle permission denied
  184.                 showErrorDialog("Permission denied. You cannot select images without permission.");
  185.             }
  186.         }
  187.     }
  188.  
  189.     galleryLauncher = registerForActivityResult(
  190.         new ActivityResultContracts.StartActivityForResult(),
  191.         result -> {
  192.             if (result.getResultCode() == Activity.RESULT_OK) {
  193.                 Intent data = result.getData();
  194.                 if (data != null && data.getData() != null) {
  195.                     Uri imageUri = data.getData();
  196.                     imageUris.add(imageUri); // Add the selected URI to the list
  197.                     adapter.notifyDataSetChanged();
  198.                 } else {
  199.                     // Handle the case where imageUri is null
  200.                     showErrorDialog("Unable to select the image. Please try again.");
  201.                 }
  202.             } else {
  203.                 // Handle other unexpected result codes or errors
  204.                 showErrorDialog("An unexpected error occurred while selecting the image.");
  205.             }
  206.         }
  207.     );
  208.  
  209.     // ... (existing code)
  210.  
  211.     private void showErrorDialog(String errorMessage) {
  212.         // You can display an error dialog or toast message to inform the user about the issue.
  213.         // For example, show a Toast message:
  214.         Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
  215.     }
  216. }
  217.  
  218.   private void checkIfExists(String userId, String restoName, String restoAddress, String restoDescription, String restoContact,
  219.                                String restoEmail, String cancellationPolicy, List<Uri> imageUris, String amenitiesResto) {
  220.         DatabaseReference restoRef = databaseReference.child("restaurants");
  221.         Query query = restoRef.orderByChild("user_id").equalTo(userId);
  222.         query.addListenerForSingleValueEvent(new ValueEventListener() {
  223.             @Override
  224.             public void onDataChange(@NonNull com.google.firebase.database.DataSnapshot dataSnapshot) {
  225.                 if (dataSnapshot.exists()) {
  226.                     String existingRestoId = dataSnapshot.getChildren().iterator().next().getKey();
  227.                     update(restoName, restoAddress, restoDescription, imageUris, restoContact, restoEmail, cancellationPolicy, existingRestoId, amenitiesResto);
  228.                     adapter.setUris(imageUris);
  229.                     adapter.notifyDataSetChanged();
  230.                     Log.d(TAG, "Resto exists for user: " + userId);
  231.                 } else {
  232.                     create(userId, restoName, restoAddress, restoDescription, restoContact, restoEmail, cancellationPolicy, imageUris, amenitiesResto);
  233.                     adapter.setUris(imageUris);
  234.                     adapter.notifyDataSetChanged();
  235.                     Log.d(TAG, "Resto does not exist for user: " + userId);
  236.                 }
  237.             }
  238.             @Override
  239.             public void onCancelled(@NonNull DatabaseError databaseError) {
  240.                 Log.e("check", "error" + databaseError.getMessage());
  241.             }
  242.         });
  243.     }
  244.  
  245.     private void create(String userId, String restoName, String restoAddress, String restoDescription, String restoContact,
  246.                         String restoEmail, String cancellationPolicy, List<Uri> imageUris, String amenitiesResto) {
  247.  
  248.         DatabaseReference restosRef = databaseReference.child("restaurants");
  249.         DatabaseReference restoRef = restosRef.push();
  250.         String restoId = restoRef.getKey();
  251.  
  252.         List<String> imageUrls = new ArrayList<>();
  253.         AtomicInteger uploadCount = new AtomicInteger(0);
  254.         AtomicBoolean hasUploadFailed = new AtomicBoolean(false);
  255.  
  256.         List<UploadTask> uploadTasks = new ArrayList<>();
  257.  
  258.         for (int i = 0; i < imageUris.size(); i++) {
  259.             final int finalIndex = i;
  260.             Uri imageUri = imageUris.get(i);
  261.             StorageReference imageRef = storageReference.child("restaurant_images/" + restoId + "/image" + (i + 1));
  262.             Log.d(TAG, "Image Storage Reference: " + imageRef.toString());
  263.             UploadTask uploadTask = imageRef.putFile(imageUri);
  264.  
  265.             uploadTask.addOnFailureListener(new MyFailureListener());
  266.             uploadTasks.add(uploadTask);
  267.  
  268.             uploadTask.addOnSuccessListener(taskSnapshot -> {
  269.                 imageRef.getDownloadUrl().addOnSuccessListener(downloadUri -> {
  270.                     String imageUrl = downloadUri.toString();
  271.                     imageUrls.add(imageUrl);
  272.                     if (uploadCount.incrementAndGet() == imageUris.size()) {
  273.                         if (!hasUploadFailed.get()) {
  274.                             save(restoId, imageUrls, restoName, restoAddress, restoDescription, restoContact, restoEmail, cancellationPolicy, amenitiesRestro);
  275.  
  276.                             adapter.setUris(imageUris);
  277.                             adapter.notifyDataSetChanged();
  278.                         } else {
  279.                             Log.e(TAG, "Image upload failed.");
  280.                         }
  281.                     }
  282.                 });
  283.             }).addOnFailureListener(e -> {
  284.                 Log.e(TAG, "Failed to upload image #" + (finalIndex + 1) + ": " + e.getMessage());
  285.                 hasUploadFailed.set(true);
  286.  
  287.                 for (int j = finalIndex + 1; j < imageUris.size(); j++) {
  288.                     UploadTask remainingUploadTask = uploadTasks.get(j);
  289.                     if (remainingUploadTask != null && !remainingUploadTask.isComplete()) {
  290.                         remainingUploadTask.cancel();
  291.                     }
  292.                 }
  293.             });
  294.         }
  295.     }
  296.  
  297.     private void update(String restoName, String restoAddress, String restoDescription, List<Uri> imageUris, String restoContact, String restoEmail, String cancellationPolicy, String restoId, String amenitiesResto) {
  298.  
  299.         DatabaseReference restosRef = databaseReference.child("restaurants");
  300.         Query query = restosRef.orderByChild("user_id").equalTo(userId);
  301.  
  302.         query.addListenerForSingleValueEvent(new ValueEventListener() {
  303.             @Override
  304.             public void onDataChange(@NonNull com.google.firebase.database.DataSnapshot dataSnapshot) {
  305.                 if (dataSnapshot.exists()) {
  306.                     for (com.google.firebase.database.DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
  307.                         String restoId = childSnapshot.getKey();
  308.  
  309.                         DatabaseReference restoRef = restosRef.child(restoId);
  310.                         restoRef.child("name").setValue(restoName);
  311.                         restoRef.child("address").setValue(restoAddress);
  312.                         restoRef.child("description").setValue(restoDescription);
  313.                         restoRef.child("contact").setValue(restoContact);
  314.                         restoRef.child("email").setValue(restoEmail);
  315.                         restoRef.child("cancellationPolicy").setValue(cancellationPolicy);
  316.                         restoRef.child("amenities").setValue(amenitiesResto);
  317.  
  318.                         if (!imageUris.isEmpty()) {
  319.                             List<String> imageUrls = new ArrayList<>();
  320.  
  321.                             for (int i = 0; i < imageUris.size(); i++) {
  322.                                 Uri imageUri = imageUris.get(i);
  323.                                 StorageReference imageRef = storageReference.child("restaurant_images/" + restoId + "/image" + (i + 1));
  324.                                 UploadTask uploadTask = imageRef.putFile(imageUri);
  325.  
  326.                                 uploadTask.addOnFailureListener(new MyFailureListener());
  327.                                 uploadTask.addOnSuccessListener(taskSnapshot -> imageRef.getDownloadUrl().addOnSuccessListener(downloadUri -> {
  328.                                     String imageUrl = downloadUri.toString();
  329.                                     imageUrls.add(imageUrl);
  330.                                 })).addOnFailureListener(e -> {
  331.                                     Log.e("image upload", "error");
  332.                                 });
  333.                             }
  334.                         }
  335.                     }
  336.                 }
  337.             }
  338.  
  339.             @Override
  340.             public void onCancelled(@NonNull DatabaseError databaseError) {
  341.                 Log.e("update", "error" + databaseError.getMessage());
  342.             }
  343.         });
  344.     }
  345.  
  346.     private void save(String restoId, List<String> imageUrls, String restoName, String restoAddress, String restoDescription, String restoContact, String restoEmail, String cancellationPolicy, String amenitiesRestro) {
  347.  
  348.         DatabaseReference restosRef = databaseReference.child("restaurants");
  349.         DatabaseReference restoRef = restosRef.child(restoId);
  350.  
  351.         restoRef.child("name").setValue(restoName);
  352.         restoRef.child("address").setValue(restoAddress);
  353.         restoRef.child("description").setValue(restoDescription);
  354.         restoRef.child("contact").setValue(restoContact);
  355.         restoRef.child("email").setValue(restoEmail);
  356.         restoRef.child("cancellationPolicy").setValue(cancellationPolicy);
  357.         restoRef.child("user_id").setValue(userId);
  358.         restoRef.child("amenities").setValue(amenitiesRestro);
  359.  
  360.         Map<String, Object> imagesMap = new HashMap<>();
  361.         for (int i = 0; i < imageUrls.size(); i++) {
  362.             imagesMap.put("image" + (i + 1), imageUrls.get(i));
  363.         }
  364.         restoRef.child("images").setValue(imagesMap);
  365.     }
  366.  
  367.     private void retrieve(String userId) {
  368.         DatabaseReference restoRef = databaseReference.child("restaurants");
  369.         Query query = restoRef.orderByChild("user_id").equalTo(userId);
  370.         query.addListenerForSingleValueEvent(new ValueEventListener() {
  371.             @Override
  372.             public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
  373.                 if (dataSnapshot.exists()) {
  374.                     DataSnapshot restoSnapshot = dataSnapshot.getChildren().iterator().next();
  375.  
  376.                     String title = restoSnapshot.child("name").getValue(String.class);
  377.                     String restoAddress = restoSnapshot.child("address").getValue(String.class);
  378.                     String description = restoSnapshot.child("description").getValue(String.class);
  379.                     String restoContact = restoSnapshot.child("contact").getValue(String.class);
  380.                     String restoEmail = restoSnapshot.child("email").getValue(String.class);
  381.                     String cancellationPolicy = restoSnapshot.child("cancellationPolicy").getValue(String.class);
  382.                     String amenitiesRestro = restoSnapshot.child("amenities").getValue(String.class);
  383.  
  384.                     List<String> imageUrls = new ArrayList<>();
  385.                     DataSnapshot imagesSnapshot = restoSnapshot.child("images");
  386.                     for (DataSnapshot imageSnapshot : imagesSnapshot.getChildren()) {
  387.                         String imageUrl = imageSnapshot.getValue(String.class);
  388.                         imageUrls.add(imageUrl);
  389.                     }
  390.  
  391.                     restoNameEditText.setText(title);
  392.                     restoDescriptionEditText.setText(description);
  393.                     restoAddressEditText.setText(restoAddress);
  394.                     restoContactEditText.setText(restoContact);
  395.                     restoEmailEditText.setText(restoEmail);
  396.                     cancellationPolicyEditText.setText(cancellationPolicy);
  397.                     amenityEditText.setText(amenitiesRestro);
  398.                     imageUris.clear();
  399.  
  400.                     imageUris.clear();
  401.                     for (String imageUrl : imageUrls) {
  402.                         imageUris.add(Uri.parse(imageUrl));
  403.                     }
  404.  
  405.                     adapter.setUris(imageUris);
  406.                     adapter.notifyDataSetChanged();
  407.                 }
  408.             }
  409.  
  410.             @Override
  411.             public void onCancelled(@NonNull DatabaseError databaseError) {
  412.                 Log.e("retrieve", "error" + databaseError.getMessage());
  413.             }
  414.         });
  415.     }
  416.  
  417.     private void dots(int position) {
  418.         dots = new ImageView[imageUris.size()];
  419.         dotsLayout.removeAllViews();
  420.  
  421.         for (int i = 0; i < dots.length; i++) {
  422.             dots[i] = new ImageView(this);
  423.             dots[i].setImageDrawable(ContextCompat.getDrawable(this, R.drawable.dots_unselected));
  424.  
  425.             LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
  426.                     LinearLayout.LayoutParams.WRAP_CONTENT,
  427.                     LinearLayout.LayoutParams.WRAP_CONTENT
  428.             );
  429.  
  430.             params.setMargins(8, 0, 8, 0);
  431.             dotsLayout.addView(dots[i], params);
  432.         }
  433.         if (dots.length > 0) {
  434.             dots[position].setImageDrawable(ContextCompat.getDrawable(this, R.drawable.dots_selected));
  435.         }
  436.     }
  437. }
  438.  
Tags: Android
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement