Advertisement
rachmadi

ReportActivity

Sep 16th, 2017
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 23.02 KB | None | 0 0
  1. package info.rekayasa.polisipro;
  2.  
  3. import android.Manifest;
  4. import android.app.ProgressDialog;
  5. import android.content.Context;
  6. import android.content.Intent;
  7. import android.content.IntentSender;
  8. import android.content.pm.ActivityInfo;
  9. import android.content.pm.PackageManager;
  10. import android.graphics.Bitmap;
  11. import android.graphics.BitmapFactory;
  12. import android.graphics.Color;
  13. import android.location.Location;
  14. import android.location.LocationManager;
  15. import android.net.Uri;
  16. import android.os.Bundle;
  17. import android.os.Environment;
  18. import android.provider.MediaStore;
  19. import android.support.annotation.NonNull;
  20. import android.support.annotation.Nullable;
  21. import android.support.design.widget.FloatingActionButton;
  22. import android.support.v4.app.ActivityCompat;
  23. import android.support.v4.content.ContextCompat;
  24. import android.support.v7.app.AppCompatActivity;
  25. import android.support.v7.widget.Toolbar;
  26. import android.text.TextUtils;
  27. import android.util.Log;
  28. import android.view.View;
  29. import android.widget.Button;
  30. import android.widget.EditText;
  31. import android.widget.ImageView;
  32. import android.widget.TextView;
  33. import android.widget.Toast;
  34.  
  35. import com.google.android.gms.common.ConnectionResult;
  36. import com.google.android.gms.common.api.GoogleApiClient;
  37. import com.google.android.gms.common.api.PendingResult;
  38. import com.google.android.gms.common.api.ResultCallback;
  39. import com.google.android.gms.common.api.Status;
  40. import com.google.android.gms.location.LocationListener;
  41. import com.google.android.gms.location.LocationRequest;
  42. import com.google.android.gms.location.LocationServices;
  43. import com.google.android.gms.location.LocationSettingsRequest;
  44. import com.google.android.gms.location.LocationSettingsResult;
  45. import com.google.android.gms.location.LocationSettingsStatusCodes;
  46. import com.google.firebase.auth.FirebaseAuth;
  47. import com.google.firebase.database.DataSnapshot;
  48. import com.google.firebase.database.DatabaseError;
  49. import com.google.firebase.database.DatabaseReference;
  50. import com.google.firebase.database.FirebaseDatabase;
  51. import com.google.firebase.database.Query;
  52. import com.google.firebase.database.ServerValue;
  53. import com.google.firebase.database.ValueEventListener;
  54. import com.google.firebase.storage.FirebaseStorage;
  55. import com.google.firebase.storage.OnProgressListener;
  56. import com.google.firebase.storage.StorageReference;
  57. import com.google.firebase.storage.UploadTask;
  58.  
  59. import org.json.JSONArray;
  60.  
  61. import java.io.ByteArrayOutputStream;
  62. import java.io.File;
  63. import java.io.FileOutputStream;
  64. import java.io.IOException;
  65. import java.text.SimpleDateFormat;
  66. import java.util.Date;
  67. import java.util.Iterator;
  68. import java.util.Locale;
  69.  
  70. import static com.google.android.gms.internal.zzax.getKey;
  71.  
  72.  
  73. public class ReportActivity extends AppCompatActivity implements
  74.         GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
  75.         LocationListener, ResultCallback<LocationSettingsResult> {
  76.  
  77.     TextView tvAccuracy, tvLocation, tvAccuracyStatus;
  78.     Toolbar toolbar;
  79.     FloatingActionButton fab;
  80.     Button btnSend;
  81.     ImageView ivPhoto;
  82.     EditText etReport;
  83.  
  84.     Uri fileUri;
  85.  
  86.     JSONArray recipients;
  87.  
  88.     double latitude, longitude;
  89.  
  90.     private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
  91.     public static final int MEDIA_TYPE_IMAGE = 1;
  92.     private static final String IMAGE_DIRECTORY_NAME = "KlikPolisi";
  93.  
  94.     String fileName, userId, reportContent, category;
  95.     private static String fullName;
  96.     long timestamp;
  97.  
  98.     private StorageReference mStorage;
  99.     private DatabaseReference mDatabase, mUserRef, mReportRef, mUserToken;
  100.     private FirebaseAuth mAuth;
  101.  
  102.     ProgressDialog mProgressDialog;
  103.  
  104.     Location mLastLocation;
  105.     private GoogleApiClient mGoogleApiClient;
  106.     private LocationRequest mLocationRequest;
  107.     public static int LOCATION_REQUEST = 300;
  108.     int REQUEST_CHECK_SETTINGS = 200;
  109.     LocationManager mLocationManager;
  110.  
  111.     public String lat, lng, accuracy;
  112.     float acc;
  113.  
  114.     @Override
  115.     protected void onCreate(Bundle savedInstanceState) {
  116.         super.onCreate(savedInstanceState);
  117.  
  118.         setContentView(R.layout.activity_report);
  119.         this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
  120.  
  121.         Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
  122.         setSupportActionBar(toolbar);
  123.         Bundle extras = getIntent().getExtras();
  124.         category = extras.getString("category");
  125.         setTitle(category);
  126.         System.out.println("Category: " + category);
  127.  
  128.         mProgressDialog = new ProgressDialog(this);
  129.  
  130. //        mStorage = FirebaseStorage.getInstance().getReference();
  131.         mDatabase = FirebaseDatabase.getInstance().getReference();
  132.         mAuth = FirebaseAuth.getInstance();
  133.  
  134.         fab = (FloatingActionButton) findViewById(R.id.fab);
  135.         ivPhoto = (ImageView) findViewById(R.id.ivPhoto);
  136.         etReport = (EditText) findViewById(R.id.etReport);
  137.         tvLocation = (TextView) findViewById(R.id.tvLocation);
  138.         tvAccuracy = (TextView) findViewById(R.id.tvAccuracy);
  139.         tvAccuracyStatus = (TextView) findViewById(R.id.tvAccuracyStatus);
  140.  
  141.         fullName = getFullName();
  142. //        getUserToken();
  143.  
  144.         btnSend = (Button) findViewById(R.id.btnSend);
  145.         btnSend.setOnClickListener(new View.OnClickListener() {
  146.             @Override
  147.             public void onClick(View view) {
  148.                 mProgressDialog.setMessage("Mengirim laporan...");
  149.                 mProgressDialog.show();
  150.                 saveReport();
  151.             }
  152.         });
  153.  
  154.         if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
  155.             fab.setEnabled(false);
  156.             ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 0);
  157.         } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
  158.             fab.setEnabled(false);
  159.             ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
  160.         } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
  161.             fab.setEnabled(false);
  162.             ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 2);
  163.         }
  164.  
  165.  
  166.         if (category.equals("Kemacetan")) {
  167.             fab.setBackgroundTintList(getResources().getColorStateList(R.color.orange));
  168.         } else if (category.equals("Kecelakaan")) {
  169.             fab.setBackgroundTintList(getResources().getColorStateList(R.color.red));
  170.         } else if (category.equals("Tindak Kriminal")) {
  171.             fab.setBackgroundTintList(getResources().getColorStateList(R.color.green));
  172.         } else if (category.equals("Bencana")) {
  173.             fab.setBackgroundTintList(getResources().getColorStateList(R.color.blue));
  174.         }
  175.  
  176.         fab.setOnClickListener(new View.OnClickListener() {
  177.             @Override
  178.             public void onClick(View view) {
  179.                 takePicture();
  180.             }
  181.         });
  182.  
  183.         buildGoogleApiClient();
  184.     }
  185.  
  186.     private void saveReport() {
  187.         reportContent = etReport.getText().toString();
  188.         if (TextUtils.isEmpty(reportContent)) {
  189.             etReport.setError("Harus diisi!");
  190.         }
  191.  
  192.         mReportRef = mDatabase.child("reports");
  193.         final String reportKey = mReportRef.push().getKey();
  194.         if (reportKey.equals("")){
  195.             return;
  196.         }
  197.         System.out.println("fileName: " + fileName);
  198.         System.out.println("fileUri.getLastPathSegment: " + fileUri.getLastPathSegment());
  199.         StorageReference storageRef = FirebaseStorage.getInstance().getReference().child("Photos/" +
  200.                 fileUri.getLastPathSegment());
  201.         storageRef.child("Photos");
  202.         Uri file = Uri.fromFile(new File(fileUri.getPath()));
  203.         UploadTask uploadTask = storageRef.putFile(file);
  204.         uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
  205.             @Override
  206.             public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
  207.                 System.out.println("Progress: " + (taskSnapshot.getBytesTransferred()));
  208.                 System.out.println("Total: " + taskSnapshot.getTotalByteCount());
  209.                 if (taskSnapshot.getBytesTransferred() == taskSnapshot.getTotalByteCount()){
  210.                     System.out.println("Upload complete!");
  211.  
  212.                     mReportRef.child(reportKey).child("timestamp").setValue(ServerValue.TIMESTAMP);
  213.                     Query query = mReportRef.child(reportKey).child("timestamp");
  214.                     query.addListenerForSingleValueEvent(new ValueEventListener() {
  215.                         @Override
  216.                         public void onDataChange(DataSnapshot dataSnapshot) {
  217.                             timestamp = dataSnapshot.getValue(long.class);
  218.                             System.out.println("fullName2: " + fullName);
  219.                             System.out.println("timestamp: " + timestamp);
  220.                             try {
  221.                                 latitude = Double.parseDouble(lat);
  222.                                 longitude = Double.parseDouble(lng);
  223.                             } catch (Exception e){
  224.                                 System.out.println("Exeption: " + e.toString());
  225.                             }
  226.                             Report report = new Report(userId, fullName, latitude, longitude,
  227.                                     timestamp, reportContent, category, fileUri.getLastPathSegment());
  228.                             mReportRef.child(reportKey).setValue(report);
  229.                             mDatabase.child("new-reports").child(reportKey).setValue(report);
  230.                         }
  231.  
  232.                         @Override
  233.                         public void onCancelled(DatabaseError databaseError) {
  234.                             System.out.println("Database Error: " + databaseError);
  235.                         }
  236.                     });
  237.  
  238.                     mProgressDialog.dismiss();
  239.                     getUserToken();
  240.                     finish();
  241.                 }
  242.             }
  243.         });
  244.  
  245. //
  246.     }
  247.  
  248.     private void takePicture() {
  249.         Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  250.  
  251.         fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
  252.         System.out.println("fileUri: " + fileUri.getPath());
  253.  
  254.         intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
  255.  
  256.         // start the image capture Intent
  257.         startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
  258.     }
  259.  
  260.     /**
  261.      * Creating file uri to store image/video
  262.      */
  263.     public Uri getOutputMediaFileUri(int type) {
  264.         return Uri.fromFile(getOutputMediaFile(type));
  265.     }
  266.  
  267.     /*
  268.      * returning image
  269.      */
  270.     private static File getOutputMediaFile(int type) {
  271.  
  272.         // External sdcard location
  273.         File mediaStorageDir = new File(
  274.                 Environment
  275.                         .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
  276.                 IMAGE_DIRECTORY_NAME);
  277.  
  278.         // Create the storage directory if it does not exist
  279.         if (!mediaStorageDir.exists()) {
  280.             if (!mediaStorageDir.mkdirs()) {
  281.                 Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
  282.                         + IMAGE_DIRECTORY_NAME + " directory");
  283.                 return null;
  284.             }
  285.         }
  286.  
  287.         // Create a media file name
  288.         String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
  289.                 Locale.getDefault()).format(new Date());
  290.         File mediaFile;
  291.         if (type == MEDIA_TYPE_IMAGE) {
  292.             mediaFile = new File(mediaStorageDir.getPath() + File.separator
  293.                     + "IMG_" + timeStamp + ".jpg");
  294.         } else {
  295.             return null;
  296.         }
  297.  
  298.         return mediaFile;
  299.     }
  300.  
  301.     @Override
  302.     public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
  303.         if (requestCode == 0) {
  304.             if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
  305.                     && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
  306.                 fab.setEnabled(true);
  307.             }
  308.         } else if (requestCode == LOCATION_REQUEST) {
  309.             if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
  310.                     && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
  311.                 Toast.makeText(getApplicationContext(), "Akses lokasi diizinkan",
  312.                         Toast.LENGTH_SHORT).show();
  313.             } else {
  314.                 Toast.makeText(getApplicationContext(), "Aplikasi harus diizinkan mengakses lokasi!",
  315.                         Toast.LENGTH_LONG).show();
  316.             }
  317.         }
  318.     }
  319.  
  320.     @Override
  321.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  322.         super.onActivityResult(requestCode, resultCode, data);
  323.         if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE && resultCode == RESULT_OK) {
  324.             try {
  325.                 System.out.println("fileUri.getPath" + fileUri.getPath());
  326.                 String getPath = fileUri.getPath();
  327.                 if (getPath.isEmpty()) {
  328.                     getPath = fileUri.getPath();
  329.                     System.out.println("getPath is empty...");
  330.                 }
  331.                 resizePhoto(getPath);
  332.                 previewCapturedImage();
  333.             } catch (Exception e) {
  334.                 Toast.makeText(getApplicationContext(), "Gagal memuat foto. Silahkan ulangi lagi!", Toast.LENGTH_LONG).show();
  335.                 System.out.println("Gagal mengecilkan foto!");
  336.                 e.printStackTrace();
  337.             }
  338.         } else if (requestCode == REQUEST_CHECK_SETTINGS) {
  339.             if (resultCode == RESULT_OK) {
  340.  
  341.                 Toast.makeText(getApplicationContext(), "GPS enabled", Toast.LENGTH_LONG).show();
  342.             } else {
  343.  
  344.                 Toast.makeText(getApplicationContext(), "GPS is not enabled", Toast.LENGTH_LONG).show();
  345.             }
  346.         }
  347.  
  348.     }
  349.  
  350.     /*
  351.     * Display image from a path to ImageView
  352.     */
  353.     private void previewCapturedImage() {
  354.  
  355.         // Get the dimensions of the View
  356.         int targetW = ivPhoto.getWidth();
  357.         int targetH = ivPhoto.getHeight();
  358.  
  359.         // Get the dimensions of the bitmap
  360.         BitmapFactory.Options bmOptions = new BitmapFactory.Options();
  361.         bmOptions.inJustDecodeBounds = true;
  362.         BitmapFactory.decodeFile(fileUri.getPath(), bmOptions);
  363.         int photoW = bmOptions.outWidth;
  364.         int photoH = bmOptions.outHeight;
  365.  
  366.         System.out.println("photoW: " + photoW + ", " + "photoH: " + photoH);
  367.  
  368.         // Determine how much to scale down the image
  369.         int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
  370.  
  371.         // Decode the image file into a Bitmap sized to fill the View
  372.         bmOptions.inJustDecodeBounds = false;
  373.         bmOptions.inSampleSize = scaleFactor;
  374.         bmOptions.inPurgeable = true;
  375.  
  376.         Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(), bmOptions);
  377.         ivPhoto.setImageBitmap(bitmap);
  378.     }
  379.  
  380.     private void resizePhoto(String uri) {
  381.         Bitmap photo = BitmapFactory.decodeFile(uri);
  382.         float scale = photo.getHeight() / 720f;
  383.         int width = (int) (Math.round(photo.getWidth() / scale));
  384.  
  385.         photo = Bitmap.createScaledBitmap(photo, width, 720, false);
  386.         ByteArrayOutputStream bytes = new ByteArrayOutputStream();
  387.         photo.compress(Bitmap.CompressFormat.JPEG, 80, bytes);
  388.  
  389.         File mediaStorageDir = new File(
  390.                 Environment
  391.                         .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
  392.                 IMAGE_DIRECTORY_NAME);
  393.  
  394.         File resizedFile;
  395.         resizedFile = new File(mediaStorageDir.getPath() + File.separator
  396.                 + fileUri.getLastPathSegment());
  397.  
  398.         try {
  399.             resizedFile.createNewFile();
  400.             FileOutputStream fo = new FileOutputStream(resizedFile);
  401.             fo.write(bytes.toByteArray());
  402.             fo.close();
  403.         } catch (IOException e) {
  404.             e.printStackTrace();
  405.         }
  406.  
  407.     }
  408.  
  409.     @Override
  410.     public void onConnected(@Nullable Bundle bundle) {
  411.         mLocationRequest = LocationRequest.create();
  412.         mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
  413.         mLocationRequest.setInterval(5000);
  414.         mLocationRequest.setFastestInterval(1000);
  415.  
  416.         if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
  417.                 != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
  418.                 android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
  419.  
  420.             ActivityCompat.requestPermissions(this,
  421.                     new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION,
  422.                             android.Manifest.permission.ACCESS_COARSE_LOCATION},
  423.                     LOCATION_REQUEST);
  424.             return;
  425.         }
  426.         LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
  427.  
  428.         mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
  429.         if (mLastLocation != null) {
  430.             lat = String.valueOf(mLastLocation.getLatitude());
  431.             lng = String.valueOf(mLastLocation.getLongitude());
  432.             accuracy = String.valueOf(mLastLocation.getAccuracy());
  433.             acc = mLastLocation.getAccuracy();
  434.         }
  435.  
  436.         mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
  437.  
  438.         LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
  439.                 .addLocationRequest(mLocationRequest);
  440.         builder.setAlwaysShow(true);
  441.         PendingResult<LocationSettingsResult> result =
  442.                 LocationServices.SettingsApi.checkLocationSettings(
  443.                         mGoogleApiClient,
  444.                         builder.build()
  445.                 );
  446.         result.setResultCallback(this);
  447.  
  448.         updateUI();
  449.     }
  450.  
  451.     private void updateUI() {
  452.         tvLocation.setText("Lokasi: " + lat + ", " + lng);
  453.         tvAccuracy.setText("Akurasi: " + accuracy + " m");
  454.         if (acc < 15) {
  455.             tvAccuracyStatus.setText("Lokasi akurat");
  456.             tvAccuracyStatus.setTextColor(Color.parseColor("#0000FF"));
  457.         } else {
  458.             tvAccuracyStatus.setText("Lokasi belum akurat");
  459.             tvAccuracyStatus.setTextColor(Color.parseColor("#FF4081"));
  460.         }
  461.     }
  462.  
  463.     @Override
  464.     public void onConnectionSuspended(int i) {
  465.  
  466.     }
  467.  
  468.     @Override
  469.     public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
  470.         buildGoogleApiClient();
  471.     }
  472.  
  473.     @Override
  474.     public void onResult(@NonNull LocationSettingsResult locationSettingsResult) {
  475.         final Status status = locationSettingsResult.getStatus();
  476.         switch (status.getStatusCode()) {
  477.             case LocationSettingsStatusCodes.SUCCESS:
  478.                 // NO need to show the dialog;
  479.                 break;
  480.  
  481.             case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
  482.                 //  Location settings are not satisfied. Show the user a dialog
  483.                 try {
  484.                     // Show the dialog by calling startResolutionForResult(), and check the result
  485.                     // in onActivityResult().
  486.  
  487.                     status.startResolutionForResult(this, REQUEST_CHECK_SETTINGS);
  488.  
  489.                 } catch (IntentSender.SendIntentException e) {
  490.                     //failed to show
  491.                 }
  492.                 break;
  493.  
  494.             case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
  495.                 // Location settings are unavailable so not possible to show any dialog now
  496.                 break;
  497.         }
  498.     }
  499.  
  500.     @Override
  501.     public void onLocationChanged(Location location) {
  502.  
  503.         lat = String.valueOf(location.getLatitude());
  504.         lng = String.valueOf(location.getLongitude());
  505.         accuracy = String.valueOf(location.getAccuracy());
  506.         acc = location.getAccuracy();
  507.         updateUI();
  508.         Log.d("ReportActivity", "Location is updated...");
  509.  
  510.     }
  511.  
  512.     synchronized void buildGoogleApiClient() {
  513.         mGoogleApiClient = new GoogleApiClient.Builder(this)
  514.                 .addConnectionCallbacks(this)
  515.                 .addOnConnectionFailedListener(this)
  516.                 .addApi(LocationServices.API)
  517.                 .build();
  518.     }
  519.  
  520.     @Override
  521.     protected void onStart() {
  522.         super.onStart();
  523.         mGoogleApiClient.connect();
  524.     }
  525.  
  526.     @Override
  527.     protected void onStop() {
  528.         super.onStop();
  529.         mGoogleApiClient.disconnect();
  530.     }
  531.  
  532.     @Override
  533.     protected void onDestroy() {
  534.         super.onDestroy();
  535.         mGoogleApiClient.disconnect();
  536.     }
  537.  
  538.     private String getFullName() {
  539.         userId = mAuth.getCurrentUser().getUid();
  540.         mUserRef = mDatabase.child("users").child(userId).child("fullName");
  541.         mUserRef.addListenerForSingleValueEvent(new ValueEventListener() {
  542.             @Override
  543.             public void onDataChange(DataSnapshot dataSnapshot) {
  544.                 fullName = dataSnapshot.getValue(String.class);
  545.                 System.out.println("fullName: " + fullName);
  546.             }
  547.  
  548.             @Override
  549.             public void onCancelled(DatabaseError databaseError) {
  550.  
  551.             }
  552.         });
  553.         return fullName;
  554.     }
  555.  
  556.     private void getUserToken(){
  557.         recipients = new JSONArray();
  558.         System.out.println("recipients: " + recipients.length());
  559.         final String body = category + " telah terjadi.";
  560.         mUserToken = mDatabase.child("user-token");
  561.         mUserToken.addValueEventListener(new ValueEventListener() {
  562.             @Override
  563.             public void onDataChange(DataSnapshot dataSnapshot) {
  564.                 Iterator<DataSnapshot> tokenSnapshot = dataSnapshot.getChildren().iterator();
  565.                 do {
  566.                     String key = tokenSnapshot.next().getKey();
  567.                     String userToken = dataSnapshot.child(key).child("userToken").getValue(String.class);
  568. //                    String token = userToken.getUserToken();
  569.                     System.out.println("datasnapshot: " + dataSnapshot);
  570.                     System.out.println("key: " + key);
  571.                     System.out.println("usertoken: " + userToken);
  572.                     recipients.put(userToken);
  573.                 } while (tokenSnapshot.hasNext());
  574.                 System.out.println("jsonarray: " + recipients);
  575.                 FcmSendMessage fcmSendMessage = new FcmSendMessage();
  576.                 fcmSendMessage.sendMessage(recipients, "", body, "", "Uji coba dari device");
  577. //                finish();
  578.             }
  579.  
  580.             @Override
  581.             public void onCancelled(DatabaseError databaseError) {
  582.  
  583.             }
  584.         });
  585.     }
  586. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement