create account

Using Firebase Database to create a chat application in Android : Part II by programminghub

View this thread on: hive.blogpeakd.comecency.com
· @programminghub · (edited)
$60.22
Using Firebase Database to create a chat application in Android : Part II
**What will I learn?**

* Selecting image from gallery and displaying the selected image
* Using firebase storage to add image
* Adding image link in firebase database.

**Requirement**

* A PC/laptop with any Operating system such as Linux, Mac OSX, Windows OS
* Preinstalled Android Studio, Android SDK and JDK

*Note: This tutorial is performed in Android Studio on the laptop with Windows 10 Home, 64 bit OS*


**Difficulty**

Anybody with basic knowledge of Android can grasp the tutorial.

**Tutorial Content**

In our previous tutorial we learnt to register user to the firebase using firebase authentication using email/password and we also successfully added user’s data that is email, password in the firebase database. Now in this series we will be adding user profile picture in firebase storage and the link in the database so that we can easily access the user’s profile image in our chatting application. So let us begin.

In order to add profile picture of user we must allow the user to select the picture first. So will will be passing the implicit intent to the gallery and user will select the desired picture. In order to achieve this let us open *activity_signup.xml* and add a ImageView  their.

```
<ImageView
    android:id="@+id/show_user_profile"
    android:src="@drawable/ic_add_profile"
    android:layout_width="match_parent"
    android:layout_height="200dp" />
```

When the user will press on this ImageView we will pass the implicit intent to the gallery of the user’s device and let the user select the desired image. After the user selects the image the selected image will be displayed in the imageview.
In order to pass the implicit intent let us add click listener in the imageview

```
showUserProfile.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent intent = new Intent();
            // Show only images, no videos or anything else
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
            // Always show the chooser (if there are multiple options available)
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);

    }
});
```

This allows users to select the image from the gallery. Here we should also override *startActivityForResult()* method so that we can handle the event once the user picks the image

```
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

        uri = data.getData();

        try {
            bitmap = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), uri);
            // Log.d(TAG, String.valueOf(bitmap));
            Toast.makeText(this, "hey you selected image" + bitmap, Toast.LENGTH_SHORT).show();
            showUserProfile.setImageBitmap(bitmap);
            //ImageView imageView = (ImageView) findViewById(R.id.imageView);
            //imageView.setImageBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
```

Here, when the user picks up his/her desired image then this method is called and if the data is not null we will be receiving the data by data.getData(). This returns the uri of the image and we will then convert this image into bitmap so that we can display it in the ImageView. Let us run this application and see what happens.

https://i.imgur.com/sqmNywK.png

Here initially this screen pops up. Now if the user presses on the image then user will be navigated to select the image. 

https://i.imgur.com/MNJnfZj.png

And finally if the user selects the image then the selected image will be displayed in the imageview along with the Toast message like this:

https://i.imgur.com/JTW9nNt.png

We successfully let our user select the image now we have to upload this particular image to firebase database if the user presses the signup button. In order to upload image to firebase storage we must initially convert our bitmap to byte array so that it will be easy for us to upload the image.

```
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
byte[] data = bytes.toByteArray();

FirebaseStorage.getInstance().getReference().child("simpleChat").child(firebaseUser.getUid())
        .child("profilePic")
        .putBytes(data)
        .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

              
            }
        });
```
Here we are getting the instance of FirebaseStorage and pushing our image in a folder named simpleChat followed by userId and the name of our image will be profilePic. onSuccessListener is called if the upload task is successful. We can get the image url simply by:

```
String url=taskSnapshot.getDownloadUrl().toString();
```

After we get the profile picture url of user then only we will be uploading the user data in the server. We will now be creating our own user so that we can add yhe desired properties on user. If we pushed the fieebaseUser object to server then we will only have fixed no of attributes available. So let us create a new Java class and name it User.java

