Headertab

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Sunday 23 July 2017

Firebase Authentication and Rules in android

Hello friends, in this  blog, we will see how we can make User Authentication and apply Rules in Android by using Firebase as our Application back end.

Integrating Firebase Auth

If you integrate firebase auth in your app so follow all instruction carefully. Fist you create a new Android Project.

 


Now you go to Tool menu Tool>Firebase and now you see right side open Firebase Assistense and now go to Authentication options and click "Email and password authentication".






Now you click Connect to firebase . When click Connect to Firebase then open browser if you not login, now login your account then click "Add firebase Authentication to your app". See your gradle and left side project structure  add json file and code is automatic integrated and create your project on firebase check your project https://firebase.google.com/



Now add some code in your app's

MainActivity.java


package com.samset.firebaseauthentication;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.util.Log;
import android.view.View;
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;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;

    private EditText etUserId, etPassword;
    private AppCompatButton btnLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mAuth = FirebaseAuth.getInstance();
        initView();


        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String userId = etUserId.getText().toString();
                String password = etPassword.getText().toString();

                loginUser(userId, password);
            }
        });
        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    // User is signed in
                    Log.e("TAG", "User:signed_in:" + user.getUid());

                    startActivity(new Intent(MainActivity.this, DataUploadActivity.class));

                } else {
                    // User is signed out
                    Log.e("TAG", "User:signed_out");
                }
            }
        };

    }

    private void loginUser(String user, String pass) {
        mAuth.signInWithEmailAndPassword(user, pass)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        Log.e("TAG", "signInWithEmail:onComplete:" + task.isSuccessful());
                        if (!task.isSuccessful()) {

                            Toast.makeText(MainActivity.this, "Login failed", Toast.LENGTH_SHORT).show();
                            Log.e("TAG", "signInWithEmail:failed", task.getException());
                        } else {
                            Log.e("TAG", "signInWithEmail:success");
                            Toast.makeText(MainActivity.this, "Successfully Login", Toast.LENGTH_SHORT).show();
                            startActivity(new Intent(MainActivity.this, DataUploadActivity.class));
                        }
                    }
                });
    }

    @Override
    public void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mAuthListener != null) {
            mAuth.removeAuthStateListener(mAuthListener);
        }
    }

    private void initView() {
        etPassword = (EditText) findViewById(R.id.et_password);
        etUserId = (EditText) findViewById(R.id.et_username);
        btnLogin = (AppCompatButton) findViewById(R.id.btnLogin);

    }
}


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    tools:context="com.samset.firebaseauthentication.MainActivity">
    <TextView
        android:textColor="#000"
        android:text="Firebase Authentication"
        android:layout_gravity="center"
        android:layout_marginTop="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <EditText
        android:id="@+id/et_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="100dp"
        android:hint="User Id" />

    <EditText
        android:id="@+id/et_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="10dp"
        android:hint="Password" />

    <android.support.v7.widget.AppCompatButton
        android:id="@+id/btnLogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="10dp"
        android:text="Login" />

</LinearLayout>

Go to firebase console and click left menu Authentication.........


Now see three tab go to SIGN IN METHOD

Now click Email and Passsword row and enable toggle see below screenshot
 

 Finally  go to USERS tab and add your user account like abc@gmailcom and password 123456. see below screenshot


Now you complete authentication process launch your app and test firebase auth.

 DataUploadActivity.java

 package com.samset.firebaseauthentication;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.view.View;
import android.widget.EditText;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.util.HashMap;
import java.util.Map;

public class DataUploadActivity extends AppCompatActivity {
    private DatabaseReference database;
    private FirebaseAuth mAuth;
    private EditText etUser, etcontact;
    private AppCompatButton btnRegi,btnLogout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data_upload);
        mAuth = FirebaseAuth.getInstance();
        database = FirebaseDatabase.getInstance().getReference("Testing");
        etcontact = (EditText) findViewById(R.id.et_contact);
        etUser = (EditText) findViewById(R.id.et_user);
        btnRegi = (AppCompatButton) findViewById(R.id.btnRegi);
        btnLogout = (AppCompatButton) findViewById(R.id.btnlogout);


        btnRegi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String,String> map=new HashMap<String, String>();
                map.put("test",etUser.getText().toString());
                database.child("User").setValue(map);

            }
        });

        btnLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mAuth.signOut();
                startActivity(new Intent(DataUploadActivity.this, MainActivity.class));
                finish();

            }
        });
    }
}

dataupload_activity.xml

<?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.samset.firebaseauthentication.DataUploadActivity">
    <LinearLayout
        android:gravity="center"
        android:layout_gravity="center"
        android:orientation="vertical"
        android:layout_width="368dp"
        android:layout_height="wrap_content"
        tools:layout_editor_absoluteY="0dp"
        tools:layout_editor_absoluteX="8dp">
        <EditText
            android:id="@+id/et_user"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:hint="Name" />

        <EditText
            android:id="@+id/et_contact"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:layout_marginTop="10dp"
            android:inputType="number"
            android:hint="Contact" />

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/btnRegi"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="10dp"
            android:text="Send Data" />

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/btnlogout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="10dp"
            android:text="Logout" />


    </LinearLayout>
</android.support.constraint.ConstraintLayout>








See firebase database if user login with auth



Thank you


Saturday 1 July 2017

Why Nougat does not allow passing file:// with Intent

Hello friends


Android Nougat is almost be publicly released. And as an Android developer, we need to prepare ourself to adjust targetSdkVersion to the latest one, 24, to let everything works perfectly on the newest release of Android.


