AndroidJSon https://androidjson.com Advanced Android Development Tutorials for beginners Sun, 25 Jun 2017 05:21:58 +0000 en-US hourly 1 https://wordpress.org/?v=4.9.3 https://androidjson.com/wp-content/uploads/2016/12/cropped-logo4-32x32.png AndroidJSon https://androidjson.com 32 32 Retrieve Uploaded Images from Firebase Storage Show in RecyclerView https://androidjson.com/retrieve-stored-images-firebase-storage/ https://androidjson.com/retrieve-stored-images-firebase-storage/#respond Sun, 25 Jun 2017 05:19:17 +0000 https://androidjson.com/?p=565 How to display images stored in Firebase storage along with image name stored in real time database, inside RecyclerView CardView example tutorial. This is the most advanced android tutorial, because in this tutorial we would going to fetch all the uploaded images along with their names which is also stored inside…

Continue reading

The post Retrieve Uploaded Images from Firebase Storage Show in RecyclerView appeared first on AndroidJSon.

]]>
How to display images stored in Firebase storage along with image name stored in real time database, inside RecyclerView CardView example tutorial.

This is the most advanced android tutorial, because in this tutorial we would going to fetch all the uploaded images along with their names which is also stored inside the Firebase Real time database into the fully custom RecyclerView one by one.

Before getting started Read My Upload Image with Text to Firebase Storage Tutorial

Please going further in this post you have to read my above mentioned post because this is the second part of current post.

Contents in this project Retrieve Uploaded Images from Firebase Storage :

  1. Create, configure and connect Firebase project to your Android Studio Application.
  2. Read my previous tutorial about Upload Image with Text to Firebase Storage.
  3. Add internet permission in your project.
  4. Add new activity named as DisplayImagesActivity in your project.
  5. Add RecyclerView activity_display_images.xml file which is the main layout file for DisplayImagesActivity .
  6. Create additional new recyclerview_items.xml layout file.
  7. Create RecyclerViewAdapter.java class extends with RecyclerView.Adapter .
  8. Create DatabaseReference, RecyclerView, RecyclerView.Adapter, ProgressDialog, List<ImageUploadInfo> list objects in DisplayImagesActivity . You can find ImageUploadInfo.java class in our previous mentioned tutorial.
  9. Assign Id and customizing the RecyclerView in DisplayImagesActivity.
  10. Showing the Progress dialog in DisplayImagesActivity.
  11. Assign the Image upload folder path to DatabaseReference object using FirebaseDatabase.getInstance() in DisplayImagesActivity.
  12. Adding addValueEventListener() on DatabaseReference object.
  13.  Add addition button widget in activity_main.xml file .
  14. Create button object and assign id to above button in MainActivity .
  15. Add click listener on DisplayImageButton .

1. Create, configure and connect Firebase project to your Android Studio Application :

1. Open firebase.google.com .

2. Click on Get Started button present on home screen.

Connect Firebase Project

3. Now log in with your Google Gmail ID.

4. Click on Add Project.

5. Enter your project name and select your country then click on CREATE PROJECT .

6. Click on Add firebase to your android app icon.

7. Create a fresh project in Android Studio.

8. Now Add application Package Name, App Nick Name, SHA-1 certificate. To get the SHA-1 certificate from Android Studio read my this tutorial, it is the easiest method to get SHA-1 certificate.

9. Now hit the Register App button.

10. Here you go now your google-services.json file has been successfully generated. Hit the Download google-services.json button to download this file physically into your computer.

11. Next step is to add google-services.json inside your project. So open your project and put( Copy ) google-services.json file inside YourProjectName/app folder. For example my firebase project name is Firebase-AndroidJSon.com then my app folder located is Firebase-AndroidJSon.com/app . Now copy the google-services.json file into app folder like i did in below screenshot.

12. Now open your Project’s build.gradle(Project) file.

13. Add classpath ‘com.google.gms:google-services:3.0.0’ inside dependencies block.

14. Open your project’s build.gradle(Module:app) file.

15. Add compile ‘com.google.firebase:firebase-storage:10.0.1’ , 
compile ‘com.google.firebase:firebase-auth:10.0.1’ , 
compile ‘com.firebase:firebase-client-android:2.4.0’ ,
compile ‘com.google.firebase:firebase-database:10.0.1’ and compile ‘com.github.bumptech.glide:glide:3.7.0’inside dependencies block .

16. Then add apply plugin: ‘com.google.gms.google-services’ at the bottom of the page.

17. Now finally add below packagingOptions just bottom of buildTypes block like i did.

packagingOptions{
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/LICENSE-FIREBASE.txt'
    exclude 'META-INF/NOTICE'

}

Final Screenshot :

18. Open firebase.google.com , Select your project. Now click on Database -> Rules .

19. Add below rules in it just like i did in above screenshot.

{
 "rules": {
 ".read": true,
 ".write": true
 }
}

20. Click on Storage -> Rules.

21. Add Storage rules like i did. You need to replace my appspot url with yours.

service firebase.storage {
 match /b/fir-imageupload-e9031.appspot.com/o {
 match /{allPaths=**} {
 allow read, write: if true;
 }
 }
}

22. You can find your Appspot url on Storage -> Files.

2. Read my previous tutorial about Upload Image with Text to Firebase Storage.

3. Add internet permission to your project :

Open your project’s AndroidManifest.xml file and copy the below permission inside it. You will find the full AndroidManifest.xml file code at the bottom of this page along with all source code.

<uses-permission android:name="android.permission.INTERNET" />

4. Add new activity named as DisplayImagesActivity in your project.

5. Add RecyclerView activity_display_images.xml file which is the main layout file for DisplayImagesActivity .

<android.support.v7.widget.RecyclerView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/recyclerView"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true">


</android.support.v7.widget.RecyclerView>

6. Create additional new recyclerview_items.xml layout file.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cardview1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    card_view:cardElevation="5dp"
    card_view:contentPadding="5dp"
    card_view:cardCornerRadius="5dp"
    card_view:cardMaxElevation="5dp"
    >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="250dp"
        android:background="#ECEFF1">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="fill_parent"
            android:layout_height="200dp"
            android:src="@mipmap/ic_launcher"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="20dp"
            android:textColor="#000"
            android:text="JSon Image Name"
            android:gravity="center"
            android:id="@+id/ImageNameTextView"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true" />

    </RelativeLayout>

</android.support.v7.widget.CardView>

7. Create RecyclerViewAdapter.java class extends with RecyclerView.Adapter .

package com.androidjson.firebaseuploadimage_androidjsoncom;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.util.List;

/**
 * Created by AndroidJSon.com on 6/18/2017.
 */

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

    Context context;
    List<ImageUploadInfo> MainImageUploadInfoList;

    public RecyclerViewAdapter(Context context, List<ImageUploadInfo> TempList) {

        this.MainImageUploadInfoList = TempList;

        this.context = context;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

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

        ViewHolder viewHolder = new ViewHolder(view);

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        ImageUploadInfo UploadInfo = MainImageUploadInfoList.get(position);

        holder.imageNameTextView.setText(UploadInfo.getImageName());

        //Loading image from Glide library.
        Glide.with(context).load(UploadInfo.getImageURL()).into(holder.imageView);
    }

    @Override
    public int getItemCount() {

        return MainImageUploadInfoList.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        public ImageView imageView;
        public TextView imageNameTextView;

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

            imageView = (ImageView) itemView.findViewById(R.id.imageView);

            imageNameTextView = (TextView) itemView.findViewById(R.id.ImageNameTextView);
        }
    }
}

8. Create DatabaseReference, RecyclerView, RecyclerView.Adapter, ProgressDialog, List<ImageUploadInfo> list objects in DisplayImagesActivity . You can find ImageUploadInfo.java class in our previous mentioned tutorial.

// Creating DatabaseReference.
DatabaseReference databaseReference;

// Creating RecyclerView.
RecyclerView recyclerView;

// Creating RecyclerView.Adapter.
RecyclerView.Adapter adapter ;

// Creating Progress dialog
ProgressDialog progressDialog;

// Creating List of ImageUploadInfo class.
List<ImageUploadInfo> list = new ArrayList<>();

9. Assign Id and customizing the RecyclerView in DisplayImagesActivity.

// Assign id to RecyclerView.
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);

// Setting RecyclerView size true.
recyclerView.setHasFixedSize(true);

// Setting RecyclerView layout as LinearLayout.
recyclerView.setLayoutManager(new LinearLayoutManager(DisplayImagesActivity.this));

10. Showing the Progress dialog in DisplayImagesActivity.

// Assign activity this to progress dialog.
progressDialog = new ProgressDialog(DisplayImagesActivity.this);

// Setting up message in Progress dialog.
progressDialog.setMessage("Loading Images From Firebase.");

// Showing progress dialog.
progressDialog.show();

11. Assign the Image upload folder path to DatabaseReference object using FirebaseDatabase.getInstance() in DisplayImagesActivity.

// Setting up Firebase image upload folder path in databaseReference.
// The path is already defined in MainActivity.
databaseReference = FirebaseDatabase.getInstance().getReference(MainActivity.Database_Path);

12. Adding addValueEventListener() on DatabaseReference object.

// Adding Add Value Event Listener to databaseReference.
databaseReference.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {

        for (DataSnapshot postSnapshot : snapshot.getChildren()) {

            ImageUploadInfo imageUploadInfo = postSnapshot.getValue(ImageUploadInfo.class);

            list.add(imageUploadInfo);
        }

        adapter = new RecyclerViewAdapter(getApplicationContext(), list);

        recyclerView.setAdapter(adapter);

        // Hiding the progress dialog.
        progressDialog.dismiss();
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

        // Hiding the progress dialog.
        progressDialog.dismiss();

    }
});

13. Add addition button widget in activity_main.xml file .

<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:id="@+id/DisplayImagesButton"
    android:layout_below="@+id/ButtonUploadImage"
    android:text="Show All Uploaded Images"/>

14. Create button object and assign id to above button in MainActivity .

// Creating button.
Button DisplayImageButton;

DisplayImageButton = (Button)findViewById(R.id.DisplayImagesButton);

 15. Add click listener on DisplayImageButton in MainActivity.

DisplayImageButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        Intent intent = new Intent(MainActivity.this, DisplayImagesActivity.class);
        startActivity(intent);

    }
});

 16. Final All source code for Upload Image with Text to Firebase Storage Tutorial :

Code for MainActivity.java file.

package com.androidjson.firebaseuploadimage_androidjsoncom;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    // Folder path for Firebase Storage.
    String Storage_Path = "All_Image_Uploads/";

    // Root Database Name for Firebase Database.
    public static final String Database_Path = "All_Image_Uploads_Database";

    // Creating button.
    Button ChooseButton, UploadButton, DisplayImageButton;

    // Creating EditText.
    EditText ImageName ;

    // Creating ImageView.
    ImageView SelectImage;

    // Creating URI.
    Uri FilePathUri;

    // Creating StorageReference and DatabaseReference object.
    StorageReference storageReference;
    DatabaseReference databaseReference;

    // Image request code for onActivityResult() .
    int Image_Request_Code = 7;

    ProgressDialog progressDialog ;

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

        // Assign FirebaseStorage instance to storageReference.
        storageReference = FirebaseStorage.getInstance().getReference();

        // Assign FirebaseDatabase instance with root database name.
        databaseReference = FirebaseDatabase.getInstance().getReference(Database_Path);

        //Assign ID'S to button.
        ChooseButton = (Button)findViewById(R.id.ButtonChooseImage);
        UploadButton = (Button)findViewById(R.id.ButtonUploadImage);

        DisplayImageButton = (Button)findViewById(R.id.DisplayImagesButton);

        // Assign ID's to EditText.
        ImageName = (EditText)findViewById(R.id.ImageNameEditText);

        // Assign ID'S to image view.
        SelectImage = (ImageView)findViewById(R.id.ShowImageView);

        // Assigning Id to ProgressDialog.
        progressDialog = new ProgressDialog(MainActivity.this);

        // Adding click listener to Choose image button.
        ChooseButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // Creating intent.
                Intent intent = new Intent();

                // Setting intent type as image to select image from phone storage.
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Please Select Image"), Image_Request_Code);

            }
        });


        // Adding click listener to Upload image button.
        UploadButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                    // Calling method to upload selected image on Firebase storage.
                    UploadImageFileToFirebaseStorage();

            }
        });


        DisplayImageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(MainActivity.this, DisplayImagesActivity.class);
                startActivity(intent);

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

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

            FilePathUri = data.getData();

            try {

                // Getting selected image into Bitmap.
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), FilePathUri);

                // Setting up bitmap selected image into ImageView.
                SelectImage.setImageBitmap(bitmap);

                // After selecting image change choose button above text.
                ChooseButton.setText("Image Selected");

            }
            catch (IOException e) {

                e.printStackTrace();
            }
        }
    }

    // Creating Method to get the selected image file Extension from File Path URI.
    public String GetFileExtension(Uri uri) {

        ContentResolver contentResolver = getContentResolver();

        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();

        // Returning the file Extension.
        return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri)) ;

    }

    // Creating UploadImageFileToFirebaseStorage method to upload image on storage.
    public void UploadImageFileToFirebaseStorage() {

        // Checking whether FilePathUri Is empty or not.
        if (FilePathUri != null) {

            // Setting progressDialog Title.
            progressDialog.setTitle("Image is Uploading...");

            // Showing progressDialog.
            progressDialog.show();

            // Creating second StorageReference.
            StorageReference storageReference2nd = storageReference.child(Storage_Path + System.currentTimeMillis() + "." + GetFileExtension(FilePathUri));

            // Adding addOnSuccessListener to second StorageReference.
            storageReference2nd.putFile(FilePathUri)
                    .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                            // Getting image name from EditText and store into string variable.
                            String TempImageName = ImageName.getText().toString().trim();

                            // Hiding the progressDialog after done uploading.
                            progressDialog.dismiss();

                            // Showing toast message after done uploading.
                            Toast.makeText(getApplicationContext(), "Image Uploaded Successfully ", Toast.LENGTH_LONG).show();

                            @SuppressWarnings("VisibleForTests")
                            ImageUploadInfo imageUploadInfo = new ImageUploadInfo(TempImageName, taskSnapshot.getDownloadUrl().toString());

                            // Getting image upload ID.
                            String ImageUploadId = databaseReference.push().getKey();

                            // Adding image upload id s child element into databaseReference.
                            databaseReference.child(ImageUploadId).setValue(imageUploadInfo);
                        }
                    })
                    // If something goes wrong .
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception exception) {

                            // Hiding the progressDialog.
                            progressDialog.dismiss();

                            // Showing exception erro message.
                            Toast.makeText(MainActivity.this, exception.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    })

                    // On progress change upload time.
                    .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {

                            // Setting progressDialog Title.
                            progressDialog.setTitle("Image is Uploading...");

                        }
                    });
        }
        else {

            Toast.makeText(MainActivity.this, "Please Select Image or Add Image Name", Toast.LENGTH_LONG).show();

        }
    }


}

Code for activity_main.xml layout file.

<?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"
    tools:context="com.androidjson.firebaseuploadimage_androidjsoncom.MainActivity"
    android:layout_margin="20dp">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Firebase Image Upload Tutorial"
        android:id="@+id/textview"
        android:textStyle="bold"
        android:textSize="20dp"
        android:gravity="center"
        android:layout_marginTop="20dp"/>

    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="150dp"
        android:id="@+id/ShowImageView"
        android:layout_below="@+id/textview"
        android:layout_marginTop="20dp"/>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/ButtonChooseImage"
        android:layout_below="@+id/ShowImageView"
        android:layout_marginTop="20dp"
        android:text="Choose Image"/>

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/ImageNameEditText"
        android:layout_below="@+id/ButtonChooseImage"
        android:layout_marginTop="20dp"
        android:hint="Enter Image Name Here"
        android:gravity="center"/>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/ButtonUploadImage"
        android:layout_below="@+id/ImageNameEditText"
        android:layout_marginTop="20dp"
        android:text="Upload image to Firebase Storage"/>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:id="@+id/DisplayImagesButton"
        android:layout_below="@+id/ButtonUploadImage"
        android:text="Show All Uploaded Images"/>

</RelativeLayout>

Code for DisplayImagesActivity.java file.

package com.androidjson.firebaseuploadimage_androidjsoncom;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

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.ValueEventListener;

import java.util.ArrayList;
import java.util.List;

public class DisplayImagesActivity extends AppCompatActivity {

    // Creating DatabaseReference.
    DatabaseReference databaseReference;

    // Creating RecyclerView.
    RecyclerView recyclerView;

    // Creating RecyclerView.Adapter.
    RecyclerView.Adapter adapter ;

    // Creating Progress dialog
    ProgressDialog progressDialog;

    // Creating List of ImageUploadInfo class.
    List<ImageUploadInfo> list = new ArrayList<>();


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

        // Assign id to RecyclerView.
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);

        // Setting RecyclerView size true.
        recyclerView.setHasFixedSize(true);

        // Setting RecyclerView layout as LinearLayout.
        recyclerView.setLayoutManager(new LinearLayoutManager(DisplayImagesActivity.this));

        // Assign activity this to progress dialog.
        progressDialog = new ProgressDialog(DisplayImagesActivity.this);

        // Setting up message in Progress dialog.
        progressDialog.setMessage("Loading Images From Firebase.");

        // Showing progress dialog.
        progressDialog.show();

        // Setting up Firebase image upload folder path in databaseReference.
        // The path is already defined in MainActivity.
        databaseReference = FirebaseDatabase.getInstance().getReference(MainActivity.Database_Path);

        // Adding Add Value Event Listener to databaseReference.
        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {

                for (DataSnapshot postSnapshot : snapshot.getChildren()) {

                    ImageUploadInfo imageUploadInfo = postSnapshot.getValue(ImageUploadInfo.class);

                    list.add(imageUploadInfo);
                }

                adapter = new RecyclerViewAdapter(getApplicationContext(), list);

                recyclerView.setAdapter(adapter);

                // Hiding the progress dialog.
                progressDialog.dismiss();
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

                // Hiding the progress dialog.
                progressDialog.dismiss();

            }
        });

    }
}

Code for activity_display_images.xml layout file.

<?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"
    tools:context="com.androidjson.firebaseuploadimage_androidjsoncom.DisplayImagesActivity">

    <android.support.v7.widget.RecyclerView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/recyclerView"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true">


    </android.support.v7.widget.RecyclerView>

</RelativeLayout>

Code for ImageUploadInfo.java file.

package com.androidjson.firebaseuploadimage_androidjsoncom;

/**
 * Created by AndroidJSon.com on 6/10/2017.
 */


public class ImageUploadInfo {

    public String imageName;

    public String imageURL;

    public ImageUploadInfo() {

    }

    public ImageUploadInfo(String name, String url) {

        this.imageName = name;
        this.imageURL= url;
    }

    public String getImageName() {
        return imageName;
    }

    public String getImageURL() {
        return imageURL;
    }

}

Code for RecyclerViewAdapter.java file.

package com.androidjson.firebaseuploadimage_androidjsoncom;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.util.List;

/**
 * Created by AndroidJSon.com on 6/18/2017.
 */

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

    Context context;
    List<ImageUploadInfo> MainImageUploadInfoList;

    public RecyclerViewAdapter(Context context, List<ImageUploadInfo> TempList) {

        this.MainImageUploadInfoList = TempList;

        this.context = context;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

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

        ViewHolder viewHolder = new ViewHolder(view);

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        ImageUploadInfo UploadInfo = MainImageUploadInfoList.get(position);

        holder.imageNameTextView.setText(UploadInfo.getImageName());

        //Loading image from Glide library.
        Glide.with(context).load(UploadInfo.getImageURL()).into(holder.imageView);
    }

    @Override
    public int getItemCount() {

        return MainImageUploadInfoList.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        public ImageView imageView;
        public TextView imageNameTextView;

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

            imageView = (ImageView) itemView.findViewById(R.id.imageView);

            imageNameTextView = (TextView) itemView.findViewById(R.id.ImageNameTextView);
        }
    }
}

Code for recyclerview_items.xml file.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cardview1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    card_view:cardElevation="5dp"
    card_view:contentPadding="5dp"
    card_view:cardCornerRadius="5dp"
    card_view:cardMaxElevation="5dp"
    >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="250dp"
        android:background="#ECEFF1">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="fill_parent"
            android:layout_height="200dp"
            android:src="@mipmap/ic_launcher"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="20dp"
            android:textColor="#000"
            android:text="JSon Image Name"
            android:gravity="center"
            android:id="@+id/ImageNameTextView"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true" />

    </RelativeLayout>

</android.support.v7.widget.CardView>

Code for AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidjson.firebaseuploadimage_androidjsoncom">

<uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".DisplayImagesActivity"></activity>
    </application>

</manifest>

Screenshots:

Download Code

The post Retrieve Uploaded Images from Firebase Storage Show in RecyclerView appeared first on AndroidJSon.

]]>
https://androidjson.com/retrieve-stored-images-firebase-storage/feed/ 0
Android Upload Image with Text to Firebase Storage Tutorial https://androidjson.com/upload-image-to-firebase-storage/ https://androidjson.com/upload-image-to-firebase-storage/#respond Sat, 17 Jun 2017 01:41:15 +0000 https://androidjson.com/?p=545 How to select image from mobile phone’s storage or gallery and upload to online Firebase storage along with Image Name text and store image name into Firebase real time database. Firebase gives us 5 GB of free space to upload Image, PDF, DOC etc files with 1 GB/Day downloading limit.…

Continue reading

The post Android Upload Image with Text to Firebase Storage Tutorial appeared first on AndroidJSon.

]]>
How to select image from mobile phone’s storage or gallery and upload to online Firebase storage along with Image Name text and store image name into Firebase real time database.

Firebase gives us 5 GB of free space to upload Image, PDF, DOC etc files with 1 GB/Day downloading limit. This is good for starter android apps. You can use Firebase Storage to upload and store your app’s images and also to upload your personal files.

So in this tutorial we would going Create an android application which would upload the selected image from phone’s storage to online Firebase Storage and store image URL with image name into Firebase real time database with unique ID, So they can be access again via JSon format.

Contents in this project Upload Image with Text to Firebase Storage :

  1. Start a new android application project.
  2. Create, configure and connect Firebase project to your Android Studio Application.
  3. Add internet permission.
  4. Add one TextView, one ImageView, One EditText and two Buttons in activity_main.xml layout file.
  5. Creating two String variables Storage_Path and Database_Path in MainActivity .
  6. Creating Button, EditText, ImageView, Uri, StorageReference, DatabaseReference, ProgressDialog and int Image_Request_Code.
  7. Assign FirebaseStorage instance to storageReference object.
  8. Assign FirebaseDatabase instance with root database name.
  9. Assign ID’s to all.
  10. Adding click listener to ChooseButton.
  11. Inside the ChooseButton click listener Add Intent open Storage Image Picker code.
  12. Add onActivityResult() override method.
  13. Creating GetFileExtension() method.
  14. Creating UploadImageFileToFirebaseStorage() method.
  15. Adding click listener to UploadButton.
  16. Inside the UploadButton, call UploadImageFileToFirebaseStorage() method.
  17. Creating new Java class named as ImageUploadInfo .
  18. Final All source code.

1. Start a new android application project.

2. Create, configure and connect Firebase project to your Android Studio Application :-

1. Open firebase.google.com .

2. Click on Get Started button present on home screen.

Connect Firebase Project

3. Now log in with your Google Gmail ID.

4. Click on Add Project.

5. Enter your project name and select your country then click on CREATE PROJECT .

6. Click on Add firebase to your android app icon.

7. Create a fresh project in Android Studio.

8. Now Add application Package Name, App Nick Name, SHA-1 certificate. To get the SHA-1 certificate from Android Studio read my this tutorial, it is the easiest method to get SHA-1 certificate.

9. Now hit the Register App button.

10. Here you go now your google-services.json file has been successfully generated. Hit the Download google-services.json button to download this file physically into your computer.

11. Next step is to add google-services.json inside your project. So open your project and put( Copy ) google-services.json file inside YourProjectName/app folder. For example my firebase project name is Firebase-AndroidJSon.com then my app folder located is Firebase-AndroidJSon.com/app . Now copy the google-services.json file into app folder like i did in below screenshot.

12. Now open your Project’s build.gradle(Project) file.

13. Add classpath ‘com.google.gms:google-services:3.0.0’ inside dependencies block.

14. Open your project’s build.gradle(Module:app) file.

15. Add compile ‘com.google.firebase:firebase-storage:10.0.1’ , 
compile ‘com.google.firebase:firebase-auth:10.0.1’ , 
compile ‘com.firebase:firebase-client-android:2.4.0’ and
compile ‘com.google.firebase:firebase-database:10.0.1’ inside dependencies block .

16. Then add apply plugin: ‘com.google.gms.google-services’ at the bottom of the page.

17. Now finally add below packagingOptions just bottom of buildTypes block like i did.

packagingOptions{
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/LICENSE-FIREBASE.txt'
    exclude 'META-INF/NOTICE'

}

Final Screenshot :

18. Open firebase.google.com , Select your project. Now click on Database -> Rules .

19. Add below rules in it just like i did in above screenshot.

{
 "rules": {
 ".read": true,
 ".write": true
 }
}

20. Click on Storage -> Rules.

21. Add Storage rules like i did. You need to replace my appspot url with yours.

service firebase.storage {
 match /b/fir-imageupload-e9031.appspot.com/o {
 match /{allPaths=**} {
 allow read, write: if true;
 }
 }
}

22. You can find your Appspot url on Storage -> Files.

3. Add internet permission to your project :

Open your project’s AndroidManifest.xml file and copy the below permission inside it. You will find the full AndroidManifest.xml file code at the bottom of this page along with all source code.

<uses-permission android:name="android.permission.INTERNET" />

4. Add one TextView, one ImageView, One EditText and two Buttons in activity_main.xml layout file :

TextView : TextView is used to show just application title on activity screen.

ImageView : ImageView is used to show selected image on activity screen.

EditText :  EditText is used to get name of image from user.

Buttons : One button for upload image, one for select image.

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Firebase Image Upload Tutorial"
    android:id="@+id/textview"
    android:textStyle="bold"
    android:textSize="20dp"
    android:gravity="center"
    android:layout_marginTop="20dp"/>

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="200dp"
    android:id="@+id/ShowImageView"
    android:layout_below="@+id/textview"
    android:layout_marginTop="20dp"/>

<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/ButtonChooseImage"
    android:layout_below="@+id/ShowImageView"
    android:layout_marginTop="20dp"
    android:text="Choose Image"/>

<EditText
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/ImageNameEditText"
    android:layout_below="@+id/ButtonChooseImage"
    android:layout_marginTop="20dp"
    android:hint="Enter Image Name Here"
    android:gravity="center"/>

<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/ButtonUploadImage"
    android:layout_below="@+id/ImageNameEditText"
    android:layout_marginTop="20dp"
    android:text="Upload image to Firebase Storage"/>

5. Creating two String variables Storage_Path and Database_Path in MainActivity .

Storage_Path : Automatically create folder in Firebase Storage to store images.

Database_Path : Create a root database on firebase real time database to store image URL with image name text.

// Folder path for Firebase Storage.
String Storage_Path = "All_Image_Uploads/";

// Root Database Name for Firebase Database.
String Database_Path = "All_Image_Uploads_Database";

6. Creating Button, EditText, ImageView, UriStorageReference, DatabaseReference, ProgressDialog and int Image_Request_Code.

// Creating button.
Button ChooseButton, UploadButton;

// Creating EditText.
EditText ImageName ;

// Creating ImageView.
ImageView SelectImage;

// Creating URI.
Uri FilePathUri;

// Creating StorageReference and DatabaseReference object.
StorageReference storageReference;
DatabaseReference databaseReference;

// Image request code for onActivityResult() .
int Image_Request_Code = 7;

ProgressDialog progressDialog ;

7. Assign FirebaseStorage instance to storageReference object.

storageReference = FirebaseStorage.getInstance().getReference();

8. Assign FirebaseDatabase instance with Root database name.

databaseReference = FirebaseDatabase.getInstance().getReference(Database_Path);

9. Assign ID’s to all.

//Assign ID'S to button.
ChooseButton = (Button)findViewById(R.id.ButtonChooseImage);
UploadButton = (Button)findViewById(R.id.ButtonUploadImage);

// Assign ID's to EditText.
ImageName = (EditText)findViewById(R.id.ImageNameEditText);

// Assign ID'S to image view.
SelectImage = (ImageView)findViewById(R.id.ShowImageView);

// Assigning Id to ProgressDialog.
progressDialog = new ProgressDialog(MainActivity.this);

10. Adding click listener to ChooseButton.

ChooseButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

      
    }
});

11. Inside the ChooseButton click listener Add Intent open Storage Image Picker code.

ChooseButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        // Creating intent.
        Intent intent = new Intent();

        // Setting intent type as image to select image from phone storage.
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Please Select Image"), Image_Request_Code);

    }
});

12. Add onActivityResult() override method :

Using onActivityResult() method android developer can get any data back from opened application. So we get the selected image using this method and set selected image into ImageView. After that we would store the image path into URI.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

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

        FilePathUri = data.getData();

        try {

            // Getting selected image into Bitmap.
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), FilePathUri);

            // Setting up bitmap selected image into ImageView.
            SelectImage.setImageBitmap(bitmap);

            // After selecting image change choose button above text.
            ChooseButton.setText("Image Selected");

        }
        catch (IOException e) {

            e.printStackTrace();
        }
    }
}

13. Creating GetFileExtension() method.

// Creating Method to get the selected image file Extension from File Path URI.
public String GetFileExtension(Uri uri) {

    ContentResolver contentResolver = getContentResolver();

    MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();

    // Returning the file Extension.
    return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri)) ;

}

14. Creating UploadImageFileToFirebaseStorage() method.

// Creating UploadImageFileToFirebaseStorage method to upload image on storage.
public void UploadImageFileToFirebaseStorage() {

    // Checking whether FilePathUri Is empty or not.
    if (FilePathUri != null) {

        // Setting progressDialog Title.
        progressDialog.setTitle("Image is Uploading...");

        // Showing progressDialog.
        progressDialog.show();

        // Creating second StorageReference.
        StorageReference storageReference2nd = storageReference.child(Storage_Path + System.currentTimeMillis() + "." + GetFileExtension(FilePathUri));

        // Adding addOnSuccessListener to second StorageReference.
        storageReference2nd.putFile(FilePathUri)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                        // Getting image name from EditText and store into string variable.
                        String TempImageName = ImageName.getText().toString().trim();

                        // Hiding the progressDialog after done uploading.
                        progressDialog.dismiss();

                        // Showing toast message after done uploading.
                        Toast.makeText(getApplicationContext(), "Image Uploaded Successfully ", Toast.LENGTH_LONG).show();

                        @SuppressWarnings("VisibleForTests")
                        ImageUploadInfo imageUploadInfo = new ImageUploadInfo(TempImageName, taskSnapshot.getDownloadUrl().toString());

                        // Getting image upload ID.
                        String ImageUploadId = databaseReference.push().getKey();

                        // Adding image upload id s child element into databaseReference.
                        databaseReference.child(ImageUploadId).setValue(imageUploadInfo);
                    }
                })
                // If something goes wrong .
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception exception) {

                        // Hiding the progressDialog.
                        progressDialog.dismiss();

                        // Showing exception erro message.
                        Toast.makeText(MainActivity.this, exception.getMessage(), Toast.LENGTH_LONG).show();
                    }
                })

                // On progress change upload time.
                .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {

                        // Setting progressDialog Title.
                        progressDialog.setTitle("Image is Uploading...");

                    }
                });
    }
    else {

        Toast.makeText(MainActivity.this, "Please Select Image or Add Image Name", Toast.LENGTH_LONG).show();

    }
}

15. Adding click listener to UploadButton.

UploadButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

    }
});

16. Inside the UploadButton, call UploadImageFileToFirebaseStorage() method.

UploadButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

            // Calling method to upload selected image on Firebase storage.
            UploadImageFileToFirebaseStorage();

    }
});

17. Creating new Java class named as ImageUploadInfo .

package com.androidjson.firebaseuploadimage_androidjsoncom;

/**
 * Created by AndroidJSon.com on 6/10/2017.
 */


public class ImageUploadInfo {

    public String imageName;

    public String imageURL;

    public ImageUploadInfo() {

    }

    public ImageUploadInfo(String name, String url) {

        this.imageName = name;
        this.imageURL= url;
    }

    public String getImageName() {
        return imageName;
    }

    public String getImageURL() {
        return imageURL;
    }

}

18. Final All source code for Upload Image with Text to Firebase Storage Tutorial :

Code for MainActivity.java file.

package com.androidjson.firebaseuploadimage_androidjsoncom;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    // Folder path for Firebase Storage.
    String Storage_Path = "All_Image_Uploads/";

    // Root Database Name for Firebase Database.
    String Database_Path = "All_Image_Uploads_Database";

    // Creating button.
    Button ChooseButton, UploadButton;

    // Creating EditText.
    EditText ImageName ;

    // Creating ImageView.
    ImageView SelectImage;

    // Creating URI.
    Uri FilePathUri;

    // Creating StorageReference and DatabaseReference object.
    StorageReference storageReference;
    DatabaseReference databaseReference;

    // Image request code for onActivityResult() .
    int Image_Request_Code = 7;

    ProgressDialog progressDialog ;

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

        // Assign FirebaseStorage instance to storageReference.
        storageReference = FirebaseStorage.getInstance().getReference();

        // Assign FirebaseDatabase instance with root database name.
        databaseReference = FirebaseDatabase.getInstance().getReference(Database_Path);

        //Assign ID'S to button.
        ChooseButton = (Button)findViewById(R.id.ButtonChooseImage);
        UploadButton = (Button)findViewById(R.id.ButtonUploadImage);

        // Assign ID's to EditText.
        ImageName = (EditText)findViewById(R.id.ImageNameEditText);

        // Assign ID'S to image view.
        SelectImage = (ImageView)findViewById(R.id.ShowImageView);

        // Assigning Id to ProgressDialog.
        progressDialog = new ProgressDialog(MainActivity.this);

        // Adding click listener to Choose image button.
        ChooseButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // Creating intent.
                Intent intent = new Intent();

                // Setting intent type as image to select image from phone storage.
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Please Select Image"), Image_Request_Code);

            }
        });


        // Adding click listener to Upload image button.
        UploadButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                    // Calling method to upload selected image on Firebase storage.
                    UploadImageFileToFirebaseStorage();

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

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

            FilePathUri = data.getData();

            try {

                // Getting selected image into Bitmap.
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), FilePathUri);

                // Setting up bitmap selected image into ImageView.
                SelectImage.setImageBitmap(bitmap);

                // After selecting image change choose button above text.
                ChooseButton.setText("Image Selected");

            }
            catch (IOException e) {

                e.printStackTrace();
            }
        }
    }

    // Creating Method to get the selected image file Extension from File Path URI.
    public String GetFileExtension(Uri uri) {

        ContentResolver contentResolver = getContentResolver();

        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();

        // Returning the file Extension.
        return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri)) ;

    }

    // Creating UploadImageFileToFirebaseStorage method to upload image on storage.
    public void UploadImageFileToFirebaseStorage() {

        // Checking whether FilePathUri Is empty or not.
        if (FilePathUri != null) {

            // Setting progressDialog Title.
            progressDialog.setTitle("Image is Uploading...");

            // Showing progressDialog.
            progressDialog.show();

            // Creating second StorageReference.
            StorageReference storageReference2nd = storageReference.child(Storage_Path + System.currentTimeMillis() + "." + GetFileExtension(FilePathUri));

            // Adding addOnSuccessListener to second StorageReference.
            storageReference2nd.putFile(FilePathUri)
                    .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                            // Getting image name from EditText and store into string variable.
                            String TempImageName = ImageName.getText().toString().trim();

                            // Hiding the progressDialog after done uploading.
                            progressDialog.dismiss();

                            // Showing toast message after done uploading.
                            Toast.makeText(getApplicationContext(), "Image Uploaded Successfully ", Toast.LENGTH_LONG).show();

                            @SuppressWarnings("VisibleForTests")
                            ImageUploadInfo imageUploadInfo = new ImageUploadInfo(TempImageName, taskSnapshot.getDownloadUrl().toString());

                            // Getting image upload ID.
                            String ImageUploadId = databaseReference.push().getKey();

                            // Adding image upload id s child element into databaseReference.
                            databaseReference.child(ImageUploadId).setValue(imageUploadInfo);
                        }
                    })
                    // If something goes wrong .
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception exception) {

                            // Hiding the progressDialog.
                            progressDialog.dismiss();

                            // Showing exception erro message.
                            Toast.makeText(MainActivity.this, exception.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    })

                    // On progress change upload time.
                    .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {

                            // Setting progressDialog Title.
                            progressDialog.setTitle("Image is Uploading...");

                        }
                    });
        }
        else {

            Toast.makeText(MainActivity.this, "Please Select Image or Add Image Name", Toast.LENGTH_LONG).show();

        }
    }


}

Code for activity_main.xml layout file.

<?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"
    tools:context="com.androidjson.firebaseuploadimage_androidjsoncom.MainActivity"
    android:layout_margin="20dp">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Firebase Image Upload Tutorial"
        android:id="@+id/textview"
        android:textStyle="bold"
        android:textSize="20dp"
        android:gravity="center"
        android:layout_marginTop="20dp"/>

    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="200dp"
        android:id="@+id/ShowImageView"
        android:layout_below="@+id/textview"
        android:layout_marginTop="20dp"/>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/ButtonChooseImage"
        android:layout_below="@+id/ShowImageView"
        android:layout_marginTop="20dp"
        android:text="Choose Image"/>

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/ImageNameEditText"
        android:layout_below="@+id/ButtonChooseImage"
        android:layout_marginTop="20dp"
        android:hint="Enter Image Name Here"
        android:gravity="center"/>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/ButtonUploadImage"
        android:layout_below="@+id/ImageNameEditText"
        android:layout_marginTop="20dp"
        android:text="Upload image to Firebase Storage"/>

</RelativeLayout>

Code for AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidjson.firebaseuploadimage_androidjsoncom">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Screenshots :

Firebase Storage

Download Code

The post Android Upload Image with Text to Firebase Storage Tutorial appeared first on AndroidJSon.

]]>
https://androidjson.com/upload-image-to-firebase-storage/feed/ 0
Android Firebase User Login Authentication with Email Password Tutorial https://androidjson.com/firebase-user-login-authentication/ https://androidjson.com/firebase-user-login-authentication/#respond Fri, 09 Jun 2017 07:45:41 +0000 https://androidjson.com/?p=525 How to create user login activity with Firebase real time database to sign in using registered Email, Password and Redirect to Profile activity. Hello Guys are, In our last tutorial we have learn about Email Registration with Firebase. This tutorial is the second part of that tutorial. In this tutorial…

Continue reading

The post Android Firebase User Login Authentication with Email Password Tutorial appeared first on AndroidJSon.

]]>
How to create user login activity with Firebase real time database to sign in using registered Email, Password and Redirect to Profile activity.

Hello Guys are, In our last tutorial we have learn about Email Registration with Firebase. This tutorial is the second part of that tutorial. In this tutorial we would going to implement Firebase User Login Authentication in our android app.

Before going further please read my previous tutorial about Android Firebase  User Email Registration Authentication. I personally recommended this tutorial for every developer who is going to implement Firebase Login in their application. Because there is no Login without Registration. So let’s get started .

Project Description( Must Read ) : In this tutorial there are three activities with three different layout files.

Activity in this project :

  1. MainActivity.java :- In MainActivity file we have performing the user Registration functionality.
  2. LoginActivity.java  :- In LoginActivity file we have performing the user Login functionality.
  3. UserProfileActivity.java :- In UserProfileActivity file we have showing the logged in user Email with Log out button.

Layout files in this project :

  1. activity_main.xml 
  2. activity_login.xml
  3. activity_user_profile.xml

Contents in this project Firebase User Login Authentication with Email Password Tutorial :

  1. Start a new android application project.
  2. Create, configure and connect Firebase project to your Android Studio Application.
  3. Add internet permission.
  4. Read my previous tutorial about Registration Authentication.
  5. Adding New Login Activity and User Profile activity in your project.
  6. Adding Two EditText and Two buttons in activity_login.xml file.
  7. Creating EditText, Button, String, Boolean, FirebaseAuth, Progress Dialog objects in LoginActivity.java file.
  8. Assign ID’s to EditText, Button and initialize FirebaseAuth in LoginActivity.java file.
  9. Checking if user already logged in before and not logged out properly LoginActivity.java file.
  10. Adding click listener on Login button LoginActivity.java file.
  11. Creating Function CheckEditTextIsEmptyOrNot() to check EditText is empty or not in LoginActivity.java file.
  12. Calling CheckEditTextIsEmptyOrNot() function inside the button click listener LoginActivity.java file.
  13. Creating function LoginFunction() and inside that create signInWithEmailAndPassword() method with FirebaseAuth object LoginActivity.java file.
  14. Adding If condition in button click listener and call LoginFunction() inside it LoginActivity.java file.
  15. Add 1 TextView and 1 Button in activity_user_profile.xml file.
  16. Creating EditText, Button, FirebaseAuth, FirebaseUser, Progress Dialog objects in UserProfileActivity.java file.
  17. Assign ID’s to EditText, Button and initialize FirebaseAuth in UserProfileActivity.java file.
  18. On activity start check whether there is user previously logged in or not in UserProfileActivity.java file.
  19. Adding firebaseAuth current user info into firebaseUser object in UserProfileActivity.java file.
  20. Getting logged in user email from firebaseUser.getEmail() method and set into TextView in UserProfileActivity.java file.
  21. Adding click listener on logout button in UserProfileActivity.java file.
  22. Complete source code.

1. Start a new android application project.

2. Create, configure and connect Firebase project to your Android Studio Application :-

1. Open firebase.google.com .

2. Click on Get Started button present on home screen.

Connect Firebase Project

3. Now log in with your Google Gmail ID.

4. Click on Add Project.

5. Enter your project name and select your country then click on CREATE PROJECT .

6. Click on Add firebase to your android app icon.

7. Create a fresh project in Android Studio.

8. Now Add application Package Name, App Nick Name, SHA-1 certificate. To get the SHA-1 certificate from Android Studio read my this tutorial, it is the easiest method to get SHA-1 certificate.

9. Now hit the Register App button.

10. Here you go now your google-services.json file has been successfully generated. Hit the Download google-services.json button to download this file physically into your computer.

11. Next step is to add google-services.json inside your project. So open your project and put( Copy ) google-services.json file inside YourProjectName/app folder. For example my firebase project name is Firebase-AndroidJSon.com then my app folder located is Firebase-AndroidJSon.com/app . Now copy the google-services.json file into app folder like i did in below screenshot.

12. Now open your Project’s build.gradle(Project) file.

13. Add classpath ‘com.google.gms:google-services:3.0.0’ inside dependencies block.

14. Open your project’s build.gradle(Module:app) file.

15. Add compile ‘com.google.firebase:firebase-auth:9.2.1’ inside dependencies block .

16. Then add apply plugin: ‘com.google.gms.google-services’ at the bottom of the page.

17. Now finally add below packagingOptions just bottom of buildTypes block like i did.

packagingOptions{
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/LICENSE-FIREBASE.txt'
    exclude 'META-INF/NOTICE'

}

Final Screenshot :

18. Now next step is to Enable Firebase User Email Registration Authentication from Firebase Panel in Authentication section. So click on Authentication -> SIGN-IN-METHOD . Select Email/Password .

login

19. Enable Email/Password From Panel and hit the SAVE button.

3. Add internet permission to your project :

Open your project’s AndroidManifest.xml file and copy the below permission inside it. You will find the full AndroidManifest.xml file code at the bottom of this page along with all source code.

<uses-permission android:name="android.permission.INTERNET" />

4. Read my previous tutorial about Registration Authentication.

5. Adding New Login Activity and User Profile activity in your project : Right click on your Project Package name -> New -> Activity -> Empty Activity. Click on the below image to see it into full large size.

6. Adding Two EditText and Two buttons in activity_login.xml file.

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/textview1"
    android:gravity="center"
    android:textSize="21dp"
    android:textStyle="bold"
    android:text="Firebase Login"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="20dp"/>

<EditText
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:hint="Enter Your Email"
    android:id="@+id/editText_email"
    android:layout_below="@+id/textview1"
    android:layout_marginTop="20dp"/>

<EditText
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:hint="Enter Your Password"
    android:id="@+id/editText_password"
    android:layout_below="@+id/editText_email"
    android:layout_marginTop="20dp"/>

<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Click Here to Login"
    android:id="@+id/button_login"
    android:layout_marginTop="14dp"
    android:layout_below="@+id/editText_password"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="NOT LOG-IN ? SIGN UP FROM HERE"
    android:id="@+id/button_SignUP"
    android:layout_marginTop="20dp"
    android:layout_below="@+id/button_login"/>

7. Creating EditText, Button, String, Boolean, FirebaseAuth, Progress Dialog objects in LoginActivity.java file.

// Creating EditText.
EditText email, password ;

// Creating string to hold values.
String EmailHolder, PasswordHolder;

// Creating buttons.
Button Login,SignUP ;

// Creating Boolean to hold EditText empty true false value.
Boolean EditTextEmptyCheck;

// Creating progress dialog.
ProgressDialog progressDialog;

// Creating FirebaseAuth object.
FirebaseAuth firebaseAuth;

8. Assign ID’s to EditText, Button and initialize FirebaseAuth in LoginActivity.java file.

// Assign ID's to EditText.
email = (EditText)findViewById(R.id.editText_email);
password = (EditText)findViewById(R.id.editText_password);

// Assign ID's to button.
Login = (Button)findViewById(R.id.button_login);
SignUP = (Button)findViewById(R.id.button_SignUP);

progressDialog =  new ProgressDialog(LoginActivity.this);

// Assign FirebaseAuth instance to FirebaseAuth object.
firebaseAuth = FirebaseAuth.getInstance();

9. Checking if user already logged in before and not logged out properly LoginActivity.java file.

if(firebaseAuth.getCurrentUser() != null){

    // Finishing current Login Activity.
    finish();

    // Opening UserProfileActivity .
    Intent intent = new Intent(LoginActivity.this, UserProfileActivity.class);
    startActivity(intent);
}

10. Adding click listener on Login button LoginActivity.java file.

// Adding click listener to login button.
Login.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

    }
});

11. Creating Function CheckEditTextIsEmptyOrNot() to check EditText is empty or not in LoginActivity.java file.

public void CheckEditTextIsEmptyOrNot(){

    // Getting value form Email's EditText and fill into EmailHolder string variable.
    EmailHolder = email.getText().toString().trim();

    // Getting value form Password's EditText and fill into PasswordHolder string variable.
    PasswordHolder = password.getText().toString().trim();

    // Checking Both EditText is empty or not.
    if(TextUtils.isEmpty(EmailHolder) || TextUtils.isEmpty(PasswordHolder))
    {

        // If any of EditText is empty then set value as false.
        EditTextEmptyCheck = false;

    }
    else {

        // If any of EditText is empty then set value as true.
        EditTextEmptyCheck = true ;

    }

}

12. Calling CheckEditTextIsEmptyOrNot() function inside the button click listener LoginActivity.java file.

// Adding click listener to login button.
Login.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        // Calling method CheckEditTextIsEmptyOrNot().
        CheckEditTextIsEmptyOrNot();

    }
});

13. Creating function LoginFunction() and inside that create signInWithEmailAndPassword() method with FirebaseAuth object LoginActivity.java file.

// Creating login function.
public void LoginFunction(){

    // Setting up message in progressDialog.
    progressDialog.setMessage("Please Wait");

    // Showing progressDialog.
    progressDialog.show();

    // Calling  signInWithEmailAndPassword function with firebase object and passing EmailHolder and PasswordHolder inside it.
    firebaseAuth.signInWithEmailAndPassword(EmailHolder, PasswordHolder)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {

                    // If task done Successful.
                    if(task.isSuccessful()){

                        // Hiding the progress dialog.
                        progressDialog.dismiss();

                        // Closing the current Login Activity.
                        finish();


                        // Opening the UserProfileActivity.
                        Intent intent = new Intent(LoginActivity.this, UserProfileActivity.class);
                        startActivity(intent);
                    }
                    else {

                        // Hiding the progress dialog.
                        progressDialog.dismiss();

                        // Showing toast message when email or password not found in Firebase Online database.
                        Toast.makeText(LoginActivity.this, "Email or Password Not found, Please Try Again", Toast.LENGTH_LONG).show();
                    }
                }
            });

}

14. Adding If condition in button click listener and call LoginFunction() inside it LoginActivity.java file.

Login.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        // Calling method CheckEditTextIsEmptyOrNot().
        CheckEditTextIsEmptyOrNot();

        // If  EditTextEmptyCheck == true
        if(EditTextEmptyCheck)
        {

            // If  EditTextEmptyCheck == true then login function called.
            LoginFunction();

        }
        else {

            // If  EditTextEmptyCheck == false then toast display on screen.
            Toast.makeText(LoginActivity.this, "Please Fill All the Fields", Toast.LENGTH_LONG).show();
        }


    }
});

15. Add 1 TextView and 1 Button in activity_user_profile.xml file.

<TextView
    android:id="@+id/user_email"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="30dp"
    android:gravity="center"
    android:textSize="20dp"
    android:textColor="#000"/>

<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/logout"
    android:layout_below="@+id/user_email"
    android:text="Click Here To Logout"
    android:layout_marginTop="30dp"/>

16. Creating EditText, Button, FirebaseAuth, FirebaseUser, Progress Dialog objects in UserProfileActivity.java file.

// Creating button.
Button logout ;

// Creating TextView.
TextView userEmailShow ;

// Creating FirebaseAuth.
FirebaseAuth firebaseAuth ;

// Creating FirebaseAuth.
FirebaseUser firebaseUser;

17. Assign ID’s to EditText, Button and initialize FirebaseAuth in UserProfileActivity.java file.

// Assigning ID's to button and TextView.
logout = (Button)findViewById(R.id.logout);
userEmailShow = (TextView)findViewById(R.id.user_email);

// Adding FirebaseAuth instance to FirebaseAuth object.
firebaseAuth = FirebaseAuth.getInstance();

18. On activity start check whether there is user previously logged in or not in UserProfileActivity.java file.

// On activity start check whether there is user previously logged in or not.
if(firebaseAuth.getCurrentUser() == null){

    // Finishing current Profile activity.
    finish();

    // If user already not log in then Redirect to LoginActivity .
    Intent intent = new Intent(UserProfileActivity.this, LoginActivity.class);
    startActivity(intent);

    // Showing toast message.
    Toast.makeText(UserProfileActivity.this, "Please Log in to continue", Toast.LENGTH_LONG).show();

}

19. Adding firebaseAuth current user info into firebaseUser object in UserProfileActivity.java file.

firebaseUser = firebaseAuth.getCurrentUser();

20. Getting logged in user email from firebaseUser.getEmail() method and set into TextView in UserProfileActivity.java file.

userEmailShow.setText("Successfully Logged In, Your Email = " + firebaseUser.getEmail());

21. Adding click listener on logout button in UserProfileActivity.java file.

// Adding click listener on logout button.
logout.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        // Destroying login season.
        firebaseAuth.signOut();

        // Finishing current User Profile activity.
        finish();

        // Redirect to Login Activity after click on logout button.
        Intent intent = new Intent(UserProfileActivity.this, LoginActivity.class);
        startActivity(intent);

        // Showing toast message on logout.
        Toast.makeText(UserProfileActivity.this, "Logged Out Successfully.", Toast.LENGTH_LONG).show();

    }
});

 22. Complete source code :

Code for MainActivity.java file.

package com.androidjson.firebaseuserloginregistration_androidjsoncom;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.support.annotation.NonNull;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;

public class MainActivity extends AppCompatActivity {

    // Creating EditText .
    EditText email, password ;

    // Creating button.
    Button SignUp, ButtonGoToLoginActivity;

    // Creating string to hold email and password .
    String EmailHolder, PasswordHolder ;

    // Creating Progress dialog.
    ProgressDialog progressDialog;

    // Creating FirebaseAuth object.
    FirebaseAuth firebaseAuth ;

    // Creating Boolean variable that holds EditText is empty or not status.
    Boolean EditTextStatus ;

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

        // Assigning layout email ID and Password ID.
        email = (EditText)findViewById(R.id.EditText_User_EmailID);
        password = (EditText)findViewById(R.id.EditText_User_Password);

        // Assign button layout ID.
        SignUp = (Button)findViewById(R.id.Button_SignUp);
        ButtonGoToLoginActivity = (Button)findViewById(R.id.Button_LoginActivity);

        // Creating object instance.
        firebaseAuth = FirebaseAuth.getInstance();

        progressDialog = new ProgressDialog(MainActivity.this);

        // Adding click listener to Sign Up Button.
        SignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // Calling method to check EditText is empty or no status.
                CheckEditTextIsEmptyOrNot();

                // If EditText is true then this block with execute.
                if(EditTextStatus){

                    // If EditText is not empty than UserRegistrationFunction method will call.
                    UserRegistrationFunction();

                }
                // If EditText is false then this block with execute.
                else {

                    Toast.makeText(MainActivity.this, "Please fill all form fields.", Toast.LENGTH_LONG).show();

                }

            }
        });

        // Adding click listener to ButtonGoToLoginActivity button.
        ButtonGoToLoginActivity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // Finishing current Main Activity.
                finish();

                // Opening the Login Activity using Intent.
                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                startActivity(intent);

            }
        });


    }

    // Creating UserRegistrationFunction
    public void UserRegistrationFunction(){

                // Showing progress dialog at user registration time.
                progressDialog.setMessage("Please Wait, We are Registering Your Data on Server");
                progressDialog.show();

                // Creating createUserWithEmailAndPassword method and pass email and password inside it.
                firebaseAuth.createUserWithEmailAndPassword(EmailHolder, PasswordHolder).
                        addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {
                            @Override
                            public void onComplete(@NonNull Task<AuthResult> task) {

                                // Checking if user is registered successfully.
                                if(task.isSuccessful()){

                                    // If user registered successfully then show this toast message.
                                    Toast.makeText(MainActivity.this,"User Registration Successfully",Toast.LENGTH_LONG).show();

                                    firebaseAuth.signOut();

                                }else{

                                    // If something goes wrong.
                                    Toast.makeText(MainActivity.this,"Something Went Wrong.",Toast.LENGTH_LONG).show();
                                }

                                // Hiding the progress dialog after all task complete.
                                progressDialog.dismiss();

            }
        });

    }

    public void CheckEditTextIsEmptyOrNot(){

        // Getting name and email from EditText and save into string variables.
        EmailHolder = email.getText().toString().trim();
        PasswordHolder = password.getText().toString().trim();

        if(TextUtils.isEmpty(EmailHolder) || TextUtils.isEmpty(PasswordHolder))
        {

            EditTextStatus = false;

        }
        else {

            EditTextStatus = true ;
        }

    }

}

Code for activity_main.xml layout file.

<?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:layout_margin="20dp"
    tools:context="com.androidjson.firebaseuserloginregistration_androidjsoncom.MainActivity">

    <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/textView"
    android:textSize="20dp"
    android:textColor="#000"
    android:text="Firebase User Registration Form"
    android:gravity="center"
    android:layout_marginTop="60dp"
    />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/EditText_User_EmailID"
        android:hint="Enter Your Email Here"
        android:gravity="center"
        android:layout_below="@+id/textView"
        android:layout_marginTop="20dp"
        />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/EditText_User_Password"
        android:hint="Enter Your Password Here"
        android:gravity="center"
        android:inputType="textPassword"
        android:layout_below="@+id/EditText_User_EmailID"
        android:layout_marginTop="20dp"/>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/Button_SignUp"
        android:layout_below="@+id/EditText_User_Password"
        android:text="Click Here To Sign Up"
        android:layout_marginTop="20dp"/>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/Button_LoginActivity"
        android:layout_below="@+id/Button_SignUp"
        android:text="ALREADY SIGN UP ? LOGIN FROM HERE"
        android:layout_marginTop="20dp"/>

    </RelativeLayout>

 

Code for LoginActivity.java file.

package com.androidjson.firebaseuserloginregistration_androidjsoncom;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.annotation.MainThread;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;

public class LoginActivity extends AppCompatActivity {

    // Creating EditText.
    EditText email, password ;

    // Creating string to hold values.
    String EmailHolder, PasswordHolder;

    // Creating buttons.
    Button Login,SignUP ;

    // Creating Boolean to hold EditText empty true false value.
    Boolean EditTextEmptyCheck;

    // Creating progress dialog.
    ProgressDialog progressDialog;

    // Creating FirebaseAuth object.
    FirebaseAuth firebaseAuth;

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

        // Assign ID's to EditText.
        email = (EditText)findViewById(R.id.editText_email);
        password = (EditText)findViewById(R.id.editText_password);

        // Assign ID's to button.
        Login = (Button)findViewById(R.id.button_login);
        SignUP = (Button)findViewById(R.id.button_SignUP);

        progressDialog =  new ProgressDialog(LoginActivity.this);

        // Assign FirebaseAuth instance to FirebaseAuth object.
        firebaseAuth = FirebaseAuth.getInstance();


        // Checking if user already logged in before and not logged out properly.
        if(firebaseAuth.getCurrentUser() != null){

            // Finishing current Login Activity.
            finish();

            // Opening UserProfileActivity .
            Intent intent = new Intent(LoginActivity.this, UserProfileActivity.class);
            startActivity(intent);
        }


        // Adding click listener to login button.
        Login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // Calling method CheckEditTextIsEmptyOrNot().
                CheckEditTextIsEmptyOrNot();

