Android 3.0 - 将图像保存到Firebase

时间:2017-12-12 09:21:24

标签: java android firebase-storage android-fragmentactivity

我正在学校开展项目,我需要捕获图片并将其保存到Firebase。这是我的代码

package com.example.akoni.conread;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

import static android.app.Activity.RESULT_OK;

/**
 * Created by Akoni on 12/2/2017.
  */

public class WaterConsumptionPage extends Fragment {
Spinner month, date, year;
ImageView imageView;
Button upload, consumption;
static final int CAM_REQUEST = 1;
private StorageReference mStorageRef;
private FirebaseAuth mAuth;
private DatabaseReference dbRef;
private ProgressDialog mProgress;
private Uri uri = null;
private Bitmap photo;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.water_consumption_page, container, false);

    mStorageRef = FirebaseStorage.getInstance().getReference();
    mAuth = FirebaseAuth.getInstance();
    dbRef = FirebaseDatabase.getInstance().getReference();

    month = rootView.findViewById(R.id.wtr_month);
    date = rootView.findViewById(R.id.wtr_date);
    year = rootView.findViewById(R.id.wtr_year);

    imageView = rootView.findViewById(R.id.water_image);
    upload = rootView.findViewById(R.id.water_upload);
    consumption = rootView.findViewById(R.id.water_consumption);

    upload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent cam_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cam_intent, CAM_REQUEST);
        }
    });

    mProgress = new ProgressDialog(getContext());
    consumption.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mProgress.setMessage("Uploading Image...");
            mProgress.show();

            StorageReference filepath = mStorageRef.child("Water").child(uri.getLastPathSegment());
            filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    mProgress.dismiss();
                    Toast.makeText(getContext(), "Upload Finished...", Toast.LENGTH_LONG).show();
                    Intent i = new Intent(getContext(), WaterConsumption.class);
                    startActivity(i);
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    mProgress.dismiss();
                    Toast.makeText(getContext(), "Upload has stopped.", Toast.LENGTH_LONG).show();
                }
            });
        }
    });

    return rootView;
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode == CAM_REQUEST && resultCode == RESULT_OK){
        uri = data.getData();
        Bundle extras = data.getExtras();
        photo = (Bitmap) extras.get("data");
        imageView.setImageBitmap(photo);
    }
}
}

我的依赖

dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        implementation 'com.android.support:appcompat-v7:26.1.0'
        implementation 'com.android.support.constraint:constraint-layout:1.0.2'
        implementation 'com.android.support:support-v4:26.1.0'
        implementation 'com.android.support:design:26.1.0'
        implementation 'com.google.firebase:firebase-auth:11.0.4'
        implementation 'com.google.firebase:firebase-database:11.0.4'
        implementation 'com.google.firebase:firebase-storage:11.0.4'
        testImplementation 'junit:junit:4.12'
        androidTestImplementation 'com.android.support.test:runner:1.0.1'
        androidTestImplementation 'com.android.support.test.espresso:espresso-
              core:3.0.1'
    }

    apply plugin: 'com.google.gms.google-services'

的AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.akoni.conread">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature
        android:name="android.hardware.camera2"
        android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".SignIn"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ForgotPassword"
            android:screenOrientation="portrait" />
        <activity
            android:name=".TabMenu"
            android:label="@string/title_activity_tab_menu"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity android:name=".WaterConsumption" />
        <activity android:name=".ElectricConsumption"></activity>
    </application>

</manifest>

logcat的(应用)

12-12 18:20:20.209 31023-31023/com.example.akoni.conread E/MultiWindowProxy: getServiceInstance failed!
12-12 18:20:22.832 31023-31078/com.example.akoni.conread E/NativeCrypto: ssl=0xb9393e78 cert_verify_callback x509_store_ctx=0xa297e21c arg=0x0
12-12 18:20:22.832 31023-31078/com.example.akoni.conread E/NativeCrypto: ssl=0xb9393e78 cert_verify_callback calling verifyCertificateChain authMethod=ECDHE_RSA
12-12 18:20:43.498 31023-31023/com.example.akoni.conread E/AndroidRuntime: FATAL EXCEPTION: main
                                                                       Process: com.example.akoni.conread, PID: 31023
                                                                       java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference
                                                                           at com.example.akoni.conread.WaterConsumptionPage$2.onClick(WaterConsumptionPage.java:78)
                                                                           at android.view.View.performClick(View.java:5265)
                                                                           at android.view.View$PerformClick.run(View.java:21534)
                                                                           at android.os.Handler.handleCallback(Handler.java:815)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:104)
                                                                           at android.os.Looper.loop(Looper.java:207)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:5728)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)

在我的firebase.google.com中,我的存储空间等于空,仅用于保存图片。

我的问题是,每次运行程序时,当我按下消耗按钮将捕获的图像保存到firebase时,应用程序最终会停止。

1 个答案:

答案 0 :(得分:0)

应用程序崩溃的原因是:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference

变量uri未初始化,因此当您执行此操作时:

StorageReference filepath = mStorageRef.child("Water").child(uri.getLastPathSegment());

您正试图访问getLastPathSegment()null个对象的uri。 您应该设置一些断点来检查变量uri是否正确初始化;查看代码onActivityResult在{{1}}中设置一次,因此您应该检查方法是否被触发以及变量是否已初始化。

修改

This answer可能有助于解决您的问题。