Open In App

How to Retrieve Blogs on User Profile in Social Media Android App?

Last Updated : 09 Apr, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

This is the Part 16 of “Build a Social Media App on Android Studio” tutorial, and we are going to cover the following functionalities in this article:

  • We are going to Retrieve Blogs Written by users on their profile fragment.
  • As previously we have already added Data of users in Profile Fragment like email, name, and profile pic.
  • Here we are also going to retrieve Blogs Written By the current user on their profile.
  • Let’s See the implementation of showing the blogs written by the current user.

Step By Step Implementation

Step 1: Working with the fragment_profile.xml file

Here we are adding a RecyclerView to view the blogs posted by the current user.

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F1EDED"
    tools:context=".ProfileFragment">
  
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
  
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
  
            <ImageView
                android:id="@+id/cavertv"
                android:layout_width="match_parent"
                android:layout_height="180dp"
                android:background="@color/colorPrimaryDark"
                android:scaleType="fitXY"></ImageView>
  
            <LinearLayout
                android:id="@+id/linearLayout"
                android:layout_width="match_parent"
                android:layout_height="120dp"
                android:layout_marginTop="100dp"
                android:orientation="horizontal">
  
                <ImageView
                    android:id="@+id/avatartv"
                    android:layout_width="120dp"
                    android:layout_height="120dp"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginStart="20dp"
                    android:background="@color/colorPrimary"
                    android:padding="5dp"
                    android:src="@drawable/ic_images" />
  
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="#77000000"
                    android:orientation="vertical">
  
                    <TextView
                        android:id="@+id/nametv"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginStart="5dp"
                        android:layout_marginLeft="5dp"
                        android:layout_marginTop="5dp"
                        android:textColor="@color/colorWhite"
                        android:textSize="25sp" />
  
                    <TextView
                        android:id="@+id/emailtv"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginStart="5dp"
                        android:layout_marginLeft="5dp"
                        android:textColor="@color/colorWhite" />
                </LinearLayout>
  
            </LinearLayout>
  
            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/recyclerposts"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_below="@id/linearLayout" />
  
        </RelativeLayout>
  
    </ScrollView>
  
    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:layout_margin="10dp"
        android:src="@drawable/ic_edit_white" />
  
</RelativeLayout>


Step 2: Working with the ProfileFragment.java file

Here we are going to retrieve value from the Posts node in such a way that uid of the current user is equal to uid of the user having a post

DatabaseReference databaseReference=FirebaseDatabase.getInstance().getReference("Posts");
Query query=databaseReference.orderByChild("uid").equalTo(uid);

Below is the code for the ProfileFragment.java file.

Java




package com.example.socialmediaapp;
  
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
  
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
  
import com.bumptech.glide.Glide;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.StorageReference;
  
import java.util.ArrayList;
import java.util.List;
  
/**
 * A simple {@link Fragment} subclass.
 */
public class ProfileFragment extends Fragment {
  
    private FirebaseAuth firebaseAuth;
    FirebaseUser firebaseUser;
    FirebaseDatabase firebaseDatabase;
    DatabaseReference databaseReference;
    ImageView avatartv, covertv;
    TextView nam, email, phone;
    RecyclerView postrecycle;
    StorageReference storageReference;
    String storagepath = "Users_Profile_Cover_image/";
    FloatingActionButton fab;
    List<ModelPost> posts;
    AdapterPosts adapterPosts;
    String uid;
    ProgressDialog pd;
    private static final int CAMERA_REQUEST = 100;
    private static final int STORAGE_REQUEST = 200;
    private static final int IMAGEPICK_GALLERY_REQUEST = 300;
    private static final int IMAGE_PICKCAMERA_REQUEST = 400;
    String cameraPermission[];
    String storagePermission[];
    Uri imageuri;
  
    public ProfileFragment() {
        // Required empty public constructor
    }
  
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
  
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_profile, container, false);
  
        firebaseAuth = FirebaseAuth.getInstance();
        firebaseUser = firebaseAuth.getCurrentUser();
        firebaseDatabase = FirebaseDatabase.getInstance();
        databaseReference = firebaseDatabase.getReference("Users");
        avatartv = view.findViewById(R.id.avatartv);
        nam = view.findViewById(R.id.nametv);
        email = view.findViewById(R.id.emailtv);
        uid = FirebaseAuth.getInstance().getUid();
        fab = view.findViewById(R.id.fab);
        postrecycle = view.findViewById(R.id.recyclerposts);
        posts = new ArrayList<>();
        pd = new ProgressDialog(getActivity());
        loadMyPosts();
        pd.setCanceledOnTouchOutside(false);
  
        // Retrieving user data from firebase
        Query query = databaseReference.orderByChild("email").equalTo(firebaseUser.getEmail());
        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
                    String name = "" + dataSnapshot1.child("name").getValue();
                    String emaill = "" + dataSnapshot1.child("email").getValue();
                    String image = "" + dataSnapshot1.child("image").getValue();
                    nam.setText(name);
                    email.setText(emaill);
                    try {
                        Glide.with(getActivity()).load(image).into(avatartv);
                    } catch (Exception e) {
  
                    }
                }
            }
  
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
  
            }
        });
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), EditProfilePage.class));
            }
        });
        return view;
    }
  
    private void loadMyPosts() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setReverseLayout(true);
        layoutManager.setStackFromEnd(true);
        postrecycle.setLayoutManager(layoutManager);
  
        DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Posts");
        Query query = databaseReference.orderByChild("uid").equalTo(uid);
        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                posts.clear();
                for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
                    ModelPost modelPost = dataSnapshot1.getValue(ModelPost.class);
                    posts.add(modelPost);
                    adapterPosts = new AdapterPosts(getActivity(), posts);
                    postrecycle.setAdapter(adapterPosts);
                }
            }
  
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
  
                Toast.makeText(getActivity(), databaseError.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
    }
  
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        super.onCreate(savedInstanceState);
    }
}


Output:

For all the drawable file used in this article please refer to this link: https://drive.google.com/drive/folders/1M_knOH_ugCuwSP5nkYzeD4dRp-Honzbe?usp=sharing

Below is the final file structure after performing these operations:

GitHub link for this project: https://github.com/Anni1123/SocialMediaPlatform



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads