Malusi Gcabashe
Malusi Gcabashe

Reputation: 17

Retrieving Values from firebase database, then displaying it as a message from someone who will be receiving it

This is the class where I want to retrieve the values in the database

public class EmergencyAlertActivity extends AppCompatActivity {

private Toolbar mChatToolbar; //used
private String mChatUser;  //used
private String mthumb_image;
private String userName;
private String mCurrentUserId;
private TextView mUserStatus;
private EditText mChatMessageView;
private String emerg_message;
private String open_location;

private CircleImageView mProfileImage;
private FirebaseAuth mAuth;
private ImageButton mChatAddBtn;
private TextView view_location;

private DatabaseReference mRootRef;
// Storage Firebase
private StorageReference mImageStorage;
private static final int GALLERY_PICK = 1;

private RecyclerView mMessagesList;
private SwipeRefreshLayout mRefreshLayout;

private ArrayList<String> arrayList_Message = new ArrayList<String>();

private AlertAdapter mAdapter;

private static final int TOTAL_ITEMS_TO_LOAD = 10;
private int mCurrentPage = 1;
private DatabaseReference mUserDatabase;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_emergency_alert);
    mChatMessageView = (EditText) findViewById(R.id.chat_message_view);
    mChatAddBtn = (ImageButton) findViewById(R.id.chat_add_btn);

    mChatToolbar = (Toolbar) findViewById(R.id.chat_app_bar);
    setSupportActionBar(mChatToolbar);

    ActionBar actionBar = getSupportActionBar();

    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setDisplayShowCustomEnabled(true);

    //for Custom Action bar
    actionBar.setDisplayShowCustomEnabled(true);

    LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
    View customBar = inflater.inflate(R.layout.chat_custom_bar,null);

    actionBar.setCustomView(customBar);

    //getting intent Data
    gettingIntentData();

    // initializing user view
    intCustomBarViewAndSetData();


    mRootRef = FirebaseDatabase.getInstance().getReference();
    mAuth = FirebaseAuth.getInstance();
    mCurrentUserId =  mAuth.getCurrentUser().getUid();




    //------- IMAGE STORAGE ---------
    mImageStorage = FirebaseStorage.getInstance().getReference();

    mRootRef.child("Emergency_Chat").child(mCurrentUserId).child(mChatUser).child("seen").setValue(true);

    LoadMessages();

    //getting information about user online or offline and thumb image
    mRootRef.child("Users").child(mChatUser).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            String thumb_image = dataSnapshot.child("thumb_image").getValue().toString();
            Picasso.with(EmergencyAlertActivity.this).load(thumb_image).placeholder(R.drawable.my_profile).into(mProfileImage);

            String lastSeen = dataSnapshot.child("online").getValue().toString();

            if(lastSeen.equals("true")){
                mUserStatus.setText("Online");
            }
            else{

                //converting string into long
                Long lastTime = Long.parseLong(lastSeen);

                // creating an instance of GetTimeAgo class
                GetTimeAgo getTimeAgo = new GetTimeAgo();
                String lastSeenTime = GetTimeAgo.getTimeAgo(lastTime,getApplicationContext());
                mUserStatus.setText(lastSeenTime);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });


    //for creating chat object
    mRootRef.child("Emergency_Chat").child(mCurrentUserId).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            if(!dataSnapshot.hasChild(mChatUser)){

                Map chatAddMap = new HashMap();
                chatAddMap.put("seen",false);
                chatAddMap.put("timestamp", ServerValue.TIMESTAMP);

                Map chatUserMap = new HashMap();
                chatUserMap.put("Emergency_Chat/"+mCurrentUserId+"/"+mChatUser, chatAddMap);
                chatUserMap.put("Emergency_Chat/"+mChatUser+"/"+mCurrentUserId, chatAddMap);

                mRootRef.updateChildren(chatUserMap, new DatabaseReference.CompletionListener() {
                    @Override
                    public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {

                        if(databaseError!= null){
                            Toast.makeText(EmergencyAlertActivity.this, "Error: "+databaseError.getMessage(), Toast.LENGTH_SHORT).show();

                        }
                    }
                });
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });


    // Retrieving the chat messages into recyclerview
    LoadMessages();
    mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {

            mCurrentPage++;

            //onRefresh remove the current messages from arraylist and load new messages
            arrayList_Message.clear();

            // Load message
            LoadMessages();
        }
    });


}
// Load all messages from database into recyclerView
private void LoadMessages() {

    DatabaseReference messageRef = mRootRef.child("Emergency_Messages").child(mCurrentUserId).child(mChatUser);

    //Query to load message per page i.e. 10
    /*
       per page load 10 message and onRefresh mCurrentpage is increment by 1
       page 1 => load 10 messages (mCurrentPage = 1 then 1*10 =10)
       page 2 => load 20 messages (mCurrentPage = 2 then 2*10 =20) and so on
     */

    Query messageQuery = messageRef.limitToLast(mCurrentPage * TOTAL_ITEMS_TO_LOAD);

    messageQuery.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            emerg_message = dataSnapshot.child("userName").getValue().toString();
            open_location = dataSnapshot.child("open_location").getValue().toString();

            arrayList_Message.add(emerg_message+ "\n"+"\n"+open_location);
            mAdapter.notifyDataSetChanged();

            mMessagesList.scrollToPosition(arrayList_Message.size()-1);

            //when data load completely set refreshing
            mRefreshLayout.setRefreshing(false);
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

private void intCustomBarViewAndSetData() {
    TextView mTitleView = (TextView) findViewById(R.id.custom_bar_title);
    mUserStatus = (TextView) findViewById(R.id.custom_bar_seen);
    mProfileImage = (CircleImageView) findViewById(R.id.custom_bar_image);
    mMessagesList = (RecyclerView) findViewById(R.id.messages_list);

    mMessagesList.setLayoutManager(new LinearLayoutManager(this));
    mRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.message_swipe_layout);
    mMessagesList.setHasFixedSize(true);

    mAdapter = new AlertAdapter(EmergencyAlertActivity.this, arrayList_Message);
    mMessagesList.setAdapter(mAdapter);

    //showing name on toolbar
    mTitleView.setText(userName);
    mTitleView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent profileIntent = new Intent(EmergencyAlertActivity.this, ProfileActivity.class);
            profileIntent.putExtra("user_id", mChatUser);
            startActivity(profileIntent);
        }
    });




}