                // If  EditTextEmptyCheck == true
                if(EditTextEmptyCheck)
                {

                    // If  EditTextEmptyCheck == true then login function called.
                    LoginFunction();

                }
                else {

                    // If  EditTextEmptyCheck == false then toast display on screen.
                    Toast.makeText(LoginActivity.this, "Please Fill All the Fields", Toast.LENGTH_LONG).show();
                }


            }
        });

        // Adding click listener to Sign up button.
        SignUP.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // Closing current activity.
                finish();

                // Opening the Main Activity .
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);

            }
        });
    }

    // Creating method to check EditText is empty or not.
    public void CheckEditTextIsEmptyOrNot(){

        // Getting value form Email's EditText and fill into EmailHolder string variable.
        EmailHolder = email.getText().toString().trim();

        // Getting value form Password's EditText and fill into PasswordHolder string variable.
        PasswordHolder = password.getText().toString().trim();

        // Checking Both EditText is empty or not.
        if(TextUtils.isEmpty(EmailHolder) || TextUtils.isEmpty(PasswordHolder))
        {

            // If any of EditText is empty then set value as false.
            EditTextEmptyCheck = false;

        }
        else {

            // If any of EditText is empty then set value as true.
            EditTextEmptyCheck = true ;

        }

    }

    // Creating login function.
    public void LoginFunction(){

        // Setting up message in progressDialog.
        progressDialog.setMessage("Please Wait");

        // Showing progressDialog.
        progressDialog.show();

        // Calling  signInWithEmailAndPassword function with firebase object and passing EmailHolder and PasswordHolder inside it.
        firebaseAuth.signInWithEmailAndPassword(EmailHolder, PasswordHolder)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {

                        // If task done Successful.
                        if(task.isSuccessful()){

                            // Hiding the progress dialog.
                            progressDialog.dismiss();

                            // Closing the current Login Activity.
                            finish();


                            // Opening the UserProfileActivity.
                            Intent intent = new Intent(LoginActivity.this, UserProfileActivity.class);
                            startActivity(intent);
                        }
                        else {

                            // Hiding the progress dialog.
                            progressDialog.dismiss();

                            // Showing toast message when email or password not found in Firebase Online database.
                            Toast.makeText(LoginActivity.this, "Email or Password Not found, Please Try Again", Toast.LENGTH_LONG).show();
                        }
                    }
                });

    }

}

Code for activity_login.xml layout file.

<?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"
    tools:context="com.androidjson.firebaseuserloginregistration_androidjsoncom.LoginActivity"
    android:layout_margin="20dp">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textview1"
        android:gravity="center"
        android:textSize="21dp"
        android:textStyle="bold"
        android:text="Firebase Login"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"/>

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:hint="Enter Your Email"
        android:id="@+id/editText_email"
        android:layout_below="@+id/textview1"
        android:layout_marginTop="20dp"/>

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:hint="Enter Your Password"
        android:id="@+id/editText_password"
        android:layout_below="@+id/editText_email"
        android:layout_marginTop="20dp"/>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Click Here to Login"
        android:id="@+id/button_login"
        android:layout_marginTop="14dp"
        android:layout_below="@+id/editText_password"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="NOT LOG-IN ? SIGN UP FROM HERE"
        android:id="@+id/button_SignUP"
        android:layout_marginTop="20dp"
        android:layout_below="@+id/button_login"/>


</RelativeLayout>

 

Code for UserProfileActivity.java file.

package com.androidjson.firebaseuserloginregistration_androidjsoncom;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class UserProfileActivity extends AppCompatActivity {

    // Creating button.
    Button logout ;

    // Creating TextView.
    TextView userEmailShow ;

    // Creating FirebaseAuth.
    FirebaseAuth firebaseAuth ;

    // Creating FirebaseAuth.
    FirebaseUser firebaseUser;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_profile);

        // Assigning ID's to button and TextView.
        logout = (Button)findViewById(R.id.logout);
        userEmailShow = (TextView)findViewById(R.id.user_email);

        // Adding FirebaseAuth instance to FirebaseAuth object.
        firebaseAuth = FirebaseAuth.getInstance();

        // On activity start check whether there is user previously logged in or not.
        if(firebaseAuth.getCurrentUser() == null){

            // Finishing current Profile activity.
            finish();

            // If user already not log in then Redirect to LoginActivity .
            Intent intent = new Intent(UserProfileActivity.this, LoginActivity.class);
            startActivity(intent);

            // Showing toast message.
            Toast.makeText(UserProfileActivity.this, "Please Log in to continue", Toast.LENGTH_LONG).show();

        }

        // Adding firebaseAuth current user info into firebaseUser object.
        firebaseUser = firebaseAuth.getCurrentUser();

        // Getting logged in user email from firebaseUser.getEmail() method and set into TextView.
        userEmailShow.setText("Successfully Logged In, Your Email = " + firebaseUser.getEmail());

        // Adding click listener on logout button.
        logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // Destroying login season.
                firebaseAuth.signOut();

                // Finishing current User Profile activity.
                finish();

                // Redirect to Login Activity after click on logout button.
                Intent intent = new Intent(UserProfileActivity.this, LoginActivity.class);
                startActivity(intent);

                // Showing toast message on logout.
                Toast.makeText(UserProfileActivity.this, "Logged Out Successfully.", Toast.LENGTH_LONG).show();

            }
        });


    }
}

Code for activity_user_profile.xml layout file.

<?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:padding="20dp"
    tools:context="com.androidjson.firebaseuserloginregistration_androidjsoncom.UserProfileActivity">

    <TextView
        android:id="@+id/user_email"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        android:gravity="center"
        android:textSize="20dp"
        android:textColor="#000"/>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/logout"
        android:layout_below="@+id/user_email"
        android:text="Click Here To Logout"
        android:layout_marginTop="30dp"/>

</RelativeLayout>

 

Code for AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidjson.firebaseuserloginregistration_androidjsoncom">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".LoginActivity" />
        <activity android:name=".UserProfileActivity"></activity>
    </application>

</manifest>

Screenshots :

Download Source Code

The post Android Firebase User Login Authentication with Email Password Tutorial appeared first on AndroidJSon.

]]>
https://androidjson.com/firebase-user-login-authentication/feed/ 0
Android Firebase User Email Registration Authentication Tutorial https://androidjson.com/firebase-registration-authentication/ https://androidjson.com/firebase-registration-authentication/#comments Fri, 02 Jun 2017 11:21:26 +0000 https://androidjson.com/?p=481 How to create user registration app using Firebase Realtime database in Android Studio and register, insert, authenticate android app user with Email and Password. Hello Guys this is another one tutorial regarding to Firebase . As we all know that using firebase we can do many things in the area of Android…

Continue reading

The post Android Firebase User Email Registration Authentication Tutorial appeared first on AndroidJSon.

]]>
How to create user registration app using Firebase Realtime database in Android Studio and register, insert, authenticate android app user with Email and Password.

Hello Guys this is another one tutorial regarding to Firebase . As we all know that using firebase we can do many things in the area of Android Application development. Now with Firebase User Registration Authentication method we can give the facility to our app user to automatic authenticate and register with our app. There is no need to purchase any extra cost web hosting for it and also no server side coding required. Because as we all know Firebase do the rest. So here is the complete step by step tutorial for Android Firebase User Email Registration Authentication Tutorial.

Contents in this project Android Firebase User Registration Authentication Example :-

  1. Start a new android application project.
  2. Create, configure and connect Firebase project to your Android Studio Application.
  3. Add internet permission.
  4. Creating 2 EditText and 1 button in layout file.
  5. Creating EditText, Button, String, Boolean, FirebaseAuth, Progress Dialog objects.
  6.  Assign ID’s to EditText, Button and initialize FirebaseAuth.
  7. Adding Click Listener to button.
  8. Creating Function CheckEditTextIsEmptyOrNot() to check EditText is empty or not.
  9. Calling CheckEditTextIsEmptyOrNot() function inside the button click listener.
  10. Creating function UserRegistrationFunction() and inside that create createUserWithEmailAndPassword() method with FirebaseAuth object.
  11. Adding If condition in button click listener and call UserRegistrationFunction() inside it.
  12. Complete Source Code.

1. Start a new android application project.

2. Create, configure and connect Firebase project to your Android Studio Application :-

1. Open firebase.google.com .

2. Click on Get Started button present on home screen.

Connect Firebase Project

3. Now log in with your Google Gmail ID.

4. Click on Add Project.

5. Enter your project name and select your country then click on CREATE PROJECT .

6. Click on Add firebase to your android app icon.

7. Create a fresh project in Android Studio.

8. Now Add application Package Name, App Nick Name, SHA-1 certificate. To get the SHA-1 certificate from Android Studio read my this tutorial, it is the easiest method to get SHA-1 certificate.

9. Now hit the Register App button.

10. Here you go now your google-services.json file has been successfully generated. Hit the Download google-services.json button to download this file physically into your computer.

11. Next step is to add google-services.json inside your project. So open your project and put( Copy ) google-services.json file inside YourProjectName/app folder. For example my firebase project name is Firebase-AndroidJSon.com then my app folder located is Firebase-AndroidJSon.com/app . Now copy the google-services.json file into app folder like i did in below screenshot.

12. Now open your Project’s build.gradle(Project) file.

13. Add classpath ‘com.google.gms:google-services:3.0.0’ inside dependencies block.

14. Open your project’s build.gradle(Module:app) file.

15. Add compile ‘com.google.firebase:firebase-auth:9.2.1’ inside dependencies block .

16. Then add apply plugin: ‘com.google.gms.google-services’ at the bottom of the page.

17. Now finally add below packagingOptions just bottom of buildTypes block like i did.

packagingOptions{
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/LICENSE-FIREBASE.txt'
    exclude 'META-INF/NOTICE'

}

Final Screenshot :

18. Now next step is to Enable Firebase User Email Registration Authentication from Firebase Panel in Authentication section. So click on Authentication -> SIGN-IN-METHOD . Select Email/Password .

sign_in_method

19. Enable Email/Password From Panel and hit the SAVE button.

3. Add internet permission to your project :

Open your project’s AndroidManifest.xml file and copy the below permission inside it. You will find the full AndroidManifest.xml file code at the bottom of this page along with all source code.

<uses-permission android:name="android.permission.INTERNET" />

4. Creating 2 EditText and 1 button in layout file.

<EditText
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/EditText_User_EmailID"
    android:hint="Enter Your Email Here"
    android:gravity="center"
    android:layout_below="@+id/textView"
    android:layout_marginTop="20dp"
    />

<EditText
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/EditText_User_Password"
    android:hint="Enter Your Password Here"
    android:gravity="center"
    android:inputType="textPassword"
    android:layout_below="@+id/EditText_User_EmailID"/>

<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/Button_SignUp"
    android:layout_below="@+id/EditText_User_Password"
    android:text="Click Here To Sign Up"/>

5. Creating EditText, Button, String, Boolean, FirebaseAuth, Progress Dialog objects in MainActivity.java file.

// Creating EditText .
EditText email, password ;

// Creating button.
Button SignUp ;

// Creating string to hold email and password .
String EmailHolder, PasswordHolder ;

// Creating Progress dialog.
ProgressDialog progressDialog;

// Creating FirebaseAuth object.
FirebaseAuth firebaseAuth ;

// Creating Boolean variable that holds EditText is empty or not status.
Boolean EditTextStatus ;

6.  Assign ID’s to EditText, Button and initialize FirebaseAuth.

/ Assigning layout email ID and Password ID.
email = (EditText)findViewById(R.id.EditText_User_EmailID);
password = (EditText)findViewById(R.id.EditText_User_Password);

// Assign button layout ID.
SignUp = (Button)findViewById(R.id.Button_SignUp);

// Creating object instance.
firebaseAuth = FirebaseAuth.getInstance();

progressDialog = new ProgressDialog(MainActivity.this);

7. Adding Click Listener to button.

// Adding click listener to Sign Up Button.
SignUp.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

    }
});

8. Creating Function CheckEditTextIsEmptyOrNot() to check EditText is empty or not.

public void CheckEditTextIsEmptyOrNot(){

    // Getting name and email from EditText and save into string variables.
    EmailHolder = email.getText().toString().trim();
    PasswordHolder = password.getText().toString().trim();

    if(TextUtils.isEmpty(EmailHolder) || TextUtils.isEmpty(PasswordHolder))
    {

        EditTextStatus = false;

    }
    else {

        EditTextStatus = true ;
    }

}

9. Calling CheckEditTextIsEmptyOrNot() function inside the button click listener.

// Adding click listener to Sign Up Button.
SignUp.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        // Calling method to check EditText is empty or no status.
        CheckEditTextIsEmptyOrNot();

    }
});

10. Creating function UserRegistrationFunction() and inside that create createUserWithEmailAndPassword() method with FirebaseAuth object.

// Creating UserRegistrationFunction
public void UserRegistrationFunction(){

            // Showing progress dialog at user registration time.
            progressDialog.setMessage("Please Wait, We are Registering Your Data on Server");
            progressDialog.show();

            // Creating createUserWithEmailAndPassword method and pass email and password inside it.
            firebaseAuth.createUserWithEmailAndPassword(EmailHolder, PasswordHolder).
                    addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {

                            // Checking if user is registered successfully.
                            if(task.isSuccessful()){

                                // If user registered successfully then show this toast message.
                                Toast.makeText(MainActivity.this,"User Registration Successfully",Toast.LENGTH_LONG).show();

                            }else{

                                // If something goes wrong.
                                Toast.makeText(MainActivity.this,"Something Went Wrong.",Toast.LENGTH_LONG).show();
                            }

                            // Hiding the progress dialog after all task complete.
                            progressDialog.dismiss();

        }
    });

}

11. Adding If condition in button click listener and call UserRegistrationFunction() inside it.

// Adding click listener to Sign Up Button.
SignUp.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        // Calling method to check EditText is empty or no status.
        CheckEditTextIsEmptyOrNot();

        // If EditText is true then this block with execute.
        if(EditTextStatus){

            // If EditText is not empty than UserRegistrationFunction method will call.
            UserRegistrationFunction();

        }
        // If EditText is false then this block with execute.
        else {

            Toast.makeText(MainActivity.this, "Please fill all form fields.", Toast.LENGTH_LONG).show();

        }

    }
});

 12. Complete Source Code :-

Code for MainActivity.java file.

package com.androidjson.firebaseuserloginregistration_androidjsoncom;

import android.support.v7.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.support.annotation.NonNull;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;

public class MainActivity extends AppCompatActivity {

    // Creating EditText .
    EditText email, password ;

    // Creating button.
    Button SignUp ;

    // Creating string to hold email and password .
    String EmailHolder, PasswordHolder ;

    // Creating Progress dialog.
    ProgressDialog progressDialog;

    // Creating FirebaseAuth object.
    FirebaseAuth firebaseAuth ;

    // Creating Boolean variable that holds EditText is empty or not status.
    Boolean EditTextStatus ;

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

        // Assigning layout email ID and Password ID.
        email = (EditText)findViewById(R.id.EditText_User_EmailID);
        password = (EditText)findViewById(R.id.EditText_User_Password);

        // Assign button layout ID.
        SignUp = (Button)findViewById(R.id.Button_SignUp);