```
public class User {

    private String emailAddress;
    private String userId;
    private String profilePic;

    public User(String emailAddress, String userId, String profilePic) {
        this.emailAddress = emailAddress;
        this.userId = userId;
        this.profilePic = profilePic;
    }

    public String getEmailAddress() {
        return emailAddress;
    }

    public void setEmailAddress(String emailAddress) {
        this.emailAddress = emailAddress;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getProfilePic() {
        return profilePic;
    }

    public void setProfilePic(String profilePic) {
        this.profilePic = profilePic;
    }
}
```
For now we will only be adding emailAddress, profilePic and userId as we will only require this three 
for now. Now finally we will add the user information to the firebase database by:

```
String url=taskSnapshot.getDownloadUrl().toString();
User user=new User(firebaseUser.getEmail(),firebaseUser.getUid(),url);
FirebaseDatabase.getInstance().getReference().child("simpleChat").child("users")
        .child(firebaseUser.getUid()).setValue(user);
```
Here we are creating adding our own user we created to the firebase database. There are multiple ways of setting value in firebase database. We can simply push string value in the firebase database but the most simple and elegant way is to directly push our object.

The final code of SignUpActivity looks like this:

```
public class SignupActivity extends AppCompatActivity {

    EditText emailEt,passwordEt;
    Button signUp;
    String email,password;
    FirebaseAuth auth;
    ImageView showUserProfile;
    private final Integer PICK_IMAGE_REQUEST=1;
    Bitmap bitmap;
    Uri uri;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signup);
        initView();
        defineView();
        addCLicklistener();
    }

    private void defineView(){
        emailEt=findViewById(R.id.email_et);
        passwordEt=findViewById(R.id.password_et);
        signUp=findViewById(R.id.signup_btn);
        showUserProfile=findViewById(R.id.show_user_profile);

    }
    private void initView(){
        auth=FirebaseAuth.getInstance();

    }

    private boolean validate(){
        boolean isValid=false;
        email=emailEt.getText().toString();
        password=passwordEt.getText().toString();
        if(TextUtils.isEmpty(email))
            emailEt.setError("Required");
        else if(TextUtils.isEmpty(password))
            passwordEt.setError("Required");
        else if(uri==null)
            Toast.makeText(this, "Please select the image", Toast.LENGTH_SHORT).show();
        else
            isValid=true;
        return isValid;
    }
    private void addCLicklistener(){
        signUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(validate())
                    registerUserToDatabse();
            }
        });
        showUserProfile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                    // Show only images, no videos or anything else
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                    // Always show the chooser (if there are multiple options available)
                startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);

            }
        });

    }
    private void registerUserToDatabse(){

        auth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(SignupActivity.this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                Toast.makeText(SignupActivity.this, "succesfully created user::email is:"+ task.getResult().getUser().getEmail(), Toast.LENGTH_SHORT).show();
                addUserInDatabse(task.getResult().getUser());
            }
        });


    }

    private void addUserInDatabse(final FirebaseUser firebaseUser){

        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        byte[] data = bytes.toByteArray();

        FirebaseStorage.getInstance().getReference().child("simpleChat").child(firebaseUser.getUid())
                .child("profilePic")
                .putBytes(data)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        String url=taskSnapshot.getDownloadUrl().toString();
                        User user=new User(firebaseUser.getEmail(),firebaseUser.getUid(),url);
                        FirebaseDatabase.getInstance().getReference().child("simpleChat").child("users")
                                .child(firebaseUser.getUid()).setValue(user);

                    }
                });


    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

            uri = data.getData();

            try {
                bitmap = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), uri);
                // Log.d(TAG, String.valueOf(bitmap));
                Toast.makeText(this, "hey you selected image" + bitmap, Toast.LENGTH_SHORT).show();
                showUserProfile.setImageBitmap(bitmap);
                //ImageView imageView = (ImageView) findViewById(R.id.imageView);
                //imageView.setImageBitmap(bitmap);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
```
Now before running our app please clear the previous authenticated user and clear the database too as we have changed the structure of the database. Go to authentication tab and press on option menu and delete user

https://i.imgur.com/on6btum.png

Clear all the user. Similarly go  on database tab and click on cross button 

https://i.imgur.com/IGgpNrZ.png

After you press on the cross button you will be shown a popup and select delete button there:

https://i.imgur.com/QV2nhGq.png