private void gettingIntentData() {
    Intent intent =getIntent();
    userName = intent.getStringExtra("Username");
    mChatUser = intent.getStringExtra("user_id");


}

}

this is the adapter class

  public class AlertAdapter extends RecyclerView.Adapter<AlertAdapter.MyAlertViewHolder>{


private ArrayList<String> arrayListMessage= new ArrayList<String>();
private Context mcontext;
FirebaseAuth mAuth;
private DatabaseReference mUserDatabase;
private String from_user;
private String emerg_message;
private String emerg_location;
private String message_type;

public AlertAdapter(Context context, ArrayList<String> arrayListMessages){
    this.arrayListMessage = arrayListMessages;
    mcontext = context;
}
@Override
public AlertAdapter.MyAlertViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.message_single_layout, parent,false);

    return new AlertAdapter.MyAlertViewHolder(view);
}

@Override
public void onBindViewHolder(final AlertAdapter.MyAlertViewHolder holder, int position) {

    mAuth = FirebaseAuth.getInstance();
    final String mCurrentUser = mAuth.getCurrentUser().getUid();

   final  String userName = String.valueOf(arrayListMessage.get(position));



    mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(from_user);
    mUserDatabase.child("Emergency_Messages").child("from").child(mCurrentUser).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
             from_user = dataSnapshot.child("from").getValue().toString();
             emerg_message = dataSnapshot.child("userName").getValue().toString();
             emerg_location = dataSnapshot.child("open_location").getValue().toString();

            if (mCurrentUser != from_user){

                holder.textViewMessage.setBackgroundResource(R.drawable.custom_message_bd_white);
                holder.textViewMessage.setGravity(Gravity.LEFT);
                holder.textViewMessage.setTextColor(Color.BLACK);

            } else{
                holder.textViewMessage.setBackgroundResource(R.drawable.custom_message_bg_primary);
                holder.textViewMessage.setGravity(Gravity.RIGHT);
                holder.textViewMessage.setTextColor(Color.WHITE);
            }
            holder.textViewMessage.setText(emerg_message + "\n"+"\n"+emerg_location);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });


    if(message_type.equals("text")) {

        holder.textViewMessage.setText(emerg_message);
        holder.messageImage.setVisibility(View.INVISIBLE);


    } else {

        holder.textViewMessage.setVisibility(View.INVISIBLE);
        Picasso.with(holder.UserProfile.getContext()).load(emerg_message)
                .placeholder(R.drawable.my_profile).into(holder.messageImage);

    }



}