        // Creating object instance.
        firebaseAuth = FirebaseAuth.getInstance();

        progressDialog = new ProgressDialog(MainActivity.this);

        // Adding click listener to Sign Up Button.
        SignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // Calling method to check EditText is empty or no status.
                CheckEditTextIsEmptyOrNot();

                // If EditText is true then this block with execute.
                if(EditTextStatus){

                    // If EditText is not empty than UserRegistrationFunction method will call.
                    UserRegistrationFunction();

                }
                // If EditText is false then this block with execute.
                else {

                    Toast.makeText(MainActivity.this, "Please fill all form fields.", Toast.LENGTH_LONG).show();

                }

            }
        });


    }

    // Creating UserRegistrationFunction
    public void UserRegistrationFunction(){

                // Showing progress dialog at user registration time.
                progressDialog.setMessage("Please Wait, We are Registering Your Data on Server");
                progressDialog.show();

                // Creating createUserWithEmailAndPassword method and pass email and password inside it.
                firebaseAuth.createUserWithEmailAndPassword(EmailHolder, PasswordHolder).
                        addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {
                            @Override
                            public void onComplete(@NonNull Task<AuthResult> task) {

                                // Checking if user is registered successfully.
                                if(task.isSuccessful()){

                                    // If user registered successfully then show this toast message.
                                    Toast.makeText(MainActivity.this,"User Registration Successfully",Toast.LENGTH_LONG).show();

                                }else{

                                    // If something goes wrong.
                                    Toast.makeText(MainActivity.this,"Something Went Wrong.",Toast.LENGTH_LONG).show();
                                }

                                // Hiding the progress dialog after all task complete.
                                progressDialog.dismiss();

            }
        });

    }

    public void CheckEditTextIsEmptyOrNot(){

        // Getting name and email from EditText and save into string variables.
        EmailHolder = email.getText().toString().trim();
        PasswordHolder = password.getText().toString().trim();

        if(TextUtils.isEmpty(EmailHolder) || TextUtils.isEmpty(PasswordHolder))
        {

            EditTextStatus = false;

        }
        else {

            EditTextStatus = true ;
        }

    }

}

Code for activity_main.xml layout file.

<?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:layout_margin="20dp"
    tools:context="com.androidjson.firebaseuserloginregistration_androidjsoncom.MainActivity">

    <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/textView"
    android:textSize="20dp"
    android:textColor="#000"
    android:text="Firebase User Registration Form"
    android:gravity="center"
    android:layout_marginTop="60dp"
    />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/EditText_User_EmailID"
        android:hint="Enter Your Email Here"
        android:gravity="center"
        android:layout_below="@+id/textView"
        android:layout_marginTop="20dp"
        />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/EditText_User_Password"
        android:hint="Enter Your Password Here"
        android:gravity="center"
        android:inputType="textPassword"
        android:layout_below="@+id/EditText_User_EmailID"/>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/Button_SignUp"
        android:layout_below="@+id/EditText_User_Password"
        android:text="Click Here To Sign Up"/>

    </RelativeLayout>

Code for AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidjson.firebaseuserloginregistration_androidjsoncom">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Screenshots:-

Registration Authentication

Download Code

The post Android Firebase User Email Registration Authentication Tutorial appeared first on AndroidJSon.

]]>
https://androidjson.com/firebase-registration-authentication/feed/ 1
Android Firebase Google Sign In Authentication Example Tutorial https://androidjson.com/add-firebase-google-login-integration/ https://androidjson.com/add-firebase-google-login-integration/#respond Fri, 26 May 2017 02:09:28 +0000 https://androidjson.com/?p=478 How to Add Google Gmail Google+ Sign In inside Android application using Firebase Tutorial and Show login user Email, Full Name. Firebase Google Sign In authentication is very easy to implement in android application. By follow a few simple steps we can easily add Google Login in our app. So…

Continue reading

The post Android Firebase Google Sign In Authentication Example Tutorial appeared first on AndroidJSon.

]]>
How to Add Google Gmail Google+ Sign In inside Android application using Firebase Tutorial and Show login user Email, Full Name.

Firebase Google Sign In authentication is very easy to implement in android application. By follow a few simple steps we can easily add Google Login in our app. So here is the complete step by step tutorial for Android Firebase Google Sign In Integration Example Tutorial. This is a very simple tutorial and if you follow all the steps i am going to mention then you can implement Google Login in your app using Firebase.

Contents in this project Android Firebase Google Sign In Authentication.

  1. Start a fresh Android Studio project.
  2. Create, configure and connect Firebase project to your Android Studio Application.
  3. Integrate Internet Permission.
  4. Start Coding.

1. Start a fresh Android Studio project.

2. Create, configure and connect Firebase project to your Android Studio Application :-

1. Open firebase.google.com .

2. Click on Get Started button present on home screen.

Connect Firebase Project

3. Now log in with your Google Gmail ID.

4. Click on Add Project.

5. Enter your project name and select your country then click on CREATE PROJECT .

6. Click on Add firebase to your android app icon.

7. Create a fresh project in Android Studio.

8. Now Add application Package Name, App Nick Name, SHA-1 certificate. To get the SHA-1 certificate from Android Studio read my this tutorial, it is the easiest method to get SHA-1 certificate.

9. Now hit the Register App button.

10. Here you go now your google-services.json file has been successfully generated. Hit the Download google-services.json button to download this file physically into your computer.

11. Next step is to add google-services.json inside your project. So open your project and put( Copy ) google-services.json file inside YourProjectName/app folder. For example my firebase project name is Firebase-AndroidJSon.com then my app folder located is Firebase-AndroidJSon.com/app . Now copy the google-services.json file into app folder like i did in below screenshot.

12. Now open your Project’s build.gradle(Project) file.

13. Add classpath ‘com.google.gms:google-services:3.0.0’ inside dependencies block.

14. Open your project’s build.gradle(Module:app) file.

15. Add compile ‘com.google.firebase:firebase-core:9.8.0’ ,
compile ‘com.google.firebase:firebase-auth:9.8.0’ and
compile ‘com.google.android.gms:play-services-auth:9.8.0’ inside dependencies block .

16. Then add apply plugin: ‘com.google.gms.google-services’ at the bottom of the page.

17. Now finally add below packagingOptions just bottom of buildTypes block like i did.

packagingOptions{
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/LICENSE-FIREBASE.txt'
    exclude 'META-INF/NOTICE'

}

Final Screenshot :

firebase_auth_login

18. Now next step is to Enable Firebase Google Login from Firebase Panel in Authentication section. So click on Authentication -> SIGN-IN-METHOD . Select Google .

sign_in_method

19. Enable Google Sign in From Panel and hit the SAVE button.

google_enable

3. Add internet permission to your project :

Open your project’s AndroidManifest.xml file and copy the below permission inside it. You will find the full AndroidManifest.xml file code at the bottom of this page along with all source code.

<uses-permission android:name="android.permission.INTERNET" />

4. Start Coding :

Code for MainActivity.java file.

package com.androidjson.firebasegooglelogin_androidjsoncom;

import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

// Importing Google GMS Auth API Libraries.
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;

public class MainActivity extends AppCompatActivity {

    // TAG is for show some tag logs in LOG screen.
    public static final String TAG = "MainActivity";

    // Request sing in code. Could be anything as you required.
    public static final int RequestSignInCode = 7;

    // Firebase Auth Object.
    public FirebaseAuth firebaseAuth;

    // Google API Client object.
    public GoogleApiClient googleApiClient;

    // Sing out button.
    Button SignOutButton;

    // Google Sign In button .
    com.google.android.gms.common.SignInButton signInButton;

    // TextView to Show Login User Email and Name.
    TextView LoginUserName, LoginUserEmail;


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


        signInButton = (SignInButton) findViewById(R.id.sign_in_button);

        SignOutButton= (Button) findViewById(R.id.sign_out);

        LoginUserName = (TextView) findViewById(R.id.textViewName);

        LoginUserEmail = (TextView) findViewById(R.id.textViewEmail);

        signInButton = (com.google.android.gms.common.SignInButton)findViewById(R.id.sign_in_button);

        // Getting Firebase Auth Instance into firebaseAuth object.
        firebaseAuth = FirebaseAuth.getInstance();

        // Hiding the TextView on activity start up time.
        LoginUserEmail.setVisibility(View.GONE);
        LoginUserName.setVisibility(View.GONE);

        // Creating and Configuring Google Sign In object.
        GoogleSignInOptions googleSignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();

        // Creating and Configuring Google Api Client.
        googleApiClient = new GoogleApiClient.Builder(MainActivity.this)
                .enableAutoManage(MainActivity.this , new GoogleApiClient.OnConnectionFailedListener() {
                    @Override
                    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

                    }
                } /* OnConnectionFailedListener */)
                .addApi(Auth.GOOGLE_SIGN_IN_API, googleSignInOptions)
                .build();


        // Adding Click listener to User Sign in Google button.
        signInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                UserSignInMethod();

            }
        });

        // Adding Click Listener to User Sign Out button.
        SignOutButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                UserSignOutFunction();

            }
        });

    }


    // Sign In function Starts From Here.
    public void UserSignInMethod(){

        // Passing Google Api Client into Intent.
        Intent AuthIntent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);

        startActivityForResult(AuthIntent, RequestSignInCode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RequestSignInCode){

            GoogleSignInResult googleSignInResult = Auth.GoogleSignInApi.getSignInResultFromIntent(data);

            if (googleSignInResult.isSuccess()){

                GoogleSignInAccount googleSignInAccount = googleSignInResult.getSignInAccount();

                FirebaseUserAuth(googleSignInAccount);
            }

        }
    }

    public void FirebaseUserAuth(GoogleSignInAccount googleSignInAccount) {

        AuthCredential authCredential = GoogleAuthProvider.getCredential(googleSignInAccount.getIdToken(), null);

        Toast.makeText(MainActivity.this,""+ authCredential.getProvider(),Toast.LENGTH_LONG).show();

        firebaseAuth.signInWithCredential(authCredential)
                .addOnCompleteListener(MainActivity.this, new OnCompleteListener() {
                    @Override
                    public void onComplete(@NonNull Task AuthResultTask) {

                        if (AuthResultTask.isSuccessful()){

                            // Getting Current Login user details.
                            FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();

                            // Showing Log out button.
                            SignOutButton.setVisibility(View.VISIBLE);

                            // Hiding Login in button.
                            signInButton.setVisibility(View.GONE);

                            // Showing the TextView.
                            LoginUserEmail.setVisibility(View.VISIBLE);
                            LoginUserName.setVisibility(View.VISIBLE);

                            // Setting up name into TextView.
                            LoginUserName.setText("NAME =  "+ firebaseUser.getDisplayName().toString());

                            // Setting up Email into TextView.
                            LoginUserEmail.setText("Email =  "+ firebaseUser.getEmail().toString());

                        }else {
                            Toast.makeText(MainActivity.this,"Something Went Wrong",Toast.LENGTH_LONG).show();
                        }
                    }
                });
    }

    public void UserSignOutFunction() {

        // Sing Out the User.
        firebaseAuth.signOut();

        Auth.GoogleSignInApi.signOut(googleApiClient).setResultCallback(
                new ResultCallback() {
                    @Override
                    public void onResult(@NonNull Status status) {

                        // Write down your any code here which you want to execute After Sign Out.

                        // Printing Logout toast message on screen.
                        Toast.makeText(MainActivity.this, "Logout Successfully", Toast.LENGTH_LONG).show();

                    }
                });

        // After logout Hiding sign out button.
        SignOutButton.setVisibility(View.GONE);

        // After logout setting up email and name to null.
        LoginUserName.setText(null);
        LoginUserEmail.setText(null);

        // After logout setting up login button visibility to visible.
        signInButton.setVisibility(View.VISIBLE);
    }

}

Code for activity_main.xml layout file.

<?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:padding="20dp"
    tools:context="com.androidjson.firebasegooglelogin_androidjsoncom.MainActivity">

    <com.google.android.gms.common.SignInButton
        android:id="@+id/sign_in_button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

    <Button
        android:id="@+id/sign_out"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Click Here To Sign Out"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:visibility="gone"
        />

    <TextView
        android:id="@+id/textViewName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text=""
        android:gravity="center"
        android:textSize="20dp"
        android:textColor="#000"
        />

    <TextView
        android:id="@+id/textViewEmail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/textViewName"
        android:text=""
        android:gravity="center"
        android:textSize="20dp"
        android:textColor="#000"
        />

</RelativeLayout>

Code for AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidjson.firebasegooglelogin_androidjsoncom">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Screenshots:-

Android Firebase Google Sign In Authentication Example Tutorial

Download Source Code

The post Android Firebase Google Sign In Authentication Example Tutorial appeared first on AndroidJSon.

]]>
https://androidjson.com/add-firebase-google-login-integration/feed/ 0
Android Firebase Cloud Messaging Tutorial Example Studio https://androidjson.com/firebase-cloud-messaging-tutorial-example/ https://androidjson.com/firebase-cloud-messaging-tutorial-example/#respond Fri, 19 May 2017 01:50:35 +0000 https://androidjson.com/?p=454 How to create Firebase Cloud Messaging Client App on Android to send push notifications to all installed application users. Firebase cloud messaging is an awesome features for every android developer who wish to send thousands of push notifications with one click to each and every user who has installed their application.…

Continue reading

The post Android Firebase Cloud Messaging Tutorial Example Studio appeared first on AndroidJSon.

]]>
How to create Firebase Cloud Messaging Client App on Android to send push notifications to all installed application users.

Firebase cloud messaging is an awesome features for every android developer who wish to send thousands of push notifications with one click to each and every user who has installed their application. You can also control the complete push notification it self by setting up push notification title, push notification message body. We can also schedule our push notification timing from the Firebase panel. So here is the complete step by step tutorial for Android Firebase Cloud Messaging Tutorial Example.

Contents in this project Android Firebase Cloud Messaging Tutorial Example :-

  1. Watch the live application demo.
  2. Create a fresh android application project.
  3. Create, configure and connect Firebase to your Application.
  4. Add internet permission to your project.
  5. Start Coding.
  6. After finish coding send push notification from Firebase Panel.

1. Watch the live application demo to know how this app works and how can we send push notification from Firebase panel.


2. Create a fresh android application project.

3. Create, configure and connect Firebase to your Application :

1. Open firebase.google.com .

2. Click on Get Started button present on home screen.

Connect Firebase Project

3. Now log in with your Google Gmail ID.

4. Click on Add Project.

5. Enter your project name and select your country then click on CREATE PROJECT .

6. Click on Add firebase to your android app icon.

7. Create a fresh project in Android Studio.