You may be curious why Android team decide to change this behavior. Actually there is a good reason behind.
If file path is sent to the target application (Camera app in this case), file will be fully accessed through the Camera app's process not the sender one.


But let's consider thoroughly, actually Camera is launched by our application to take a photo and save as a file on our app's behalf. So the access right to that file should be our app's not Camera's. Every operation did with the file should be done through our application not by Camera app itself.

And that's why file:// is now prohibited on targetSdkVersion 24 to force every developer to do this task in the proper way.


Solution 

So if file:// is not allowed anymore, which approach should we go for? 
The answer is we should send the URI through content:// scheme instead which is the URI scheme for Content Provider. In this case, we would like to share an access to a file through our app so FileProvider is needed to be implemented. Flow is now changed like below:







And now, with FileProvider, file operation would be done through our app process like it supposes to be !
It is quite easy to implement FileProvider on your application. 

First you need to add a FileProvider <provider> tag in AndroidManifest.xml under <application> tag like below:


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    ...
    <application
        ...
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>
    </application>
</manifest>



And then create a provider_paths.xml file in xml folder under res folder. Folder may be needed to create if it doesn't exist.
The content of the file is shown below. It describes that we would like to share access to the External Storage at root folder (path=".") with the name external_files.


res/xml/provider_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>


Done! FileProvider is now declared and be ready to use.
The final step is to change the line of code below in MainActivity.java


Uri photoURI = Uri.fromFile(createImageFile());

to

Uri photoURI = FileProvider.getUriForFile(MainActivity.this,
        BuildConfig.APPLICATION_ID + ".provider",
        createImageFile());



And .... done ! Your application should now work perfectly fine on any Android version including Android Nougat


If you not understand above process don't worry i describe with sample follow some easy steps....


MainActivity.java

import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import static android.R.attr.path;
import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE;
import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO;

public class MainActivity extends AppCompatActivity {
    private ImageView imageView;
    private int REQUEST_CAMERA = 101;
    private int PIC_CROP = 102;
    private Uri photoURI = null;
    private String IMAGE_DIRECTORY_NAME = "sample";
    //String path;

   
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = (ImageView) findViewById(R.id.iv);
        findViewById(R.id.btncamera).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                takePicture();
            }
        });
    }

    private void takePicture() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                File photoFile = getOutputMediaFile();
                photoURI = FileProvider.getUriForFile(MainActivity.this, getString(R.string.file_provider_authority), photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, REQUEST_CAMERA);
            }
        } else {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            photoURI = getOutputMediaFileUri();
            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(intent, REQUEST_CAMERA);

        }


    }

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

        if (resultCode == AppCompatActivity.RESULT_OK) {
            if (requestCode == REQUEST_CAMERA) {

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    imageView.setImageURI(photoURI);
                 
                } else {
                    try {

                        BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inSampleSize = 8;
                        final Bitmap bitmap = BitmapFactory.decodeFile(photoURI.getPath(), options);
                        //imageView.setImageBitmap(bitmap);
                       
                        // If you want croping use this
                       
performCrop(photoURI);
                    } catch (NullPointerException e) {
                        e.printStackTrace();
                    }
                }
            } else if (requestCode == PIC_CROP) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    Uri selectedImageUri = data.getData();
                    imageView.setImageURI(selectedImageUri);
                    Log.e("TAG", " onResult after crop pixel " + selectedImageUri);

                } else {
                    Uri selectedImageUri = data.getData();


                    if (selectedImageUri != null) {
                        imageView.setImageURI(selectedImageUri);

                    } else {

                        Bitmap selectedBitmap = (Bitmap) data.getExtras().get("data");
                        imageView.setImageBitmap(selectedBitmap);
                    }
                }

            }
        }
    }

    private void performCrop(Uri selectedImageUri) {
        try {
            Log.e("TAG", " get data crop " + selectedImageUri);
            Intent cropIntent = new Intent("com.android.camera.action.CROP");
            // indicate image type and Uri
           
cropIntent.setDataAndType(selectedImageUri, "image/*");
            // set crop properties
           
cropIntent.putExtra("crop", "true");
            // indicate aspect of desired crop
           
cropIntent.putExtra("aspectX", 1);
            cropIntent.putExtra("aspectY", 1);
            // indicate output X and Y
           
cropIntent.putExtra("outputX", 128);
            cropIntent.putExtra("outputY", 128);
            // retrieve data on return
           
cropIntent.putExtra("return-data", true);
            // start the activity - we handle returning in onActivityResult
           
if (getPackageManager() != null) {
                startActivityForResult(cropIntent, PIC_CROP);
            }

        } catch (Exception anfe) {
            anfe.printStackTrace();
            String errorMessage = "Whoops - your device doesn't support the crop action!";
            Log.e("TAG", " Croping error " + errorMessage);

        }
    }

    /**
     * Creating file uri to store image/video
     */
   
public Uri getOutputMediaFileUri() {
        return Uri.fromFile(getOutputMediaFile());
    }

    /*
     * returning image / video
     */
   
private File getOutputMediaFile() {

        // External sdcard location
       
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), IMAGE_DIRECTORY_NAME);

        // Create the storage directory if it does not exist
       
if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "+ IMAGE_DIRECTORY_NAME + " directory");
                return null;
            }
        }

        // Create a media file name
       
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
                Locale.getDefault()).format(new Date());
        File mediaFile;
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");

        return mediaFile;
    }
}


AndroidManifest.xml


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

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <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"
>
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="@string/file_provider_authority"
            android:exported="false"
            android:grantUriPermissions="true"
>
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_provider_path"
/>
        </provider>
        <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>


Thank you

FullSourceCode DownloadNougatCamera



Sample