2017-05-16 15 views
0

안녕하세요. firebase에 데이터를 입력하는 데 문제가 있습니다. 앨범의 이미지 데이터를 firebase에 삽입 할 수는 있지만 카메라의 이미지 데이터를 방금 찍은 Firebase에 놓을 수는 없습니다. 제발 도와주세요 :)데이터베이스를 firebase android studio에 푸시

//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); 
 
      } 
 
     } 
 
    } 
 
}

감사

다음
+1

[firebase에 이미지를 저장하고 보는 방법?] (http://stackoverflow.com/questions/13955813/how-to-store-and-view-images-on- firebase) – mmd1080

+0

이미지를'Base64'로 인코딩하여 Firebase에'String'으로 저장할 수 있습니다. 그리고 마지막으로 이미지를 검색 할 때'Bitmap' 이미지로 디코딩 할 수 있습니다. 희망이 도움이된다. – iMAD

답변

0

내가 그 날 위해 작업했던 방법입니다으로 onActivity 결과에서

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); 
         } 
        } 
       }); 

카메라 시작을 클릭하면

신고하기 Uri fileUri; - 글로벌

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); 
     } 
    } 
}