8. Now Add application Package Name, App Nick Name, SHA-1 certificate. To get the SHA-1 certificate from Android Studio read my this tutorial, it is the easiest method to get SHA-1 certificate.

9. Now hit the Register App button.

10. Here you go now your google-services.json file has been successfully generated. Hit the Download google-services.json button to download this file physically into your computer.

11. Next step is to add google-services.json inside your project. So open your project and put( Copy ) google-services.json file inside YourProjectName/app folder. For example my firebase project name is Firebase-AndroidJSon.com then my app folder located is Firebase-AndroidJSon.com/app . Now copy the google-services.json file into app folder like i did in below screenshot.

12. Now open your Project’s build.gradle(Project) file.

13. Add classpath ‘com.google.gms:google-services:3.0.0’ inside dependencies block.

14. Open your project’s build.gradle(Module:app) file.

15. Add compile ‘com.firebase:firebase-client-android:2.4.0’ and compile ‘com.google.firebase:firebase-messaging:9.2.1’ inside dependencies block .

16. Then add apply plugin: ‘com.google.gms.google-services’ at the bottom of the page.

17. Now finally add below packagingOptions just bottom of buildTypes block like i did.

packagingOptions{
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/LICENSE-FIREBASE.txt'
    exclude 'META-INF/NOTICE'

}

Final Screenshot :

4. Add internet permission to your project :

Open your project’s AndroidManifest.xml file and copy the below permission inside it. You will find the full AndroidManifest.xml file code at the bottom of this page along with all source code.

<uses-permission android:name="android.permission.INTERNET" />

5. Add service into AndroidManifest.xml file.

<service
    android:name=".MyFirebaseMessagingService">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT"/>
    </intent-filter>
</service>

<service
    android:name=".MyFirebaseInstanceIDService">
    <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
    </intent-filter>
</service>

5. Start Coding for project Android Firebase Cloud Messaging Tutorial Example :-

Code for MainActivity.java file.

package com.androidjson.firebasecloudmessage_androidjsoncom;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

Code for activity_main.xml layout file.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.androidjson.firebasecloudmessage_androidjsoncom.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Code for MyFirebaseInstanceIDService.java file.

package com.androidjson.firebasecloudmessage_androidjsoncom;

/**
 * Created by AndroidJSon.com on 5/13/2017.
 */

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;

import android.util.Log;

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    private static final String Firebase_Tag = "FirebaseIDService";

    @Override
    public void onTokenRefresh() {

        //Getting token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();

        //Show token on logcat
        Log.d(Firebase_Tag, "Refreshed token: " + refreshedToken);

    }

    private void sendRegistrationToServer(String token) {
        // Write down your code here to do anything with toke like sending on server or save locally.
    }
}

Code for MyFirebaseMessagingService.java file.

package com.androidjson.firebasecloudmessage_androidjsoncom;

/**
 * Created by AndroidJSon.com on 5/13/2017.
 */

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import android.content.Intent;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        //Method To Generate Notification.
        FirebaseCloudMessageFunction(remoteMessage.getData().get("title"), remoteMessage.getData().get("body"));
    }

    // Function to Generate Push Notification After Receiving Response from Server.
    private void FirebaseCloudMessageFunction(String messageTitle, String messageBody) {

        // Creating Intent.
        Intent intent = new Intent(this, MainActivity.class);

        // Device vibrate pattern.
        long[] pattern = {500,500,500,500,500};

        // Adding FLAG_ACTIVITY_CLEAR_TOP to intent.
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        // Creating Pending Intent object.
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0 , intent,PendingIntent.FLAG_UPDATE_CURRENT);


        // Creating URI to access the default Notification Ringtone.
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        // Converting drawable icon to bitmap for default notification ICON.
        Bitmap DefaultIconBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);

        // Building Notfication.
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)

                // Adding Default Icon to Notification bar.
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))

                // Setting up Title.
                .setContentTitle(messageTitle)

                // Setting the default msg coming from server into Notification.
                .setContentText(messageBody)

                .setAutoCancel(true)

                .setVibrate(pattern)

                .setSound(defaultSoundUri)

                .setContentIntent(pendingIntent);

        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        notificationManager.notify(0, builder.build());
    }
}

Code for AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidjson.firebasecloudmessage_androidjsoncom">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
<!-- Defining Services -->
        <service
            android:name=".MyFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>

        <service
            android:name=".MyFirebaseInstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>

    </application>

</manifest>

Screenshot :

Android Firebase Cloud Messaging Tutorial Example

Download Source Code

7. After finish coding send push notification from Firebase Panel :-

  1. Open Firebase .
  2. Select your application.
  3. Goto Notifications.
  4. Click on SEND YOUR FIRST MESSAGE .
  5. Enter Message body and title, Hit the Send Message button.

The post Android Firebase Cloud Messaging Tutorial Example Studio appeared first on AndroidJSon.

]]>
https://androidjson.com/firebase-cloud-messaging-tutorial-example/feed/ 0
Android Firebase Tutorial-Insert Read Firebase data example https://androidjson.com/android-firebase-tutorial-fetch-write/ https://androidjson.com/android-firebase-tutorial-fetch-write/#comments Fri, 12 May 2017 01:54:03 +0000 https://androidjson.com/?p=429 How to add setup Firebase configuration inside Android Studio Project and Add Update real time firebase database using EditText. In this tutorial we would going to insert multiple EditText data into Firebase runtime online database. First we would configure the runtime database on online Firebase server then connect that database…

Continue reading

The post Android Firebase Tutorial-Insert Read Firebase data example appeared first on AndroidJSon.

]]>
How to add setup Firebase configuration inside Android Studio Project and Add Update real time firebase database using EditText.

In this tutorial we would going to insert multiple EditText data into Firebase runtime online database. First we would configure the runtime database on online Firebase server then connect that database to our android app. So here is the complete step by step tutorial for Android Firebase Tutorial-Insert Read Firebase data example tutorial.

Contents in this project Android Firebase Tutorial-Insert Read Firebase data example tutorial :-

  1. Watch the live application demo to know how this app works.
  2. Create a fresh android application in Studio.
  3. Create and configure and connect Firebase database to your Application.
  4. Add internet permission to your project.
  5. Start Coding.

Note :- In source code section i already define each line work using comment so just read the code carefully and you will know exactly how each line works and what work perform each line code.

1. Watch the live application demo to know how this app works :

2. Create a fresh android application in Studio.

3. Create and configure and connect Firebase database to your Application :

Read my this tutorial to connect firebase directly to your android app by importing their libraries and dependencies.

4. Add internet permission to your project :

Open your project’s AndroidManifest.xml file and copy the below permission inside it. You will find the full AndroidManifest.xml file code at the bottom of this page along with all source code.

<uses-permission android:name="android.permission.INTERNET" />

 5. Start Coding for project Android Firebase Tutorial-Insert Read Firebase data example tutorial :

Code for MainActivity.java file.

package com.androidjson.firebase_androidjsoncom;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;

public class MainActivity extends AppCompatActivity {

    // Declaring Button object.
    Button SubmitButton, ShowButton;

    // Declaring EditText object.
    EditText NameEditText, PhoneNumberEditText;

    // Declaring String variable ( In which we are storing firebase server URL ).
    public static final String Firebase_Server_URL = "https://fir-ed3b9.firebaseio.com/";

    // Declaring String variables to store name & phone number get from EditText.
    String NameHolder, NumberHolder;

    // // Declaring TextView object.
    TextView ShowDataTextView ;

    // Declaring Firebase object.
    Firebase firebase;

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

        // Adding MainActivity context into Firebase context.
        Firebase.setAndroidContext(MainActivity.this);

        // Passing firebase Server URL into firebase object.
        firebase = new Firebase(Firebase_Server_URL);

        // Adding ID'S .
        SubmitButton = (Button)findViewById(R.id.submit);

        ShowButton = (Button)findViewById(R.id.show);

        ShowDataTextView = (TextView)findViewById(R.id.showData);

        NameEditText = (EditText)findViewById(R.id.name);

        PhoneNumberEditText = (EditText)findViewById(R.id.phone_number);

        // Adding Click listener to Submit button.
        SubmitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // Declaring student class object.
                Student student = new Student();

                // Calling function to Get data from EditText and store into string variables.
                GetDataFromEditText();

                // Adding student name into student class object.
                student.setStudentName(NameHolder);

                // Adding student number into student class object.
                student.setStudentPhoneNumber(NumberHolder);

                // Passing student phone number and name into firebase object to add into database.
                firebase.child("Student").setValue(student);

                // Showing toast message after data inserted.
                Toast.makeText(MainActivity.this,"Data Inserted Successfully", Toast.LENGTH_LONG).show();

            }
        });

        // Adding click listener to Show data button.
        ShowButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // Adding addValueEventListener method on firebase object.
                firebase.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot MainSnapshot) {

                        for (DataSnapshot SubSnapshot : MainSnapshot.getChildren()) {

                            Student student = SubSnapshot.getValue(Student.class);

                            // Adding name and phone number of student into string that is coming from server.
                            String ShowDataString = "Name : "+student.getStudentName()+"\nPhone Number : "+student.getStudentPhoneNumber()+"\n\n";

                            // Apply complete string variable into TextView.
                            ShowDataTextView.setText(ShowDataString);
                        }
                    }

                    @Override
                    public void onCancelled(FirebaseError firebaseError) {
                        System.out.println("Data Access Failed" + firebaseError.getMessage());
                    }
                });

            }
        });
    }

    public void GetDataFromEditText(){

        NameHolder = NameEditText.getText().toString().trim();

        NumberHolder = PhoneNumberEditText.getText().toString().trim();

    }
}

Code for activity_main.xml layout file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.androidjson.firebase_androidjsoncom.MainActivity"
    android:layout_margin="7dp">

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/name"
        android:hint="Enter Name"
        android:gravity="center"
        android:layout_marginTop="40dp"/>

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/phone_number"
        android:hint="Enter Phone Number"
        android:gravity="center"
        android:layout_below="@+id/name"
        android:layout_marginTop="10dp"/>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/submit"
        android:layout_below="@id/phone_number"
        android:text="Submit Data To Firebase Database"
        android:layout_marginTop="10dp"/>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/show"
        android:layout_below="@id/submit"
        android:text="Show inserted Firebase data into TextView From Server"
        android:layout_marginTop="10dp"/>

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:id="@+id/showData"
        android:textSize="20dp"
        android:textColor="#000"
        android:layout_below="@+id/show"
        android:layout_margin="20dp"/>


</RelativeLayout>

Code for Student.java file.

package com.androidjson.firebase_androidjsoncom;

/**
 * Created by AndroidJson.com on 5/5/2017.
 */

public class Student {

    private String name;
    private String phoneNumber;

    public Student() {
        // This is default constructor.
    }

    public String getStudentName() {

        return name;
    }

    public void setStudentName(String name) {

        this.name = name;
    }

    public String getStudentPhoneNumber() {
        return phoneNumber;
    }

    public void setStudentPhoneNumber(String phonenumber) {

        this.phoneNumber = phonenumber;
    }

}

Code for AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidjson.firebase_androidjsoncom">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Screenshots:

Android Firebase Tutorial-Insert Read Firebase data example tutorial

Download Code

The post Android Firebase Tutorial-Insert Read Firebase data example appeared first on AndroidJSon.

]]>
https://androidjson.com/android-firebase-tutorial-fetch-write/feed/ 2
Add Connect Firebase Project to Android Studio Step by Step Guide https://androidjson.com/integrate-firebase-project-android-studio/ https://androidjson.com/integrate-firebase-project-android-studio/#respond Sat, 06 May 2017 05:47:08 +0000 https://androidjson.com/?p=431 How to properly configure setup Firebase online project to Android Studio and install firebase libraries in application. Firebase is one of the most popular products from Google to create and manage web applications like websites and mobile applications(Android, iPhone). Firebase is very easy to use and comes with no server…

Continue reading

The post Add Connect Firebase Project to Android Studio Step by Step Guide appeared first on AndroidJSon.

]]>
How to properly configure setup Firebase online project to Android Studio and install firebase libraries in application.

Firebase is one of the most popular products from Google to create and manage web applications like websites and mobile applications(Android, iPhone). Firebase is very easy to use and comes with no server side coding skills because there is no need to do server side programming . It is much easier then MySQL because when we are using MySQL then we need to server side work in PHP language to convert that data into JSon form. So here is the complete step by step tutorial for Add Connect Firebase Project to Android Studio Step by Step Guide .

How to Add Connect Firebase Project to Android Studio Step by Step Guide .

1. Open firebase.google.com .

2. Click on Get Started button present on home screen.

Connect Firebase Project

3. Now log in with your Google Gmail ID.

4. Click on Add Project.

5. Enter your project name and select your country then click on CREATE PROJECT .

6. Click on Add firebase to your android app icon.

7. Create a fresh project in Android Studio.

8. Now Add application Package Name, App Nick Name, SHA-1 certificate. To get the SHA-1 certificate from Android Studio read my this tutorial, it is the easiest method to get SHA-1 certificate.

9. Now hit the Register App button.

10. Here you go now your google-services.json file has been successfully generated. Hit the Download google-services.json button to download this file physically into your computer.

11. Next step is to add google-services.json inside your project. So open your project and put( Copy ) google-services.json file inside YourProjectName/app folder. For example my firebase project name is Firebase-AndroidJSon.com then my app folder located is Firebase-AndroidJSon.com/app . Now copy the google-services.json file into app folder like i did in below screenshot.

12. Now open your Project’s build.gradle(Project) file.

13. Add classpath ‘com.google.gms:google-services:3.0.0’ inside dependencies block.

14. Open your project’s build.gradle(Module:app) file.

15. Add compile ‘com.firebase:firebase-client-android:2.4.0’ inside dependencies block .

16. Then add apply plugin: ‘com.google.gms.google-services’ at the bottom of the page.

17. Now finally add below packagingOptions just bottom of buildTypes block like i did.

packagingOptions{
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/LICENSE-FIREBASE.txt'
    exclude 'META-INF/NOTICE'

}

Final Screenshot :

The post Add Connect Firebase Project to Android Studio Step by Step Guide appeared first on AndroidJSon.

]]>
https://androidjson.com/integrate-firebase-project-android-studio/feed/ 0
Android Capture Image From Camera Upload to Server Using PHP MySQL https://androidjson.com/capture-image-camera-upload-server/ https://androidjson.com/capture-image-camera-upload-server/#comments Wed, 26 Apr 2017 17:08:23 +0000 https://androidjson.com/?p=410 How to Take a photo from camera and upload online and save image path into MySQL database with image name project with Runtime Camera permission. In this tutorial we would going to create an android application which would capture image from android mobile phone camera and show that image inside…

Continue reading

The post Android Capture Image From Camera Upload to Server Using PHP MySQL appeared first on AndroidJSon.

]]>
How to Take a photo from camera and upload online and save image path into MySQL database with image name project with Runtime Camera permission.

