firebase database snapshot crashes when i add 2 datasnapshots to look after

0

i am using firebase database and wanted to match a value (the schoolcode) of the user being added to contacts with current users value ( schoolcode) and when i added the code user1.getSchoolCode it started crashing any ideas?

if i pass just a simple string like if (user.getSchoolcode().equals("001")) { users.add(user); } it works but user1.getSchoolCode dont work

RecyclerView recyclerView;
    UserAdapter userAdapter;

    List<User> users;

    FirebaseUser firebaseUser;
    DatabaseReference reference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contacts_parent);

        recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));

        users = new ArrayList<>();



        firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
        reference = FirebaseDatabase.getInstance().getReference("teacher");

        readUsers();
    }

    private void readUsers() {

        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                users.clear();
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {

                    DataSnapshot snapshot1 = dataSnapshot.child(firebaseUser.getUid());

                    User user = snapshot.getValue(User.class);

                    User user1 = snapshot1.getValue(User.class);

                    assert user != null;
                    if (user.getSchoolcode().equals(user1.getSchoolcode())) {
                        users.add(user);
                    }
                }
                userAdapter= new UserAdapter(getApplicationContext(), users);
                recyclerView.setAdapter(userAdapter);
            }
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }
}

thanks in advance

this is the logcat

2020-04-15 16:01:44.851 15021-15021/net.gobz.gobz D/AndroidRuntime: Shutting down VM
2020-04-15 16:01:44.852 15021-15021/net.gobz.gobz E/AndroidRuntime: FATAL EXCEPTION: main
    Process: net.gobz.gobz, PID: 15021
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String net.gobz.gobz.Model.User.getSchoolcode()' on a null object reference
        at net.gobz.gobz.parent.ContactsParentActivity$1.onDataChange(ContactsParentActivity.java:69)
        at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@19.2.1:75)
        at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@19.2.1:63)
        at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@19.2.1:55)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7099)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
2020-04-15 16:01:44.864 15021-15021/net.gobz.gobz I/Process: Sending signal. PID: 15021 SIG: 9

i dont know if you need this too

   2020-04-15 15:55:56.298 15021-15021/? E/Zygote: isWhitelistProcess - Process is Whitelisted
