0

I'm working on my project at school where I need to capture an image and save it to Firebase. Here's my code

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

my dependencies

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(application)

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)

In my firebase.google.com my storage is equal to null for saving image only.

My problem is that, every time I run the program, when I pressed the consumption button to save the captured image to the firebase, the application would eventually stopped.

frogatto
  • 28,539
  • 11
  • 83
  • 129
Mike
  • 83
  • 1
  • 1
  • 14
  • please add your `logcat` to see which exception you're receiving – LS_ Dec 12 '17 at 09:28
  • I didn't receive any exception or error during build. – Mike Dec 12 '17 at 09:30
  • It's not during build but during runtime, if the application stops as soon as you click a button you'll find the exception which caused the crash in the logcat – LS_ Dec 12 '17 at 09:32
  • Please see the edited, thanks. – Mike Dec 12 '17 at 09:45
  • Sorry but I think the lines you posted are not related to the issue, the exception in logcat should appear with a red text and under your app name. – LS_ Dec 12 '17 at 09:49
  • Most of the red ones are those lines, except for these, "12-12 17:37:41.039 26126-26126/? E/MultiWindowProxy: getServiceInstance failed!" and "12-12 17:37:54.384 1351-1652/? E/NativeCrypto: ssl=0xb9bb49e8 cert_verify_callback x509_store_ctx=0xa019fd0c arg=0x0; 12-12 17:37:54.384 1351-1652/? E/NativeCrypto: ssl=0xb9bb49e8 cert_verify_callback calling verifyCertificateChain authMethod=ECDHE_RSA" – Mike Dec 12 '17 at 10:05
  • in logcat you should be able to select both the device and the app package you'd like to filter from a dropdown list. Are you able to select only your application's log? – LS_ Dec 12 '17 at 10:10
  • Please see the edited, thank you :) – Mike Dec 12 '17 at 10:23

1 Answers1

0

The reason the app is crashing is this:

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

The variable uri is not initialized, so when you do this:

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

You're trying to access getLastPathSegment() of a null object. You should setup some breakpoints to check if the variable uri gets initialized correctly; Looking at the code uri is set once in onActivityResult so you should check here if the method gets fired and if the variable gets initialized.

EDIT:

This answer can possibly help with your issue.

LS_
  • 6,763
  • 9
  • 52
  • 88