Now as your database is cleared go to the storage tab and press on getStarted there

https://i.imgur.com/S3TiVUh.png

By this you are enabling you firebase Storage service.
let us run the application:

https://i.imgur.com/5P2KLrg.png

Here we successfully created the user. Now let us view our database:

https://i.imgur.com/bRJMPNX.png

We successfully added user with his/her profile picture. Now we can get the profile picture simply by getting the link.
Now let us view our storage
Firebase stores every child in the form of folders. Here simpleChat is our main parent folder

https://i.imgur.com/6dkbCCa.png

Inside simpleChat folder we have created a new folder that is user_id so that we can identify each user’s picture

https://i.imgur.com/GVBwD9P.png
And finally we have named our image profilePic

https://i.imgur.com/DUJ60En.png

If we clicked the image then we can view our image

https://i.imgur.com/48AMziY.png

Hence here we successfully registered user and added his/her profile picture to the firebase. Now in next session we will be refining our view and also we will be allowing our user to login.

All above codes are available in my Github. Click [here](https://github.com/programminghubb/Chatapp) to download.

**Curriculam**

[Using firebase Database to create a chat application in Android : Part I](https://utopian.io/utopian-io/@programminghub/using-firebase-database-to-create-a-chat-application-in-android-part-i)


<br /><hr/><em>Posted on <a href="https://utopian.io/utopian-io/@programminghub/using-firebase-database-to-create-a-chat-application-in-android-part-ii">Utopian.io -  Rewarding Open Source Contributors</a></em><hr/>
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 142 others
properties (23)
authorprogramminghub
permlinkusing-firebase-database-to-create-a-chat-application-in-android-part-ii
categoryutopian-io
json_metadata"{"community":"utopian","app":"utopian/1.0.0","format":"markdown","repository":{"id":106021222,"name":"android-studio-poet","full_name":"android/android-studio-poet","html_url":"https://github.com/android/android-studio-poet","fork":false,"owner":{"login":"android"}},"pullRequests":[],"platform":"github","type":"tutorials","tags":["utopian-io","android","tutorial","chat-app","firebase"],"users":["drawable","Override","NonNull","programminghub"],"links":["https://github.com/programminghubb/Chatapp","https://utopian.io/utopian-io/@programminghub/using-firebase-database-to-create-a-chat-application-in-android-part-i"],"moderator":{"account":"cha0s0000","time":"2018-03-12T02:23:02.234Z","reviewed":true,"pending":false,"flagged":false},"questions":[{"question":"Is the project description formal?","answers":[{"value":"Yes it’s straight to the point","selected":true,"score":10},{"value":"Need more description ","selected":false,"score":5},{"value":"Not too descriptive","selected":false,"score":0}],"selected":0},{"question":"Is the language / grammar correct?","answers":[{"value":"Yes","selected":true,"score":20},{"value":"A few mistakes","selected":false,"score":10},{"value":"It's pretty bad","selected":false,"score":0}],"selected":0},{"question":"Was the template followed?","answers":[{"value":"Yes","selected":true,"score":10},{"value":"Partially","selected":false,"score":5},{"value":"No","selected":false,"score":0}],"selected":0},{"question":"Is there information about the additional frameworks?","answers":[{"value":"Yes, everything is explained","selected":true,"score":5},{"value":"Yes, but not enough","selected":false,"score":3},{"value":"No details at all","selected":false,"score":0}],"selected":0},{"question":"Is there code in the tutorial?","answers":[{"value":"Yes, and it’s well explained","selected":true,"score":5},{"value":"Yes, but no explanation","selected":false,"score":3},{"value":"No","selected":false,"score":0}],"selected":0},{"question":"Is the tutorial explains technical aspects well enough?","answers":[{"value":"Yes, it teaches how and why about technical aspects","selected":true,"score":5},{"value":"Yes, but it’s not good/enough","selected":false,"score":3},{"value":"No, it explains poorly","selected":false,"score":0}],"selected":0},{"question":"Is the tutorial general and dense enough?","answers":[{"value":"Yes, it’s general and dense","selected":true,"score":5},{"value":"Kinda, it might be more generalized","selected":false,"score":3},{"value":"No, it’s sliced unnecessarily to keep part number high","selected":false,"score":0}],"selected":0},{"question":"Is there an outline for the tutorial content at the beginning of the post","answers":[{"value":"Yes, there is a well prepared outline in “What will I learn?” or another outline section","selected":true,"score":5},{"value":"Yes, but there is no proper listing for every step of the tutorial or it’s not detailed enough","selected":false,"score":3},{"value":"No, there is no outline for the steps.","selected":false,"score":0}],"selected":0},{"question":"Is the visual content of good quality?","answers":[{"value":"Yes","selected":true,"score":5},{"value":"Yes, but bad quality","selected":false,"score":3},{"value":"No","selected":false,"score":0}],"selected":0},{"question":"Is this a tutorial series?","answers":[{"value":"Yes","selected":true,"score":5},{"value":"Yes, but first part","selected":false,"score":3},{"value":"No","selected":false,"score":0}],"selected":0},{"question":"Is the tutorial post structured?","answers":[{"value":"Yes","selected":true,"score":5},{"value":"Not so good","selected":false,"score":3},{"value":"No","selected":false,"score":0}],"selected":0}],"score":89}"
created2018-03-11 19:12:51
last_update2018-03-12 02:23:09
depth0
children2
last_payout2018-03-18 19:12:51
cashout_time1969-12-31 23:59:59
total_payout_value42.398 HBD
curator_payout_value17.817 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length13,819
author_reputation6,190,820,765,528
root_title"Using Firebase Database to create a chat application in Android : Part II"
beneficiaries
0.
accountutopian.pay
weight2,500
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id43,761,944
net_rshares22,836,842,867,244
author_curate_reward""
vote details (206)
@cha0s0000 ·
Thank you for the contribution. It has been approved.

You can contact us on [Discord](https://discord.gg/uTyJkNm).
**[[utopian-moderator]](https://utopian.io/moderators)**
properties (22)
authorcha0s0000
permlinkre-programminghub-using-firebase-database-to-create-a-chat-application-in-android-part-ii-20180312t022321999z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"utopian","app":"utopian/1.0.0"}
created2018-03-12 02:23:24
last_update2018-03-12 02:23:24
depth1
children0
last_payout2018-03-19 02:23:24
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length172
author_reputation30,983,518,016,225
root_title"Using Firebase Database to create a chat application in Android : Part II"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id43,814,963
net_rshares0
@utopian-io ·
### Hey @programminghub I am @utopian-io. I have just upvoted you!
#### Achievements
- WOW WOW WOW People loved what you did here. GREAT JOB!
- You have less than 500 followers. Just gave you a gift to help you succeed!
- Seems like you contribute quite often. AMAZING!
#### Community-Driven Witness!
I am the first and only Steem Community-Driven Witness. <a href="https://discord.gg/zTrEMqB">Participate on Discord</a>. Lets GROW TOGETHER!
- <a href="https://v2.steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1">Vote for my Witness With SteemConnect</a>
- <a href="https://v2.steemconnect.com/sign/account-witness-proxy?proxy=utopian-io&approve=1">Proxy vote to Utopian Witness with SteemConnect</a>
- Or vote/proxy on <a href="https://steemit.com/~witnesses">Steemit Witnesses</a>

[![mooncryption-utopian-witness-gif](https://steemitimages.com/DQmYPUuQRptAqNBCQRwQjKWAqWU3zJkL3RXVUtEKVury8up/mooncryption-s-utopian-io-witness-gif.gif)](https://steemit.com/~witnesses)

**Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x**
properties (22)
authorutopian-io
permlinkre-programminghub-using-firebase-database-to-create-a-chat-application-in-android-part-ii-20180312t114833638z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"utopian","app":"utopian/1.0.0"}
created2018-03-12 11:48:33
last_update2018-03-12 11:48:33
depth1
children0
last_payout2018-03-19 11:48:33
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,147
author_reputation152,955,367,999,756
root_title"Using Firebase Database to create a chat application in Android : Part II"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id43,890,370
net_rshares0