In this tutorial we would going to create an android application which would capture image from android mobile phone camera and show that image inside ImageView. After capturing we would set image name into EditText and upload image online to our hosting server. While uploading we would also show ProgressBar dialog on app screen. The image would store on our server inside a folder created by myself and the whole image path save into MySQL database along with image name. We are using PHP script to receive and store image on server. So here is the complete step by step tutorial for Android Capture Image From Camera Upload to Server Using PHP MySQL.

Contents in this project Android Capture Image From Camera Upload to Server Using PHP MySQL :-

  1. Create Database including table on your server.
  2. Create folder named as images on your server.
  3. Create PHP Script to receive send image from android phone.
  4. Start a fresh android app development project.
  5. Add internet and camera permission inside the project Manifest.xml file.
  6. Start coding.

1. Create Database including table on your server :

Create a fresh database on your server and inside that database create a fresh table which will used to store image name and image path inside MySQL database like i did in below screenshot.

2. Create folder named as images on your server :

After creating table we have to create a folder on our hosting server which will used to store images.

3. Create PHP Script to receive send image from android phone :

Now we would have to create 2 php files first one is capture_img_upload_to_server.php file and DatabaseConfig.php file and upload that file into our server. These file will used to receive and store image details, image itself, image name on MySQL database.

Code for capture_img_upload_to_server.php file.

<?php

include 'DatabaseConfig.php';

// Create connection
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
 
 if($_SERVER['REQUEST_METHOD'] == 'POST')
 {
 $DefaultId = 0;
 
 $ImageData = $_POST['image_path'];
 
 $ImageName = $_POST['image_name'];

 $GetOldIdSQL ="SELECT id FROM ImageToServerTable ORDER BY id ASC";
 
 $Query = mysqli_query($conn,$GetOldIdSQL);
 
 while($row = mysqli_fetch_array($Query)){
 
 $DefaultId = $row['id'];
 }
 
 $ImagePath = "images/$DefaultId.png";
 
 $ServerURL = "https://androidjsonblog.000webhostapp.com/$ImagePath";
 
 $InsertSQL = "insert into ImageToServerTable (image_path,image_name) values ('$ServerURL','$ImageName')";
 
 if(mysqli_query($conn, $InsertSQL)){

 file_put_contents($ImagePath,base64_decode($ImageData));

 echo "Your Image Has Been Uploaded.";
 }
 
 mysqli_close($conn);
 }else{
 echo "Not Uploaded";
 }

?>

Code for DatabaseConfig.php file.

<?php

//Define your host here.
$HostName = "localhost";

//Define your database username here.
$HostUser = "id632449_androidjson";

//Define your database password here.
$HostPass = "kdfjdfdskljomew9ry3873";

//Define your database name here.
$DatabaseName = "id632449_androidjson";

?>

5. Add internet and camera permission inside the project Manifest.xml file :

Open your project’s AndroidManifest.xml file and add camera permission and internet permission inside it.

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INTERNET" />

 6. Start coding For Project :-

Code for MainActivity.java file.

package com.androidjson.captureimageupload_androidjsoncom;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.net.HttpURLConnection;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.widget.EditText;
import android.net.Uri;
import java.io.InputStreamReader;
import java.io.OutputStream;
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedWriter;
import java.util.Map;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.io.OutputStreamWriter;
import java.net.URL;
import android.provider.MediaStore;
import java.io.BufferedReader;
import java.net.URLEncoder;
import java.io.UnsupportedEncodingException;
import android.util.Base64;

public class MainActivity extends AppCompatActivity {

    Button CaptureImageFromCamera,UploadImageToServer;

    ImageView ImageViewHolder;

    EditText imageName;

    ProgressDialog progressDialog ;

    Intent intent ;

    public  static final int RequestPermissionCode  = 1 ;

    Bitmap bitmap;

    boolean check = true;

    String GetImageNameFromEditText;

    String ImageNameFieldOnServer = "image_name" ;

    String ImagePathFieldOnServer = "image_path" ;

    String ImageUploadPathOnSever ="https://androidjsonblog.000webhostapp.com/capture_img_upload_to_server.php" ;


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

        CaptureImageFromCamera = (Button)findViewById(R.id.button);
        ImageViewHolder = (ImageView)findViewById(R.id.imageView);
        UploadImageToServer = (Button) findViewById(R.id.button2);
        imageName = (EditText)findViewById(R.id.editText);

        EnableRuntimePermissionToAccessCamera();

        CaptureImageFromCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

                startActivityForResult(intent, 7);

            }
        });

        UploadImageToServer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                GetImageNameFromEditText = imageName.getText().toString();

                ImageUploadToServerFunction();

            }
        });
    }

// Star activity for result method to Set captured image on image view after click.
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

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

            Uri uri = data.getData();

            try {

                // Adding captured image in bitmap.
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);

                // adding captured image in imageview.
                ImageViewHolder.setImageBitmap(bitmap);

            } catch (IOException e) {

                e.printStackTrace();
            }
        }

    }

    // Requesting runtime permission to access camera.
    public void EnableRuntimePermissionToAccessCamera(){

        if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                Manifest.permission.CAMERA))
        {

            // Printing toast message after enabling runtime permission.
            Toast.makeText(MainActivity.this,"CAMERA permission allows us to Access CAMERA app", Toast.LENGTH_LONG).show();

        } else {

            ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.CAMERA}, RequestPermissionCode);

        }
    }

    // Upload captured image online on server function.
    public void ImageUploadToServerFunction(){

        ByteArrayOutputStream byteArrayOutputStreamObject ;

        byteArrayOutputStreamObject = new ByteArrayOutputStream();

        // Converting bitmap image to jpeg format, so by default image will upload in jpeg format.
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStreamObject);

        byte[] byteArrayVar = byteArrayOutputStreamObject.toByteArray();

        final String ConvertImage = Base64.encodeToString(byteArrayVar, Base64.DEFAULT);

        class AsyncTaskUploadClass extends AsyncTask<Void,Void,String> {

            @Override
            protected void onPreExecute() {

                super.onPreExecute();

                // Showing progress dialog at image upload time.
                progressDialog = ProgressDialog.show(MainActivity.this,"Image is Uploading","Please Wait",false,false);
            }

            @Override
            protected void onPostExecute(String string1) {

                super.onPostExecute(string1);

                // Dismiss the progress dialog after done uploading.
                progressDialog.dismiss();

                // Printing uploading success message coming from server on android app.
                Toast.makeText(MainActivity.this,string1,Toast.LENGTH_LONG).show();

                // Setting image as transparent after done uploading.
                ImageViewHolder.setImageResource(android.R.color.transparent);


            }

            @Override
            protected String doInBackground(Void... params) {

                ImageProcessClass imageProcessClass = new ImageProcessClass();

                HashMap<String,String> HashMapParams = new HashMap<String,String>();

                HashMapParams.put(ImageNameFieldOnServer, GetImageNameFromEditText);

                HashMapParams.put(ImagePathFieldOnServer, ConvertImage);

                String FinalData = imageProcessClass.ImageHttpRequest(ImageUploadPathOnSever, HashMapParams);

                return FinalData;
            }
        }
        AsyncTaskUploadClass AsyncTaskUploadClassOBJ = new AsyncTaskUploadClass();

        AsyncTaskUploadClassOBJ.execute();
    }

    public class ImageProcessClass{

        public String ImageHttpRequest(String requestURL,HashMap<String, String> PData) {

            StringBuilder stringBuilder = new StringBuilder();

            try {

                URL url;
                HttpURLConnection httpURLConnectionObject ;
                OutputStream OutPutStream;
                BufferedWriter bufferedWriterObject ;
                BufferedReader bufferedReaderObject ;
                int RC ;

                url = new URL(requestURL);

                httpURLConnectionObject = (HttpURLConnection) url.openConnection();

                httpURLConnectionObject.setReadTimeout(19000);

                httpURLConnectionObject.setConnectTimeout(19000);

                httpURLConnectionObject.setRequestMethod("POST");

                httpURLConnectionObject.setDoInput(true);

                httpURLConnectionObject.setDoOutput(true);

                OutPutStream = httpURLConnectionObject.getOutputStream();

                bufferedWriterObject = new BufferedWriter(

                        new OutputStreamWriter(OutPutStream, "UTF-8"));

                bufferedWriterObject.write(bufferedWriterDataFN(PData));

                bufferedWriterObject.flush();

                bufferedWriterObject.close();

                OutPutStream.close();

                RC = httpURLConnectionObject.getResponseCode();

                if (RC == HttpsURLConnection.HTTP_OK) {

                    bufferedReaderObject = new BufferedReader(new InputStreamReader(httpURLConnectionObject.getInputStream()));

                    stringBuilder = new StringBuilder();

                    String RC2;

                    while ((RC2 = bufferedReaderObject.readLine()) != null){

                        stringBuilder.append(RC2);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            return stringBuilder.toString();
        }

        private String bufferedWriterDataFN(HashMap<String, String> HashMapParams) throws UnsupportedEncodingException {

            StringBuilder stringBuilderObject;

            stringBuilderObject = new StringBuilder();

            for (Map.Entry<String, String> KEY : HashMapParams.entrySet()) {

                if (check)

                    check = false;
                else
                    stringBuilderObject.append("&");

                stringBuilderObject.append(URLEncoder.encode(KEY.getKey(), "UTF-8"));

                stringBuilderObject.append("=");

                stringBuilderObject.append(URLEncoder.encode(KEY.getValue(), "UTF-8"));
            }

            return stringBuilderObject.toString();
        }

    }

    @Override
    public void onRequestPermissionsResult(int RC, String per[], int[] PResult) {

        switch (RC) {

            case RequestPermissionCode:

                if (PResult.length > 0 && PResult[0] == PackageManager.PERMISSION_GRANTED) {

                    Toast.makeText(MainActivity.this,"Permission Granted, Now your application can access CAMERA.", Toast.LENGTH_LONG).show();

                } else {

                    Toast.makeText(MainActivity.this,"Permission Canceled, Now your application cannot access CAMERA.", Toast.LENGTH_LONG).show();

                }
                break;
        }
    }

}

Code for activity_main.xml layout file.

<?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"
    tools:context="com.androidjson.captureimageupload_androidjsoncom.MainActivity">

    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="270dp"
        android:id="@+id/imageView"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:text="Click here to capture image using camera"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:layout_below="@+id/imageView"/>

    <EditText
        android:id="@+id/editText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button"
        android:layout_centerHorizontal="true"
        android:ems="10"
        android:inputType="textPersonName"
        android:hint="Enter Image Name"
        android:gravity="center"
        android:layout_marginTop="10dp"/>

    <Button
        android:id="@+id/button2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Upload Captured Image On Server"
        android:layout_below="@+id/editText"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

</RelativeLayout>

Code for AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidjson.captureimageupload_androidjsoncom">

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Screenshots:-

Android Capture Image From Camera Upload to Server Using PHP MySQL

Download Code

The post Android Capture Image From Camera Upload to Server Using PHP MySQL appeared first on AndroidJSon.

]]>
https://androidjson.com/capture-image-camera-upload-server/feed/ 4
Manually Update Android Studio Old Version to Latest Upcoming Fresh Version Tutorial https://androidjson.com/manually-update-android-studio-latest-upcoming-version-tutorial/ https://androidjson.com/manually-update-android-studio-latest-upcoming-version-tutorial/#respond Wed, 19 Apr 2017 08:59:58 +0000 https://androidjson.com/?p=399 How to Update Studio Gradle plugin to fresh released version to include latest features. Android Studio is the official IDE ( Integrated Development Environment ) for android application development comes with all files and software required to build android apps into a single download link. You can download the latest…

Continue reading

The post Manually Update Android Studio Old Version to Latest Upcoming Fresh Version Tutorial appeared first on AndroidJSon.

]]>
How to Update Studio Gradle plugin to fresh released version to include latest features.

Android Studio is the official IDE ( Integrated Development Environment ) for android application development comes with all files and software required to build android apps into a single download link. You can download the latest fresh Android Studio version from Google Developers official website From Here. Android Studio comes with build in SDK Manger so you don’t need to download the SDK Manger externally. So here is the complete step by step tutorial for Manually Update Android Studio Old Version to Latest Upcoming Fresh Version Tutorial.

List of All Android Studio updates Till April 19th, 2017.

  • Android Studio v2.3.1 (April 2017)
  • Android Studio v2.3.0 (March 2017)
  • Android Studio v2.2.3 (December 2016)
  • Android Studio v2.2.2 (October 2016)
  • Android Studio v2.2.1 (October 2016)
  • Android Studio v2.2.0 (September 2016)
  • Android Studio v2.1.3 (August 2016)
  • Android Studio v2.1.2 (June 2016)
  • Android Studio v2.1.1 (May 2016)
  • Android Studio v2.1.0 (April 2016)
  • Android Studio v2.0.0 (April 2016)
  • Android Studio v1.5.1 (December 2015)
  • Android Studio v1.5.0 (November 2015)
  • Android Studio v1.4.1 (October 2015)
  • Android Studio v1.4.0 (September 2015)
  • Android Studio v1.3.2 (August 2015)
  • Android Studio v1.3.1 (August 2015)
  • Android Studio v1.3.0 (July 2015)
  • Android Studio v1.2.2 (June 2015)
  • Android Studio v1.2.1 (May 2015)
  • Android Studio v1.2.0 (April 2015)
  • Android Studio v1.1.0 (February 2015)
  • Android Studio v1.0.1 (December 2014)
  • Android Studio v1.0 (December 2014)
  • Android Studio v0.8.14 (October 2014)
  • Android Studio v0.8.6 (August 2014)
  • Android Studio v0.8.0 (June 2014)
  • Android Studio v0.5.2 (May 2014)
  • Android Studio v0.4.6 (March 2014)
  • Android Studio v0.4.2 (Jan 2014)
  • Android Studio v0.3.2 (Oct 2013)
  • Android Studio v0.2.x (July 2013)
  • Android Studio v0.1.x (May 2013)

How to Manually Update Android Studio Old Version to Latest Upcoming Fresh Version Tutorial.

1. Start Android Studio.

2. Click on Help -> Check For Updates .

Manually Update Android Studio Old Version to Latest Upcoming Fresh Version Tutorial

3. After click on Check For Updates it will start checking whether a new update is available or not . If new update is available then update notification message will show on your desktop screen. Now just click on Update and Restart  button.

Here you go now your studio update should start downloading .

The post Manually Update Android Studio Old Version to Latest Upcoming Fresh Version Tutorial appeared first on AndroidJSon.

]]>
https://androidjson.com/manually-update-android-studio-latest-upcoming-version-tutorial/feed/ 0