Upload file on Firebase Storage in Android

Firebase provides lot of good feature as we had seen in my last tutorial. If you have not seen my last articles Here is the quick description Firebase Database and authentication and Firebase Analytics.

Today I am sharing article to upload any files on Firebase storage. Lets talk about what is firebase storage. Firebase Storage is built for app developers who need to store and serve user-generated content, such as photos or videos. Firebase Storage is a stand-alone solution for uploading user generated content like images and videos from an iOS and Android device, as well as the Web.


Here is firebase storage video by Firebase Team. 



Lets start configuration for firebase storage and database. Here is video that helps you understand before start upload.



Step.1: Please go to Firebase console to create the project.


Step.2: Now you can create the project name and enter your county name. 

Step.3: You have to choose which platform do you want to use. Here we are configuring for android platform, so I am choosing option for android app.
Step.4: Now you need to enter your package name of your project. Ex: Here my package name is "com.sunil.firebasedatabasetest" . Other fields are optional for debug mode. But if you want to release your app that time you need to pass the SHA-1 key. 

Step.5: Once you done your step.4 You will get downloded one google-services.json file. You have to copy this file and paste inside the app folder. 

build.gradle project level

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.2'
        classpath 'com.google.gms:google-services:3.0.0'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files

    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}


build.gradle app level

apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    defaultConfig {
        applicationId "com.sunil.firebasedatabasetest"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.0.0'
    testCompile 'junit:junit:4.12'

    compile 'com.firebaseui:firebase-ui-database:0.6.2'
    compile 'com.google.firebase:firebase-auth:9.8.0'
    compile 'com.google.firebase:firebase-database:9.8.0'

    compile 'com.google.firebase:firebase-storage:9.8.0'

    compile 'de.hdodenhof:circleimageview:2.1.0'
    compile 'com.github.bumptech.glide:glide:3.7.0'

    compile 'com.android.support:cardview-v7:25.0.0'
    compile 'com.android.support:design:25.0.0'
    compile 'com.jakewharton:butterknife:8.4.0'
    apt 'com.jakewharton:butterknife-compiler:8.4.0'

}
apply plugin: 'com.google.gms.google-services'


I will get the file form gallery and upload on Firebase storage. Before upload user should be authenticate to give reference where he wants to upload. Here I have button for select picture from gallery and one more button to upload on firebase storage.

UserFragment.java

/**
 * Created by sunil on 11/16/16.
 */

public class UserFragment extends Fragment {

    public static final String TAG = UserFragment.class.getSimpleName();
    public static final int EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE = 2;

    @BindView(R.id.profile_image)
    CircleImageView profileImage;
    @BindView(R.id.select)
    Button select;
    @BindView(R.id.uplaod)
    Button uplaod;
    @BindView(R.id.cardView)
    CardView cardView;
    @BindView(R.id.register_user_email_edit_text)
    TextInputEditText registerUserEmailEditText;
    @BindView(R.id.email_container)
    TextInputLayout emailContainer;
    @BindView(R.id.update)
    Button update;

    private View rootView;
    OnFragmentInteractionListener mListener;
    DatabaseReference databaseRef;
    private FirebaseAuth mFirebaseAuth;
    FirebaseUser mFirebaseUser;
    StorageReference storageRef;
    private ProgressDialog mProgressDialog;

    private static final int SELECT_PICTURE = 100;
    private File mFile;
    Uri selectedImageUri;


    public static UserFragment newInstance() {
        UserFragment fragment = new UserFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {

        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        rootView = inflater.inflate(R.layout.fragment_userprofile, container, false);
        ButterKnife.bind(this, rootView);

        databaseRef = FirebaseDatabase.getInstance().getReference();
        mFirebaseAuth = FirebaseAuth.getInstance();
        // creating an instance of Firebase Storage
        FirebaseStorage firebaseStorage = FirebaseStorage.getInstance();
        storageRef =  firebaseStorage.getReference().child("photos");

        uplaod.setEnabled(false);

        getUserInfo();
        return rootView;
    }

    private void getUserInfo(){
        mFirebaseUser = mFirebaseAuth.getCurrentUser();
        if (mFirebaseUser != null) {
            String userId = mFirebaseUser.getUid();
            String email = mFirebaseUser.getEmail();
            registerUserEmailEditText.setText(email);
            DatabaseReference usernameRef = databaseRef.child(userId);
            Query queryRef = usernameRef.orderByKey();
            queryRef.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    String userProfileUrl = (String) dataSnapshot.child("userProfileUrl").getValue();
                    Log.e(TAG, "Profile Url: "+ userProfileUrl);
                    if (userProfileUrl != null && !userProfileUrl.isEmpty()){
                        Glide.with(getActivity()).load(userProfileUrl).into(profileImage);
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    Log.e(TAG, databaseError.getMessage());
                }
            });

        }


