Skip to content Skip to sidebar Skip to footer

Store Url In Firebase

I am relatively new to android development and I was attempting to save an image url from firebase storage to firebase realtime database. However, when I save the link to the real

Solution 1:

enter image description herethis is all working, First will try and understand how to firebase working. It's very easy enjoy.

MainActivity.java

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Patterns;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
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.File;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

importstatic android.widget.Toast.LENGTH_SHORT;



publicclassMainActivityextendsAppCompatActivity {

    private EditText inputEmail, inputPassword,f_name,l_name,phone;
    private Button  btnSignUp,back;
    private ProgressBar progressBar;
    private FirebaseAuth auth;

    FirebaseStorage storage;

    private DatabaseReference mCustomerDatabase,mCustomerDatabase1;

    ImageView profileImage;
    UriresultUri= Uri.parse("android.resource://com.example.chetan.printerprinting/" + R.drawable.ic_launcher_background);
    ProgressDialog progress;
    publicstaticfinalintPICK_IMAGE=1;

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        mCustomerDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child("Customers").child("UploadFile");

        storage = FirebaseStorage.getInstance();



            btnSignUp = (Button) findViewById(R.id.sign_up_button);
            inputEmail = (EditText) findViewById(R.id.email);
            inputPassword = (EditText) findViewById(R.id.password);
            f_name = (EditText) findViewById(R.id.f_name);
            l_name = (EditText) findViewById(R.id.l_name);
            phone = (EditText) findViewById(R.id.phone);
            back = (Button) findViewById(R.id.back);
            profileImage = (ImageView) findViewById(R.id.image_profile);





            profileImage.setOnClickListener(newView.OnClickListener() {
                @OverridepublicvoidonClick(View v) {

                    if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
                        selectPdf();
                    }
                    else {
                        ActivityCompat.requestPermissions(MainActivity.this,newString[]{Manifest.permission.READ_EXTERNAL_STORAGE},9);
                    }
                }
            });

            btnSignUp.setOnClickListener(newView.OnClickListener() {
                @OverridepublicvoidonClick(View v) {

                    finalStringemail= inputEmail.getText().toString().trim();
                    finalStringpassword= inputPassword.getText().toString().trim();
                    finalStringF_name= f_name.getText().toString().trim();
                    finalStringL_name= l_name.getText().toString().trim();
                    finalStringPhone= phone.getText().toString().trim();



                    if (TextUtils.isEmpty(F_name)) {
                        f_name.setError("Enter First Name!");
                        return;
                    }


                    if (TextUtils.isEmpty(L_name)) {
                        l_name.setError("Enter Last Name!");
                        return;
                    }


                    if (TextUtils.isEmpty(Phone)) {
                        phone.setError("Enter Phone Number!");
                        return;
                    }
                    if(isValidPhone(Phone)){

                        //Toast.makeText(getApplicationContext(),"Phone number is valid",Toast.LENGTH_SHORT).show();
                    }else {
                        phone.setError("Phone number is not valid");
                        // Toast.makeText(getApplicationContext(),"Phone number is not valid",Toast.LENGTH_SHORT).show();return;
                    }

                    if (TextUtils.isEmpty(email)) {
                        inputEmail.setError("Enter Email Address!");
                        return;
                    }
                    elseif (isValidEmail(email)){

                    }
                    else {
                        inputEmail.setError("Enter Valid Email Address!");
                        return;
                    }

                    if (TextUtils.isEmpty(password)) {
                        inputPassword.setError("Enter Password!");
                        return;
                    }

                    if (password.length() < 6) {
                        inputPassword.setError("Password too short, enter minimum 6 characters!");
                        return;
                    }



                                        MapuserInfo=newHashMap();
                                        userInfo.put("email", email);
                                        userInfo.put("password", password);
                                        userInfo.put("f_name", F_name);
                                        userInfo.put("l_name", L_name);
                                        userInfo.put("phone", Phone);

                                        mCustomerDatabase.updateChildren(userInfo);
                                        finalStringfileName= System.currentTimeMillis()+"";

                                        if(resultUri != null) {
                                            StorageReferencestorageReference= storage.getReference();
                                            storageReference.child("profileImageUrl").child(fileName).putFile(resultUri)
                                                    .addOnSuccessListener(newOnSuccessListener<UploadTask.TaskSnapshot>() {
                                                        @OverridepublicvoidonSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                                                            Stringurl= taskSnapshot.getDownloadUrl().toString();
                                                            mCustomerDatabase.child("profileImageUrl").setValue(url).addOnCompleteListener(newOnCompleteListener<Void>() {
                                                                @OverridepublicvoidonComplete(@NonNull Task<Void> task) {


                                                                    if (task.isSuccessful()){ }
                                                                    else{

                                                                        Toast.makeText(getApplicationContext(),"File not Successfully Uploaded",LENGTH_SHORT).show(); }
                                                                }
                                                            });
                                                        }
                                                    }).addOnFailureListener(newOnFailureListener() {
                                                @OverridepublicvoidonFailure(@NonNull Exception e) {

                                                    Toast.makeText(getApplicationContext(),"File not Successfully Uploaded",LENGTH_SHORT).show();

                                                }
                                            }).addOnProgressListener(newOnProgressListener<UploadTask.TaskSnapshot>() {
                                                @OverridepublicvoidonProgress(UploadTask.TaskSnapshot taskSnapshot) {

                                                }
                                            });
                                        }else{


                                        }

                                    }



            });

            back.setOnClickListener(newView.OnClickListener() {
                @OverridepublicvoidonClick(View v) {
                    onBackPressed();
                }
            });

        }



    publicbooleanisValidPhone(CharSequence phone) {
        boolean check=false;
        if(!Pattern.matches("[a-zA-Z]+", phone))
        {
            if(phone.length() < 10 || phone.length() > 11)
            {
                check = false;
            }
            else
            {
                check = true;
            }
        }
        else
        {
            check=false;
        }
        return check;
    }


    publicstaticbooleanisValidEmail(CharSequence target) {
        return (!TextUtils.isEmpty(target) && Patterns.EMAIL_ADDRESS.matcher(target).matches());
    }

    @OverridepublicvoidonRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNullint[] grantResults) {
        if (requestCode == 9 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
            selectPdf();
        }
        else{
            Toast.makeText(getApplicationContext(),"Please provide the permission", LENGTH_SHORT).show();

        }
    }


    privatevoidselectPdf() {

        Intentintent=newIntent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
        startActivityForResult(intent,86);
    }
    @OverrideprotectedvoidonActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 86 && resultCode == RESULT_OK && data != null){

            finalUriimageUri= data.getData();
            resultUri = imageUri;
            profileImage.setImageURI(resultUri);
        }
        else {
            Toast.makeText(getApplicationContext(),"Please select file", LENGTH_SHORT).show();
        }
    }






}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayoutxmlns: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"android:background="#FBFBFB"android:orientation="vertical"tools:context=".MainActivity"tools:layout_editor_absoluteY="25dp"><ScrollViewandroid:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><RelativeLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"><TextViewandroid:id="@+id/text"android:layout_width="match_parent"android:layout_height="wrap_content"android:textSize="30dp"android:textColor="#4B74FF"android:layout_marginRight="30dp"android:layout_marginLeft="30dp"android:text="Create an account"/><ImageViewandroid:id="@+id/image_profile"android:layout_width="match_parent"android:layout_height="150dp"android:layout_marginRight="50dp"android:layout_marginLeft="50dp"android:layout_below="@id/text"android:layout_marginTop="20dp"android:src="@drawable/ic_launcher_background" /><EditTextandroid:id="@+id/f_name"android:layout_width="match_parent"android:layout_height="wrap_content"android:hint="First Name"android:layout_marginTop="20dp"android:layout_marginRight="30dp"android:layout_marginLeft="30dp"android:layout_below="@id/image_profile"android:inputType="textEmailAddress"android:textColor="#aaa"android:fontFamily="monospace"android:textSize="22dp" /><Viewandroid:layout_width="match_parent"android:layout_height="2dp"android:layout_marginTop="-10dp"android:layout_marginLeft="30dp"android:layout_below="@id/f_name"android:layout_marginRight="30dp"android:background="#aaaaaa" /><EditTextandroid:id="@+id/l_name"android:layout_width="match_parent"android:layout_height="wrap_content"android:hint="Last Name"android:layout_marginTop="20dp"android:layout_marginRight="30dp"android:layout_marginLeft="30dp"android:layout_below="@id/f_name"android:inputType="textEmailAddress"android:textColor="#aaa"android:fontFamily="monospace"android:textSize="22dp" /><Viewandroid:layout_width="match_parent"android:layout_height="2dp"android:layout_marginTop="-10dp"android:layout_marginLeft="30dp"android:layout_below="@id/l_name"android:layout_marginRight="30dp"android:background="#aaaaaa" /><EditTextandroid:id="@+id/phone"android:layout_width="match_parent"android:layout_height="wrap_content"android:hint="Phone No."android:layout_marginTop="20dp"android:layout_marginRight="30dp"android:layout_marginLeft="30dp"android:layout_below="@id/l_name"android:inputType="phone"android:textColor="#aaa"android:fontFamily="monospace"android:textSize="22dp" /><Viewandroid:layout_width="match_parent"android:layout_height="2dp"android:layout_marginTop="-10dp"android:layout_marginLeft="30dp"android:layout_below="@id/phone"android:layout_marginRight="30dp"android:background="#aaaaaa" /><EditTextandroid:id="@+id/email"android:layout_width="match_parent"android:layout_height="wrap_content"android:hint="email"android:layout_marginRight="30dp"android:layout_marginTop="20dp"android:layout_marginLeft="30dp"android:layout_below="@id/phone"android:inputType="textEmailAddress"android:textColor="#aaa"android:fontFamily="monospace"android:textSize="22dp" /><Viewandroid:layout_width="match_parent"android:layout_height="2dp"android:layout_marginTop="-10dp"android:layout_marginLeft="30dp"android:layout_below="@id/email"android:layout_marginRight="30dp"android:background="#aaaaaa" /><EditTextandroid:id="@+id/password"android:layout_width="match_parent"android:layout_height="wrap_content"android:hint="password"android:layout_marginLeft="30dp"android:layout_marginRight="30dp"android:layout_marginTop="20dp"android:layout_below="@id/email"android:maxLength="11"android:inputType="textPassword"android:textColor="#aaa"android:textSize="22dp"
                /><Viewandroid:layout_width="match_parent"android:layout_height="2dp"android:layout_marginTop="-10dp"android:layout_marginLeft="30dp"android:layout_below="@id/password"android:layout_marginRight="30dp"android:background="#aaaaaa" /><Buttonandroid:id="@+id/sign_up_button"android:layout_width="match_parent"android:layout_height="wrap_content"android:textColor="@android:color/background_light"android:layout_marginTop="10dp"android:padding="20dp"android:layout_marginLeft="30dp"android:layout_marginRight="30dp"android:textSize="20dp"android:layout_marginBottom="10dp"android:layout_below="@id/password"android:textStyle="bold" /></RelativeLayout></ScrollView><!-- Link to Login Screen --></RelativeLayout>

hope use full

Post a Comment for "Store Url In Firebase"