@Override
public int getItemCount() {
    return arrayListMessage.size();
}

class MyAlertViewHolder extends RecyclerView.ViewHolder{

    TextView textViewMessage;
    CircleImageView UserProfile;
    ImageView messageImage;

    public MyAlertViewHolder(View itemView) {
        super(itemView);

        textViewMessage = itemView.findViewById(R.id.messageTextView);
        UserProfile = itemView.findViewById(R.id.message_profile_layout);
        messageImage = (ImageView) itemView.findViewById(R.id.message_image_layout);
    }


}

}

this is the supporting class

public class Alerts {
String userName,open_location ,latitude, longitude,type,from;
long time;
boolean seen;

public Alerts(){
    // for datashnap shot
}
public Alerts(String userName,String open_location,String latitude,String longitude, String type, long time, boolean seen, String from) {
    this.userName = userName;
    this.open_location = open_location;
    this.latitude = latitude;
    this.longitude = longitude;
    this.type = type;
    this.time = time;
    this.seen = seen;
    this.from=from;
}

public String getFrom() {
    return from;
}

public void setFrom(String from) {
    this.from = from;
}
public String getUserName() {
    return userName;
}

public void setUserName(String userName) {
    this.userName = userName;
}

public String getOpen_location() {
    return open_location;
}

public void setOpen_location(String open_location) {
    this.open_location = open_location;
}
public String getLatitude() {
    return latitude;
}

public void setLatitude(String latitude) {
    this.latitude= latitude;
}
public String getLongitude() {
    return longitude;
}

public void setLongitude(String longitude) {
    this.longitude= longitude;
}

public String getType() {
    return type;
}

public void setType(String type) {
    this.type = type;
}

public long getTime() {
    return time;
}

public void setTime(long time) {
    this.time = time;
}

public boolean isSeen() {
    return seen;
}

public void setSeen(boolean seen) {
    this.seen = seen;
}

}

when i try to run the app and open the class that is going to retrieve information in my database i get this error:

01-05 09:54:48.479 29178-29178/? E/Zygote: no v2
01-05 09:54:48.489 29178-29178/? E/SELinux: [DEBUG] get_category: variable 
 seinfo: default sensitivity: NULL, cateogry: NULL
01-05 10:01:23.395 29178-29178/com.rescuex_za.rescuex E/ViewRootImpl: 
sendUserActionEvent() mView == null
01-05 10:01:27.218 29178-29178/com.rescuex_za.rescuex E/ViewRootImpl: 
sendUserActionEvent() mView == null
01-05 10:01:27.689 29178-29178/com.rescuex_za.rescuex E/AndroidRuntime: 

FATAL EXCEPTION: main Process: com.rescuex_za.rescuex, PID: 29178

java.lang.NullPointerException: Can't pass null for argument 'pathString' in 
child()
                                                                        at 
 com.google.firebase.database.DatabaseReference.child(Unknown Source)
                                                                        at 
 com.rescuex_za.rescuex.AlertAdapter.onBindViewHolder(AlertAdapter.java:63)
                                                                        at 
 com.rescuex_za.rescuex.AlertAdapter.onBindViewHolder(AlertAdapter.java:29)
                                                                        at 

  android.support.v7.widget.RecyclerView$Adapter.
 onBindViewHolder(RecyclerView.java:6482)
                                                                        at 
 android.support.v7.widget.RecyclerView$Adapter.
 bindViewHolder(RecyclerView.java:6515)
                                                                        at 
 android.support.v7.widget.RecyclerView$Recycler.
 tryBindViewHolderByDeadline(RecyclerView.java:5458)
                                                                        at 
  android.support.v7.widget.RecyclerView$Recycler.
 tryGetViewHolderForPositionByDeadline(RecyclerView.java:5724)
                                                                        at 
 android.support.v7.widget.RecyclerView$Recycler.
 getViewForPosition(RecyclerView.java:5563)
                                                                        at 
 android.support.v7.widget.RecyclerView$Recycler.
 getViewForPosition(RecyclerView.java:5559)
                                                                        at 

 android.support.v7.widget.LinearLayoutManager$LayoutState.
 next(LinearLayoutManager.java:2229)
                                                                        at 
 android.support.v7.widget.LinearLayoutManager
