1

Please help here (fore job interview)

I'm trying to upload an image , when it's starts uploding , it crashes and removes the two basic childrens (image,thumb image)

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.pc.newchatj, PID: 9350 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference at com.example.pc.newchatj.SettingsActivity$1.onDataChange(SettingsActivity.java:103) at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@16.0.4:75) at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@16.0.4:63) at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@16.0.4:55) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5254) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

And in my Firebase database it removes the two childrens (image , thumb_image)

anyone please help

mUserDatabase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            String name = dataSnapshot.child("name").getValue().toString();
            String image = dataSnapshot.child("image").getValue().toString();
            String status = dataSnapshot.child("status").getValue().toString();
            String thumb_image = dataSnapshot.child("thumb_image").getValue().toString();

            mName.setText(name);
            mStatus.setText(status);

            if (!image.equals("default")) {
                Picasso.get().load(image).placeholder(R.drawable.default_avatar).into(mDisplayImage);
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

I've added StorageReference for both (image , thumb image)

filepath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                if (task.isSuccessful()){

                    UploadTask uploadTask = thumb_filepath.putBytes(thumb_byte);
                    uploadTask.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> thumb_task) {

                            if (thumb_task.isSuccessful()){

                                //getting regular image download url
                                filepath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                                    @Override
                                    public void onSuccess(Uri uri) {

                                        download_urll = uri.toString();

                                    }
                                }).addOnFailureListener(new OnFailureListener() {
                                    @Override
                                    public void onFailure(@NonNull Exception e) {
                                        Toast.makeText(SettingsActivity.this, "Regular fail", Toast.LENGTH_SHORT).show();
                                    }
                                });


                                //getting thumbnail download url
                                thumb_filepath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                                    @Override
                                    public void onSuccess(Uri thumb_uri) {

                                        thumb_downloadUrl = thumb_uri.toString();

                                    }
                                }).addOnFailureListener(new OnFailureListener() {
                                    @Override
                                    public void onFailure(@NonNull Exception e) {
                                        Toast.makeText(SettingsActivity.this, "thumb failed", Toast.LENGTH_SHORT).show();
                                    }
                                });


                                Map update_hashMap = new HashMap();
                                update_hashMap.put("image" , download_urll);
                                update_hashMap.put("thumb_image" , thumb_downloadUrl);


                                mUserDatabase.updateChildren(update_hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {

                                        if (task.isSuccessful()){
                                            avi_settings.smoothToHide();
                                            avi_settings.setVisibility(View.INVISIBLE);
                                            Toast.makeText(SettingsActivity.this, "Successfully uploaded", Toast.LENGTH_SHORT).show();


                                        }

                                    }
                                });

                            }



                        }
                    });

                    Toast.makeText(SettingsActivity.this, "working", Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(SettingsActivity.this, "Error uploading file", Toast.LENGTH_SHORT).show();
                    avi_settings.smoothToHide();
                    avi_settings.setVisibility(View.INVISIBLE);
                }
                }
            });
4
  • Can you please indicate at which particular line of code does this error occur? Commented Nov 5, 2018 at 18:08
  • @AlexMamo it's in the line of the image String image = dataSnapshot.child("image").getValue().toString(); Commented Nov 5, 2018 at 18:09
  • @AlexMamo i'm new to stackOverflow , can i post the hole code here ? Commented Nov 5, 2018 at 18:10
  • There is no need for the entire code. Please see my answer below. Commented Nov 5, 2018 at 18:20

4 Answers 4

0

Before trying to get the data from the dataSnapshot object, you should check if that data actually exist:

mUserDatabase.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()) { //Check for existens
            String name = dataSnapshot.child("name").getValue(String.class);
            String image = dataSnapshot.child("image").getValue(String.class);
            String status = dataSnapshot.child("status").getValue(String.class);
            String thumb_image = dataSnapshot.child("thumb_image").getValue(String.class);

            mName.setText(name);
            mStatus.setText(status);

            if (!image.equals("default")) {
                Picasso.get().load(image).placeholder(R.drawable.default_avatar).into(mDisplayImage);
            }   
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
    }
});

Also is best to pass String.class to the getValue() method insted of casting it to String. You will not get any NullPointerException anymore.

Sign up to request clarification or add additional context in comments.

7 Comments

So ? ... that dose not do anything , the data exists on the Storage !
You said you get NullPointerException at this line of code String image = dataSnapshot.child("image").getValue().toString();. It doesn't matter if the data exist in the Storage, you should check if it exist in your dataSnapshot object. Is has nothing to do with what exist, or does not exist in the Firebase Storage. Have you even tried my solution above? Does it work?
yes i've tried it , i'm storing an image in the firebase storage , getting it's URL and storing it on the firebase database , but when i store it it crashes
If the app crashes, there is a stack trace. Please look that up on logcat, and add it to your question or as a comment and indicate the line at which line of code it occurs.
Hi Johnny! Is there everything alright, have you solved the issue?
|
0

As you wrote NullPointerException rises in line

String name = dataSnapshot.child("name").getValue().toString();

The error message says you try to invoke .toString() on an null object. You should save the result from String name = dataSnapshot.child("name").getValue() and check if it's not null before calling .toSring() method.

2 Comments

Error appers inString image = dataSnapshot.child("image").getValue().toString();
ok, sorry for this ;) .... but checking the value before calling the method could help nevertheless
0

use it

store.setUrl((String) snapshot1.child("url").getValue());
store.setName((String) snapshot1.child("name").getValue());

Instead of

store.setUrl(snapshot1.child("url").getValue().toString());
store.setName(snapshot1.child("name").getValue().toString());

Comments

-1

I know it's not something technical but it could be a mistake, so please check your child or reference name if it is same as on your database. I spent 3 days in fixing related bug and ending up with finding wrong reference name. I hope if it can help. Thanks.

1 Comment

Please, don't post several times the same answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.