        //databaseReference.child(user.getUid()).child("userProfileUrl").setValue(22);
    }
    private void setUserProfile(String url){
        final String userId = SharedPreferenceUtils.getInstance(getActivity()).getUUID();
        databaseRef.child(userId).child("userProfileUrl").setValue(url);
    }

    @TargetApi(23)
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        onAttachToContext(context);
    }

        /*
         * Deprecated on API 23
         * Use onAttachToContext instead
         */


    @SuppressWarnings("deprecation")
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            onAttachToContext(activity);
        }
    }

    /*
     * Called when the fragment attaches to the activity
     */
    protected void onAttachToContext(Context context) {
        Activity activity = (Activity) context;
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        void updateProfileDone();
    }

    @OnClick(R.id.select)
    public void imageSelectFile(){
        if(checkPermissionForExternalStorage(getActivity())) {
            if(checkPermissionForCamera(getActivity())) {
                openFile();
            }
        }
    }

    @OnClick(R.id.uplaod)
    public void uploadClick(){
        if (mFile != null && mFile.exists()) {
            uploadFile(mFile, selectedImageUri );
        }else {
            Toast.makeText(getActivity(), "File does not exist", Toast.LENGTH_LONG).show();
        }

    }

    private void showProgressDialog() {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(getActivity());
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setIndeterminate(true);
        }

        mProgressDialog.show();
    }

    private void hideProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    private void uploadFile(File file, Uri fileUri){
        showProgressDialog();
        InputStream stream = null;
        try {
            stream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        if(stream != null){

            // Create a reference to "file"
            storageRef = storageRef.child(fileUri.getLastPathSegment());

            UploadTask uploadTask = storageRef.putStream(stream);
            uploadTask.addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                    hideProgressDialog();
                    Toast.makeText(getActivity(), "Uploading failed", Toast.LENGTH_LONG).show();
                    // Handle unsuccessful uploads
                }
            }).addOnSuccessListener(new OnSuccessListener() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    hideProgressDialog();
                    // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
                    Uri downloadUrl = taskSnapshot.getDownloadUrl();
                    Log.e("Url", "DownloadUrl: "+downloadUrl);
                    setUserProfile(downloadUrl.toString());
                    uplaod.setEnabled(false);
                    mListener.updateProfileDone();

                }
            });
        }
        else{
            Toast.makeText(getActivity(), "Getting null file", Toast.LENGTH_LONG).show();
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    public static boolean checkPermissionForCamera(Activity context) {
        int result = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA);
        if (result == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            ActivityCompat.requestPermissions(context, new String[]{Manifest.permission.CAMERA}, EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE);
            return false;
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    public static boolean checkPermissionForExternalStorage(Activity context) {
        int result = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (result == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            ActivityCompat.requestPermissions(context, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE);
            return false;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if(checkPermissionForCamera(getActivity())) {
                        openFile();
                    }
                } else {
                    Toast.makeText(getActivity(), "You have denied permission to access external storage. Please go to settings and enable access to use this feature", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    private void openFile(){
        Intent i = new Intent();
        i.setType("image/*");
        i.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(i, "Select Picture"), SELECT_PICTURE );
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
            if(requestCode==SELECT_PICTURE){
                selectedImageUri = data.getData();
                String path = getPath(getActivity(),selectedImageUri);
                mFile = new File(path);
                uplaod.setEnabled(true);
                if (null != selectedImageUri) {
                    // Get the path from the Uri
                    ContentResolver cr = getActivity().getContentResolver();
                    Bitmap bitmap;
                    try {
                        bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, selectedImageUri);
                        profileImage.setImageBitmap(bitmap);
                    } catch (Exception e) {
                        Log.e("Camera", e.toString());
                    }

                }
            }
        }

    @SuppressLint("NewApi")
    public static String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/"
                            + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"),
                        Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[] { split[1] };

                return getDataColumn(context, contentUri, selection,
                        selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri
                .getAuthority());
    }

    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri
                .getAuthority());
    }

    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri
                .getAuthority());
    }

    public static String getDataColumn(Context context, Uri uri,
                                       String selection, String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = { column };

        try {
            cursor = context.getContentResolver().query(uri, projection,
                    selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

}

Lest see our firebase console to check file had uploaded or not. Wow file is uploaded successfully.





Uploaded file that can access and download and showed on imageview. Please refer my snap shot.


Thanks for reading this article. I hope it will helps you to understand firebase storage.

No comments:

Post a Comment

Debug Database in Android

In my last tutorial, we have learned how we can use persistence database in android. We also understood which database wrapper we can use...

Contact Me

Name

Email *

Message *