我正在尝试构建一个包含两个按钮的MainActivity
,一个按钮用于使用相机拍照并将其上传到Firebase Storage,另一个按钮用于从Firebase Storage下载图像并显示在ImageView
。
现在,我受制于上传功能。我可以拍照并将其保存到应用程序目录中。我想将保存的图片上传到Firebase存储中。
我的MainActivity.java
(基于Firebase开发人员教程)如下:
package com.example.mathi.image;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
static final int REQUEST_TAKE_PHOTO = 1;
String mCurrentPhotoPath;
private Button btn_upload;
private Button btn_download;
//Firebase
FirebaseStorage storage;
StorageReference storageReference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_upload = (Button)findViewById(R.id.btn_upload);
btn_download = (Button)findViewById(R.id.btn_download);
btn_upload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
btn_download.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
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) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.mathi.image.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
upload_photo();
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
private void upload_photo(){
Uri file = Uri.fromFile(new File(mCurrentPhotoPath));
UploadTask uploadTask = storageReference.putFile(file);
// Register observers to listen for when the download is done or if
it fails
uploadTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle unsuccessful uploads
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, etc.
// ...
}
});
}
}
在调试器中,我出现以下错误:
java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'com.google.firebase.storage.UploadTask com.google.firebase.storage.StorageReference.putFile(android.net.Uri)' 在com.example.mathi.image.MainActivity.upload_photo(MainActivity.java:112)
第112行是以下行:
UploadTask uploadTask = storageReference.putFile(file);
当我删除upload()
方法时,该文件是在本地目录上创建的。但是,使用upload()
方法会使应用程序崩溃。
有人知道我想念什么吗?
答案 0 :(得分:1)
尝试此代码
btn_upload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CaptureImageFromCamera();
}
});
private void CaptureImageFromCamera() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, 200);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
try {
if (requestCode == 200) {
Uri imageUri = data.getData();
sendImage(imageUri);
}
}
catch (Exception e) {
}
}else{
Toast.makeText(this, "Cancelled", Toast.LENGTH_SHORT).show();
}
}
private void sendImage(Uri imageUri){
UploadTask uploadTask = storageReference.putFile(imageUri);
uploadTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle unsuccessful uploads
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
}
});
}