2020-04-15 15:55:56.298 15021-15021/? E/Zygote: accessInfo : 1
2020-04-15 15:55:56.304 15021-15021/? I/net.gobz.gobz: Late-enabling -Xcheck:jni
2020-04-15 15:55:56.336 15021-15021/? I/net.gobz.gobz: report jit thread pid = 15027
2020-04-15 15:55:56.966 15021-15021/net.gobz.gobz I/MultiDex: VM with version 2.1.0 has multidex support
2020-04-15 15:55:56.967 15021-15021/net.gobz.gobz I/MultiDex: Installing application
2020-04-15 15:55:56.967 15021-15021/net.gobz.gobz I/MultiDex: VM has multidex support, MultiDex support library is disabled.
2020-04-15 15:55:57.011 15021-15057/net.gobz.gobz W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
2020-04-15 15:55:57.029 15021-15021/net.gobz.gobz D/FirebaseAuth: Notifying id token listeners about user ( RvM1ycqh35Vxzi4M8NzHGaFERMp1 ).
2020-04-15 15:55:57.034 15021-15021/net.gobz.gobz I/FirebaseInitProvider: FirebaseApp initialization successful
2020-04-15 15:55:57.042 15021-15059/net.gobz.gobz W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
2020-04-15 15:55:57.051 15021-15059/net.gobz.gobz I/FirebaseAuth: [FirebaseAuth:] Preparing to create service connection to gms implementation
2020-04-15 15:55:57.114 15021-15021/net.gobz.gobz W/net.gobz.gobz: Accessing hidden method Landroid/graphics/drawable/Drawable;->getOpticalInsets()Landroid/graphics/Insets; (light greylist, linking)
2020-04-15 15:55:57.114 15021-15021/net.gobz.gobz W/net.gobz.gobz: Accessing hidden field Landroid/graphics/Insets;->left:I (light greylist, linking)
2020-04-15 15:55:57.114 15021-15021/net.gobz.gobz W/net.gobz.gobz: Accessing hidden field Landroid/graphics/Insets;->right:I (light greylist, linking)
2020-04-15 15:55:57.114 15021-15021/net.gobz.gobz W/net.gobz.gobz: Accessing hidden field Landroid/graphics/Insets;->top:I (light greylist, linking)
2020-04-15 15:55:57.114 15021-15021/net.gobz.gobz W/net.gobz.gobz: Accessing hidden field Landroid/graphics/Insets;->bottom:I (light greylist, linking)
2020-04-15 15:55:57.141 15021-15021/net.gobz.gobz W/Glide: Failed to find GeneratedAppGlideModule. You should include an annotationProcessor compile dependency on com.github.bumptech.glide:compiler in your application and a @GlideModule annotated AppGlideModule implementation or LibraryGlideModules will be silently ignored
2020-04-15 15:55:57.193 15021-15021/net.gobz.gobz I/DecorView: createDecorCaptionView >> DecorView@a917524[], isFloating: false, isApplication: true, hasWindowDecorCaption: false, hasWindowControllerCallback: true
2020-04-15 15:55:57.228 15021-15021/net.gobz.gobz W/net.gobz.gobz: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (light greylist, reflection)
2020-04-15 15:55:57.229 15021-15021/net.gobz.gobz W/net.gobz.gobz: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (light greylist, reflection)
2020-04-15 15:55:57.295 15021-15021/net.gobz.gobz W/net.gobz.gobz: Accessing hidden method Landroid/widget/TextView;->getTextDirectionHeuristic()Landroid/text/TextDirectionHeuristic; (light greylist, linking)
2020-04-15 15:55:57.339 15021-15021/net.gobz.gobz W/net.gobz.gobz: Accessing hidden field Landroid/view/View;->mAccessibilityDelegate:Landroid/view/View$AccessibilityDelegate; (light greylist, reflection)
2020-04-15 15:55:57.572 15021-15021/net.gobz.gobz D/OpenGLRenderer: Skia GL Pipeline
2020-04-15 15:55:57.578 15021-15021/net.gobz.gobz D/EmergencyMode: [EmergencyManager] android createPackageContext successful
2020-04-15 15:55:57.641 15021-15021/net.gobz.gobz D/InputTransport: Input channel constructed: fd=64
2020-04-15 15:55:57.642 15021-15021/net.gobz.gobz D/ViewRootImpl@98b94c[MainParentActivity]: setView = DecorView@a917524[MainParentActivity] TM=true MM=false
2020-04-15 15:55:57.670 15021-15066/net.gobz.gobz D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2020-04-15 15:55:57.676 15021-15066/net.gobz.gobz D/NetworkManagementSocketTagger: tagSocket(62) with statsTag=0xffffffff, statsUid=-1
2020-04-15 15:55:57.734 15021-15021/net.gobz.gobz D/ViewRootImpl@98b94c[MainParentActivity]: Relayout returned: old=[0,0][1080,2340] new=[0,0][1080,2340] result=0x7 surface={true 537833799680} changed=true
2020-04-15 15:55:57.751 15021-15065/net.gobz.gobz I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
2020-04-15 15:55:57.752 15021-15065/net.gobz.gobz I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasHDRDisplay retrieved: 0
2020-04-15 15:55:57.752 15021-15065/net.gobz.gobz I/OpenGLRenderer: Initialized EGL, version 1.4
2020-04-15 15:55:57.752 15021-15065/net.gobz.gobz D/OpenGLRenderer: Swap behavior 2
2020-04-15 15:55:57.766 15021-15065/net.gobz.gobz D/mali_winsys: EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, EGLBoolean) returns 0x3000
2020-04-15 15:55:57.766 15021-15065/net.gobz.gobz D/OpenGLRenderer: eglCreateWindowSurface = 0x7d3d346e00, 0x7d39648010
2020-04-15 15:55:57.832 15021-15021/net.gobz.gobz D/ViewRootImpl@98b94c[MainParentActivity]: Relayout returned: old=[0,0][1080,2340] new=[0,0][1080,2340] result=0x3 surface={true 537833799680} changed=false
2020-04-15 15:55:57.967 15021-15021/net.gobz.gobz D/ViewRootImpl@98b94c[MainParentActivity]: MSG_RESIZED: frame=[0,0][1080,2340] ci=[0,83][0,126] vi=[0,83][0,126] or=1
2020-04-15 15:55:57.968 15021-15021/net.gobz.gobz D/ViewRootImpl@98b94c[MainParentActivity]: MSG_WINDOW_FOCUS_CHANGED 1 1
2020-04-15 15:55:57.968 15021-15021/net.gobz.gobz D/InputMethodManager: prepareNavigationBarInfo() DecorView@a917524[MainParentActivity]
2020-04-15 15:55:57.969 15021-15021/net.gobz.gobz D/InputMethodManager: getNavigationBarColor() -855310
2020-04-15 15:55:57.979 15021-15021/net.gobz.gobz D/InputMethodManager: prepareNavigationBarInfo() DecorView@a917524[MainParentActivity]
2020-04-15 15:55:57.979 15021-15021/net.gobz.gobz D/InputMethodManager: getNavigationBarColor() -855310
2020-04-15 15:55:57.979 15021-15021/net.gobz.gobz V/InputMethodManager: Starting input: tba=net.gobz.gobz ic=null mNaviBarColor -855310 mIsGetNaviBarColorSuccess true , NavVisible : true , NavTrans : false
2020-04-15 15:55:57.979 15021-15021/net.gobz.gobz D/InputMethodManager: startInputInner - Id : 0
2020-04-15 15:55:57.979 15021-15021/net.gobz.gobz I/InputMethodManager: startInputInner - mService.startInputOrWindowGainedFocus
2020-04-15 15:55:57.990 15021-15040/net.gobz.gobz D/InputTransport: Input channel constructed: fd=84
2020-04-15 15:55:57.990 15021-15021/net.gobz.gobz D/InputMethodManager: prepareNavigationBarInfo() DecorView@a917524[MainParentActivity]
2020-04-15 15:55:57.991 15021-15021/net.gobz.gobz D/InputMethodManager: getNavigationBarColor() -855310
2020-04-15 15:55:57.991 15021-15021/net.gobz.gobz V/InputMethodManager: Starting input: tba=net.gobz.gobz ic=null mNaviBarColor -855310 mIsGetNaviBarColorSuccess true , NavVisible : true , NavTrans : false
2020-04-15 15:55:57.991 15021-15021/net.gobz.gobz D/InputMethodManager: startInputInner - Id : 0
2020-04-15 15:56:00.294 15021-15021/net.gobz.gobz W/ClassMapper: No setter/field for studentname found on class net.gobz.gobz.Model.User
2020-04-15 15:56:00.295 15021-15021/net.gobz.gobz W/ClassMapper: No setter/field for grade found on class net.gobz.gobz.Model.User
2020-04-15 15:56:00.295 15021-15021/net.gobz.gobz W/ClassMapper: No setter/field for section found on class net.gobz.gobz.Model.User
2020-04-15 15:56:00.296 15021-15021/net.gobz.gobz W/ClassMapper: No setter/field for status found on class net.gobz.gobz.Model.User

