0

Hi i'm having trouble entering data into firebase. I can insert image data from album to firebase but i can not put image data from camera to firebase that i just photo. Please help me :)

//activitylapor

public class Lapor extends AppCompatActivity {

    private ImageButton mSelectImage;
    private EditText mPostNamaPelapor;
    private EditText mPostNoTelpon;
    private EditText mPostLokasiKejadian;
    private EditText mPostKeteranganBencana;
    private EditText mPostWaktuBencana;

    private Uri mImageUri = null;

    //private static final int GALLERY_REQUEST = 1;
    private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
    private String userChoosenTask;
    private ImageView ivImage;

    private StorageReference mStorage;
    private DatabaseReference mDatabase;

    private ProgressDialog mProgress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        mStorage = FirebaseStorage.getInstance().getReference();
        mDatabase = FirebaseDatabase.getInstance().getReference().child("Lapor");

        mSelectImage = (ImageButton) findViewById(R.id.imageSelect);
        mPostNamaPelapor = (EditText) findViewById(R.id.namaPelapor);
        mPostNoTelpon = (EditText) findViewById(R.id.noTelpon);
        mPostLokasiKejadian = (EditText) findViewById(R.id.lokasiKejadian);
        mPostKeteranganBencana = (EditText) findViewById(R.id.keteranganBencana);
        ivImage = (ImageView) findViewById(R.id.ivImage);

        Button mSubmitBtn = (Button) findViewById(R.id.submitBtn);

        mProgress = new ProgressDialog(this);


        mSelectImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectImage();
            }
        });

        mSubmitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startPosting();
            }
        });
    }


    private void startPosting() {

        mProgress.setMessage("Posting Lapor");
        mProgress.show();

        final String namapelapor_val = mPostNamaPelapor.getText().toString().trim();
        final String notelpon_val = mPostNoTelpon.getText().toString().trim();
        final String lokasikejadian_val = mPostLokasiKejadian.getText().toString().trim();
        final String keteranganbencana_val = mPostKeteranganBencana.getText().toString().trim();

        if (!TextUtils.isEmpty(namapelapor_val) && !TextUtils.isEmpty(notelpon_val) && !TextUtils.isEmpty(lokasikejadian_val)
                && !TextUtils.isEmpty(keteranganbencana_val) && mImageUri != null) {

            StorageReference filepath = mStorage.child("Foto_Lapor").child(mImageUri.getLastPathSegment());

            filepath.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                    Uri downloadUrl = taskSnapshot.getDownloadUrl();

                    DatabaseReference newPost = mDatabase.push();

                    newPost.child("namapelapor").setValue(namapelapor_val);
                    newPost.child("nomortelpon").setValue(notelpon_val);
                    newPost.child("lokasikejadian").setValue(lokasikejadian_val);
                    newPost.child("keteranganbencana").setValue(keteranganbencana_val);
                    assert downloadUrl != null;
                    newPost.child("foto").setValue(downloadUrl.toString());

                    mProgress.dismiss();

                    startActivity(new Intent(Lapor.this, Terimakasih.class));
                    finish();
                }
            });
        }

    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){
        switch (requestCode) {
            case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (userChoosenTask.equals("Ambil Foto"))
                        cameraIntent();
                    else if (userChoosenTask.equals("Ambil dari Album"))
                        galleryIntent();
                } else {
                    //code for deny
                }
                break;
        }
    }

    private void selectImage() {
        final CharSequence[] items = {"Ambil Foto", "Ambil dari Album",
                "Batal"};

        AlertDialog.Builder builder = new AlertDialog.Builder(Lapor.this);
        builder.setTitle("Ambil Gambar");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                boolean result = Utility.checkPermission(Lapor.this);

                if (items[item].equals("Ambil Foto")) {
                    userChoosenTask = "Ambil Foto";
                    if (result)
                        cameraIntent();

                } else if (items[item].equals("Ambil dari Album")) {
                    userChoosenTask = "Ambil dari Album";
                    if (result)
                        galleryIntent();

                } else if (items[item].equals("Batal")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }

    private void galleryIntent() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);//
        startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
    }

    private void cameraIntent() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, REQUEST_CAMERA);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == SELECT_FILE) {
                Uri mImageUri = data.getData();
                CropImage.activity(mImageUri)
                        .setGuidelines(CropImageView.Guidelines.ON)
                        .setAspectRatio(4, 3)
                        .start(this);
            }
            if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
                CropImage.ActivityResult result = CropImage.getActivityResult(data);

                mImageUri = result.getUri();

                ivImage.setImageURI(mImageUri);
            }
            else if (requestCode == REQUEST_CAMERA) {
                Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
                ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);

                File destination = new File(Environment.getExternalStorageDirectory(),
                        System.currentTimeMillis() + ".jpg");


                ivImage.setImageBitmap(thumbnail);
            }
        }
    }
}

Thanks

AL.
  • 36,815
  • 10
  • 142
  • 281
  • 1
    Possible duplicate of [How to store and view images on firebase?](http://stackoverflow.com/questions/13955813/how-to-store-and-view-images-on-firebase) – mmd1080 May 16 '17 at 18:31
  • It is possible to encode the image into `Base64`, store it into Firebase as a `String` and finally, when you retrieve it, decode it into a `Bitmap` image. Hope it helps – Imad May 16 '17 at 20:25

1 Answers1

0

Here is how i have done,its working for me,

In OnActivity Result,

   FirebaseStorage storage = FirebaseStorage.getInstance();
        StorageReference storageRef = storage.getReferenceFromUrl(AppConstants.STORAGE_BUCKET);
        final String imageName = "INSTA_"+System.currentTimeMillis()+".JPEG";
       StorageReference imagePathReference;
                imagePathReference = storageRef.child("---your storage path---"+ imageName);
                // bimatp factory
                BitmapFactory.Options options = new BitmapFactory.Options();
                // downsizing image as it throws OutOfMemory Exception for larger  images
                options.inSampleSize = 8;
                final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(), options);
                ByteArrayOutputStream bos2 = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 60, bos2);

                byte[] dataNew2 = bos2.toByteArray();
                uploadTask = imagePathReference2.putBytes(dataNew2);
                uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        if(FirebaseAuth.getInstance().getCurrentUser() != null){
                            initToSendMessageToFirebase(fileUri, MESSAGE_TYPE_IMAGE,taskSnapshot,"",imageName);
                        }
                    }
                });

On Clicking launch Camera,

Declare Uri fileUri ; -- global

   private void launchCamera() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            try {
                fileUri = Uri.fromFile(createImageFile());
            } catch (IOException e) {
                e.printStackTrace();
            }
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
            startActivityForResult(takePictureIntent, RC_CAMERA);
        }
    }
}
Priya
  • 672
  • 1
  • 5
  • 21