.layoutChunk(LinearLayoutManager.java:1556)
                                                                        at 
 android.support.v7.widget.LinearLayoutManager
  .fill(LinearLayoutManager.java:1516)
                                                                        at 
 android.support.v7.widget.LinearLayoutManager
 .onLayoutChildren(LinearLayoutManager.java:608)
                                                                        at 
 android.support.v7.widget.RecyclerView
 .dispatchLayoutStep2(RecyclerView.java:3693)
                                                                        at 
  android.support.v7.widget.RecyclerView
  .dispatchLayout(RecyclerView.java:3410)
                                                                        at 
 android.support.v7.widget.RecyclerView
.onLayout(RecyclerView.java:3962)
                                                                        at 
 android.view.View.layout(View.java:16075)
                                                                        at 
 android.view.ViewGroup.layout(ViewGroup.java:5300)
                                                                        at 
 android.support.v4.widget.SwipeRefreshLayout
.onLayout(SwipeRefreshLayout.java:610)
                                                                        at 
 android.view.View.layout(View.java:16075)
                                                                        at android.view.ViewGroup.layout(ViewGroup.java:5300)
                                                                        at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1077)
                                                                        at android.view.View.layout(View.java:16075)
                                                                        at android.view.ViewGroup.layout(ViewGroup.java:5300)
                                                                        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:579)
                                                                        at android.widget.FrameLayout.onLayout(FrameLayout.java:514)
                                                                        at android.view.View.layout(View.java:16075)
                                                                        at android.view.ViewGroup.layout(ViewGroup.java:5300)
                                                                        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)
                                                                        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)
                                                                        at android.widget.LinearLayout.onLayout(LinearLayout.java:1466)
                                                                        at android.view.View.layout(View.java:16075)
                                                                        at android.view.ViewGroup.layout(ViewGroup.java:5300)
                                                                        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:579)
                                                                        at android.widget.FrameLayout.onLayout(FrameLayout.java:514)
                                                                        at android.view.View.layout(View.java:16075)
                                                                        at android.view.ViewGroup.layout(ViewGroup.java:5300)
                                                                        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)
                                                                        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)
                                                                        at android.widget.LinearLayout.onLayout(LinearLayout.java:1466)
                                                                        at android.view.View.layout(View.java:16075)
                                                                        at android.view.ViewGroup.layout(ViewGroup.java:5300)
                                                                        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:579)
                                                                        at android.widget.FrameLayout.onLayout(FrameLayout.java:514)
                                                                        at android.view.View.layout(View.java:16075)
                                                                        at android.view.ViewGroup.layout(ViewGroup.java:5300)
                                                                        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2119)
                                                                        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1873)
                                                                        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1073)
                                                                        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5988)
                                                                        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
                                                                        at android.view.Choreographer.doCallbacks(Choreographer.java:580)
                                                                        at android.view.Choreographer.doFrame(Choreographer.java:550)
                                                                        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
                                                                        at android.os.Handler.handleCallback(Handler.java:739)
                                                                        at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                        at android.os.Loop

I have tried everything I thought would help to retrieve this information and display it the way I want it to be displayed but it keeps on crashing.

Upvotes: 0

Views: 130

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138969

This error: java.lang.NullPointerException: Can't pass null for argument 'pathString' in child() tells you what the problem is. You are passing into child() method an argument chich has the value of null.

This means that you need to check all your variable like: mCurrentUserId, mChatUser and so on for nullity. Make sure all this variables have the correct value.

Upvotes: 1

Related Questions