here is a screenshot of my database

this is the screen shot of my database

i have one more problem now when i touch the contact and open the messaging activity it is crashing again

this is my messages activity


    CircleImageView imageView;

    FirebaseUser firebaseUser;
    DatabaseReference reference;

    Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message);

        final Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        imageView = findViewById(R.id.profile_image);

        intent = getIntent();
        String userid = intent.getStringExtra("userid");

        firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
        reference = FirebaseDatabase.getInstance().getReference("parent").child(userid);

        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                User user = dataSnapshot.getValue(User.class);

                if (user.getImageURL().equals("default")) {
                    imageView.setImageResource(R.drawable.ic_user);
                }else {
                    Glide.with(MessageActivity.this).load(user.getImageURL()).into(imageView);
                }
            }

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

            }
        });
    }
}

and this is the intent i was calling for

holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context, MessageActivity.class);
                intent.putExtra("userid", user.getId());
                context.startActivity(intent);
            }
        });
android
firebase-realtime-database
asked on Stack Overflow Apr 15, 2020 by Rough Manly • edited May 1, 2020 by Rough Manly

1 Answer

1

first get current user from Firebase

private void getCurrentUser(String userID) {
Log.("UserId==>",userID+"");//do check this value in teacher database

        FirebaseDatabase.getInstance().getReference("parent").child(userID).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
               try{ if(dataSnapshot != null){ Log.e("UserVal==>", snapshot.getValue(JSONObject.class));
                    User user1 = snapshot.getValue(User.class);
                    readUsers(user1.getSchoolcode());}} catch (Exception e){e.printstacktrace(); Log.e("getusererror",e.getMessage());}

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

            }
        });
    }

And update your readUsers method like this , you can also change parameter to pass User instead of schoolCode

private void readUsers(String schoolCode) {

        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
               try{ users.clear();
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {



                    User user = snapshot.getValue(User.class);


                    assert user != null;
                    if (user.getSchoolcode().equals(schoolCode)) {
                        users.add(user);
                    }
                }
                userAdapter= new UserAdapter(getApplicationContext(), users);
                recyclerView.setAdapter(userAdapter);} catch (Exception e){e.printstacktrace(); Log.e("readError",e.getMessage());}
            }
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }

first Call the getCurrentUser method

firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
        reference = FirebaseDatabase.getInstance().getReference("teacher");

        getCurrentUser(firebaseUser.getUid());// readUsers()  
answered on Stack Overflow Apr 15, 2020 by R7G • edited Apr 15, 2020 by R7G

User contributions licensed under CC BY-SA 3.0