This is a Light weight Library to Convert SQLite Database to Excel and Convert Excel to SQLite. I have already released version 1.0.0 . I...

SQLiteToExcel v1.0.1 SQLiteToExcel v1.0.1

A blog about android developement

SQLite2Excel
This is a Light weight Library to Convert SQLite Database to Excel and Convert Excel to SQLite. I have already released version 1.0.0. It is suitable to export SQLite Database to Excel. But, In version 1.0.1 I have Included following features

Features

  1. Added Functionality to Import Excel into SQLite Database.
  2. Added Functionality to Export Blob into Image.
  3. Added Functionality to Export List of tables specified.

Sample App

The sample app in the repository is available on Google Play:
Get it on Google Play

How to Download

Add the following library in your app level gradle file
compile 'com.ajts.androidmads.SQLite2Excel:library:1.0.1'

How to Use

Add Permission to Read External Storage in AndriodManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Export SQLite to Excel

This line is used to save the exported file in default location.
SqliteToExcel sqliteToExcel = new SqliteToExcel(this, "helloworld.db");
This line is used to save the exported file in used preferred location.
SqliteToExcel sqliteToExcel = new SqliteToExcel(this, "helloworld.db", directory_path);
This code snippet is used to Export a single table in a database to Excel Sheet
sqliteToExcel.exportSingleTable("table1", "table1.xls", new SQLiteToExcel.ExportListener() {
     @Override
     public void onStart() {

     }
     @Override
     public void onCompleted(String filePath) {

     }
     @Override
     public void onError(Exception e) {

     }
});
This following code snippet is used to Export a list of table in a database to Excel Sheet
sqliteToExcel.exportSpecificTables(tablesList, "table1.xls", new SQLiteToExcel.ExportListener() {
     @Override
     public void onStart() {

     }
     @Override
     public void onCompleted(String filePath) {

     }
     @Override
     public void onError(Exception e) {

     }
});
This code snippet is used to Export a every table in a database to Excel Sheet
sqliteToExcel.exportAllTables("table1.xls", new SQLiteToExcel.ExportListener() {
     @Override
     public void onStart() {

     }
     @Override
     public void onCompleted(String filePath) {

     }
     @Override
     public void onError(Exception e) {

     }
});

Import Excel into Database

The following snippet is used to initialize the library for Importing Excel
ExcelToSQLite excelToSQLite = new ExcelToSQLite(getApplicationContext(), "helloworld.db");
The following code is used to Import Excel from Assets
excelToSQLite.importFromAsset("assetFileName.xls", new ExcelToSQLite.ImportListener() {
    @Override
    public void onStart() {

    }

    @Override
    public void onCompleted(String dbName) {

    }

    @Override
    public void onError(Exception e) {

    }
});
The following code is used to Import Excel from user directory
excelToSQLite.importFromAsset(directory_path, new ExcelToSQLite.ImportListener() {
    @Override
    public void onStart() {

    }

    @Override
    public void onCompleted(String dbName) {

    }

    @Override
    public void onError(Exception e) {

    }
});
Please Visit the Wiki Link for full Guidance on SQLite2XL(v1.0.1).

Github Wiki Link

You can Download Full source code from Github. If you Like this library, Please star it in Github.

Github Link for Repo

Smart lock API By integrating Smart Lock for Passwords into your Android app, you can automatically sign users in to your app using t...

Smart Lock API in Android Smart Lock API in Android

A blog about android developement

Smart lock API
By integrating Smart Lock for Passwords into your Android app, you can automatically sign users in to your app using the credentials they have saved. Users can save both username-password credentials and federated identity provider credentials.

Integrate Smart Lock for Passwords into your app by using the Credentials API to retrieve saved credentials on sign-in. Use successfully retrieved credentials to sign the user in, or use the Credentials API to rapidly on-board new users by partially completing your app's sign in or sign up form. Prompt users after sign-in or sign-up to store their credentials for future automatic authentication.

Reference : Official Link

Project Setup

Smart Lock for Passwords on Android requires the following:
Add the following line in app level gradle file
compile 'com.google.android.gms:play-services-auth:10.0.1'
Then Click Sync Now

Coding Part

Create your activity with implements of 
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener 
In your activity add the following lines to initialize GoogleApiClient
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.enableAutoManage(this, 0, this)
.addApi(Auth.CREDENTIALS_API)
.build();
Save Credentials:

You can save your username and password credentials by passing as in the following:
String username = mUsernameTextInputLayout.getEditText().getText().toString();
String password = mPasswordTextInputLayout.getEditText().getText().toString();
Credential credential = new Credential.Builder(username)
                        .setPassword(password)
                        .build();
Pass your credentials to Save method
protected void saveCredential(Credential credential) {
        // Credential is valid so save it.
        Auth.CredentialsApi.save(mGoogleApiClient,
                credential).setResultCallback(new ResultCallback() {
            @Override
            public void onResult(Status status) {
                if (status.isSuccess()) {
                    Log.d(TAG, "Credential saved");
                    goToContent();
                } else {
                    Log.d(TAG, "Attempt to save credential failed " +
                            status.getStatusMessage() + " " +
                            status.getStatusCode());
                    resolveResult(status, RC_SAVE);
                }
            }
        });
    }
Following Method is used to process the status of saving your credentials
private void resolveResult(Status status, int requestCode) {
 // We don't want to fire multiple resolutions at once since that
 // can   result in stacked dialogs after rotation or another
 // similar event.
 if (mIsResolving) {
  Log.w(TAG, "resolveResult: already resolving.");
  return;
 }

 Log.d(TAG, "Resolving: " + status);
 if (status.hasResolution()) {
  Log.d(TAG, "STATUS: RESOLVING");
  try {
   status.startResolutionForResult(this, requestCode);
   mIsResolving = true;
  } catch (IntentSender.SendIntentException e) {
   Log.e(TAG, "STATUS: Failed to send resolution.", e);
  }
 } else {
  Log.e(TAG, "STATUS: FAIL");
  if (requestCode == RC_SAVE) {
   goToContent();
  }
 }
}
OnActivityResult shows in the output of saving your credentials
public void onActivityResult(int requestCode, int resultCode, Intent data) {
 super.onActivityResult(requestCode, resultCode, data);
 Log.d(TAG, "onActivityResult:" + requestCode + ":" + resultCode + ":" + data);
 if (requestCode == RC_SAVE) {
  Log.d(TAG, "Result code: " + resultCode);
  if (resultCode == RESULT_OK) {
   Log.d(TAG, "Credential Save: OK");
  } else {
   Log.e(TAG, "Credential Save Failed");
  }
  goToContent();
 }
 if (requestCode == RC_READ) {
  if (resultCode == RESULT_OK) {
   Credential credential = data.getParcelableExtra(Credential.EXTRA_KEY);
   processRetrievedCredential(credential);
  } else {
   Log.e(TAG, "Credential Read: NOT OK");
  }
 }
}
/**
 * Start the Content Activity and finish this one.
 */
protected void goToContent() {
 startActivity(new Intent(this, ContentActivity.class));
 finish();

}
Retrieve Credentials:

Retrieve your saved credentials from your account and made your login process easier
private void requestCredentials() {
Log.d(TAG, "requestCredentials");
CredentialRequest request = new CredentialRequest.Builder()
  .setPasswordLoginSupported(true)
  .build();

Auth.CredentialsApi.request(mGoogleApiClient, request).setResultCallback(
 new ResultCallback() {
 @Override
 public void onResult(@NonNull CredentialRequestResult credentialRequestResult) {
  Status status = credentialRequestResult.getStatus();
  Log.v(TAG, status.getStatus().toString());
  if (credentialRequestResult.getStatus().isSuccess()) {
   Credential credential = credentialRequestResult.getCredential();
   processRetrievedCredential(credential);
  } else if (status.getStatusCode() == CommonStatusCodes.SIGN_IN_REQUIRED) {
   Log.d(TAG, "Sign in required");
  } else if (status.getStatusCode() == CommonStatusCodes.RESOLUTION_REQUIRED) {
   Log.w(TAG, "Unrecognized status code: " + status.getStatusCode());
   try {
    status.startResolutionForResult(MainActivity.this, RC_READ);
   } catch (IntentSender.SendIntentException e) {
    Log.e(TAG, "STATUS: Failed to send resolution.", e);
   }
  }
 }
    });
}
Download Code:

You can download the full source from the following Github link. If you Like this tutorial, Please star it in Github.
    
Download From Github

Post your doubts and comments in the comments section.  

SQLiteToExcel is a Light weight Library to Convert SQLite Database to Excel. I have Released Newer Version for this Library. If your Requ...

SQLiteToExcel - v1.0.0 SQLiteToExcel - v1.0.0

A blog about android developement

SQLite2Excel
SQLiteToExcel is a Light weight Library to Convert SQLite Database to Excel. I have Released Newer Version for this Library. If your Requirement is only to export your SQLite Database, then this library is very much suitable. Otherwise you requirement is to import or export excel to db or vice-versa, then you go for my newer release. Please visit here to see about SQLite2XL Version 1.0.1

How to Download

add the following library in your app level gradle file
compile 'com.ajts.androidmads.SQLite2Excel:library:1.0.0'

How to Use

1.AndroidManifest.xml
Add the following line in your Manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
2.Library Initialization 
This line is used to save the exported file in default location.
SqliteToExcel sqliteToExcel = new SqliteToExcel(this, "helloworld.db");
This line is used to save the exported file in used preferred location.
SqliteToExcel sqliteToExcel = new SqliteToExcel(this, "helloworld.db", directory_path);
3.Export DB to Excel 
This code snippet is used to Export a single table in a database to Excel Sheet
sqliteToExcel.startExportSingleTable("table1", "table1.xls", new ExportListener() {
   
 @Override
 public void onStart() {
  
 }
   
 @Override
 public void onError() {
  
 }
   
 @Override
 public void onComplete() {
  
 }
});
This code snippet is used to Export a every table in a database to Excel Sheet
sqliteToExcel.startExportAllTables("helloworlddb.xls", new ExportListener() {
   
 @Override
 public void onStart() {
  
 }
   
 @Override
 public void onError() {
  
 }
   
 @Override
 public void onComplete() {
  
 }
});
Please Visit the Wiki Link for full Guidance on SQLite2XL(v1.0.0). If you Like this library, Please star it in Github.

Github Wiki Link

Every Android Developer knows about the Snackbar , which is an important component introduced in Material Design. It is similar to Toast ...

How to Customize Snack Bar in Android How to Customize Snack Bar in Android

A blog about android developement

Custom Snackbar
Every Android Developer knows about the Snackbar, which is an important component introduced in Material Design. It is similar to Toast used for android Development. But the Snackbar had provides action callback to perform action like Click-listeners in Button. In this article, we are going to learn How to Customize the Snackbar.

Summary

We are going learn,
  1. Implementation of Default Snackbar
  2. Implementation of Snackbar with action callback
  3. Snackbar with custom gravity for message text
  4. Snackbar with custom color
  5. Snackbar with custom text color for message and action.
  6. Snackbar with custom typeface for message text and action text.
  7. Implementation of Top Snackbar

Implementation of Default Snackbar

Below is the syntax of a simple Snackbar. The make function accepts three parameters. View, display message and duration of the message to be displayed.
Snackbar.make(v, "Normal Snackbar", Snackbar.LENGTH_LONG).show();
Default Snackbar

Implementation of Snackbar with action callback

Below is the syntax to display snackbar with action callback
Snackbar.make(v, "Snackbar with Action", Snackbar.LENGTH_LONG)
.setAction("UNDO", new View.OnClickListener() {
        @Override
        public void onClick(View view) {
               Snackbar.make(view, "Action!", Snackbar.LENGTH_SHORT).show();
        }
}).setActionTextColor(Color.RED).show();
Snackbar with action callback

Snackbar with custom gravity for message text

Below is the syntax to display snackbar with custom gravity
Snackbar mSnackBar = Snackbar.make(v, "Snackbar with Custom Gravity", Snackbar.LENGTH_LONG);
TextView mainTextView = (TextView) (mSnackBar.getView()).findViewById(android.support.design.R.id.snackbar_text);
 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
    mainTextView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
 else
    mainTextView.setGravity(Gravity.CENTER_HORIZONTAL);
mainTextView.setGravity(Gravity.CENTER_HORIZONTAL);
mSnackBar.show();
Snackbar with custom gravity for message text

Snackbar with custom color

Below is the syntax to display snackbar with custom color
Snackbar mSnackBar = Snackbar.make(v, "Custom Snackbar", Snackbar.LENGTH_LONG);
// To Change Snackbar Color
mSnackBar.getView().setBackgroundColor(Color.WHITE);
mSnackBar.show();

Snackbar with custom text color for message and action

Below is the syntax to display snackbar with custom text color
Snackbar mSnackBar = Snackbar.make(v, "Custom Snackbar", Snackbar.LENGTH_LONG);
TextView mainTextView = (TextView) (mSnackBar.getView()).findViewById(android.support.design.R.id.snackbar_text);
TextView actionTextView = (TextView) (mSnackBar.getView()).findViewById(android.support.design.R.id.snackbar_action);
// To Change Text Color for Message and Action
mainTextView.setTextColor(Color.BLACK);
actionTextView.setTextColor(Color.BLACK);
mSnackBar.show();

Snackbar with custom typeface for message text and action text

Below is the syntax to display snackbar with custom Typeface
Snackbar mSnackBar = Snackbar.make(v, "Custom Snackbar", Snackbar.LENGTH_LONG);
TextView mainTextView = (TextView) (mSnackBar.getView()).findViewById(android.support.design.R.id.snackbar_text);
TextView actionTextView = (TextView) (mSnackBar.getView()).findViewById(android.support.design.R.id.snackbar_action);
// To Apply Custom Fonts for Message and Action
Typeface font = Typeface.createFromAsset(getAssets(), "Lato-Regular.ttf");
mainTextView.setTypeface(font);
actionTextView.setTypeface(font);
mSnackBar.show();
Customized Snackbar

Implementation of Top Snackbar

Below is the syntax to display snackbar from screen Top
 Snackbar mSnackBar = Snackbar.make(v, "TOP SNACKBAR", Snackbar.LENGTH_LONG);
View view = mSnackBar.getView();
FrameLayout.LayoutParams params =(FrameLayout.LayoutParams)view.getLayoutParams();
params.gravity = Gravity.TOP;
view.setLayoutParams(params);
view.setBackgroundColor(Color.RED);
TextView mainTextView = (TextView) (view).findViewById(android.support.design.R.id.snackbar_text);
mainTextView.setTextColor(Color.WHITE);
mSnackBar.show();
Top Snackbar

For Full Reference, Download whole source code from the github link and post your comments. If you like this post, provide one star in Github or Like my Page. For any suggestions, feel free to post comments.
For more, Details Please download whole project source from Github.

Download From Github

In this android tutorial, I am going to show how to use Android ButterKnife View Binding in android application development. If you have...

Android ButterKnife View Binding Android ButterKnife View Binding

A blog about android developement

Android ButterKnife View Binding

In this android tutorial, I am going to show how to use Android ButterKnife View Binding in android application development. If you have been developing android application, you will realized that there are lots of boilerplate codes in your application. In some cases, it will be too much that the onCreate() method will be bloated with boilerplate codes. This is where Android ButterKnife comes to your help.

How it can help us to improve your code

  1. Eliminate findViewById calls by using @BindView on fields. 
  2. Group multiple views in a list or array. Operate on all of them at once with actions, setters, or properties. 
  3. Eliminate anonymous inner-classes for listeners by annotating methods with @OnClick and others. Eliminate resource lookups by using resource annotations on fields. 
In this post, I am going to show the method of using ButterKnife in RecyclerView and Each Single Views.

Creating New Project with Android Studio

  1. Open Android Studio and Select create a new project.
  2. Name the project as per your wish and select an Empty activity.
    Android
    Figure 1
  3. Click finish button to create a new project in Android Studio.

Project Setup: 

Open App Level build.gradle file and add the following lines as mentioned.
...
// add the below lines in dependencies
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
...

Coding Part

Method to use ButterKnife: In your Activity, add the following line
// Initialize ButterKnife 
ButterKnife.bind(this);
Each View is initialized as in the following
@BindView(R.id.title)
public TextView title;
RecyclerView is initialized as in the following
@BindView(R.id.recycler)
public RecyclerView recyclerView;
Create ToDoViewHolder.java and Paste the following code
class ToDoViewHolder extends RecyclerView.ViewHolder{

    @BindView(R.id.todo_type)
    TextView todoType;
    @BindView(R.id.todo)
    TextView todo;

    ToDoViewHolder(View itemView) {
        super(itemView);
        ButterKnife.bind(this, itemView);
    }

}
Create ToDoObject.java and add the following lines
class ToDoObject {
    private String todoType;
    private String todoName;

    ToDoObject(String todoType, String todoName) {
        this.todoType = todoType;
        this.todoName = todoName;
    }

    String getTodoType() {
        return todoType;
    }

    String getTodoName() {
        return todoName;
    }

}
Create ToDoAdapter.java and add the following lines
class ToDoAdapter extends RecyclerView.Adapter {
    private Context context;
    private List toDoObjectList;

    ToDoAdapter(Context context, List toDoObjectList) {
        this.context = context;
        this.toDoObjectList = toDoObjectList;
    }

    @Override
    public ToDoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.list_row, parent, false);
        return new ToDoViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ToDoViewHolder holder, final int position) {
        ToDoObject toDoObject = toDoObjectList.get(position);
        holder.todoType.setText(toDoObject.getTodoType());
        holder.todo.setText(toDoObject.getTodoName());

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(context, "Selected index " + position, Toast.LENGTH_LONG).show();
            }
        });
    }

    @Override
    public int getItemCount() {
        return toDoObjectList.size();
    }
}
Finally Create ToDoActivity.java and call your Adapter as usual for RecyclerView. The Complete Code for ToDoActivity.java is given below
public class ToDoActivity extends AppCompatActivity {

    @BindView(R.id.toolbar)
    public Toolbar toolbar;

    @BindView(R.id.fab)
    public FloatingActionButton fab;

    @BindView(R.id.recycler)
    public RecyclerView recyclerView;

    @BindView(R.id.title)
    public TextView title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        setSupportActionBar(toolbar);

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        title.setText("ToDo List");
        title.setTextSize(20);

        LinearLayoutManager layoutManager = new LinearLayoutManager(ToDoActivity.this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);
        ToDoAdapter mAdapter = new ToDoAdapter(ToDoActivity.this, getTestData());
        recyclerView.setAdapter(mAdapter);

    }

    public List getTestData() {
        List cars = new ArrayList<>();
        cars.add(new ToDoObject("Shopping", "Cake"));
        cars.add(new ToDoObject("Shopping", "Cloth"));
        cars.add(new ToDoObject("Shopping", "Color Paper"));
        cars.add(new ToDoObject("HomeWork", "Science"));
        cars.add(new ToDoObject("HomeWork", "Maths"));
        cars.add(new ToDoObject("HomeWork", "Chemistry"));
        return cars;
    }

}
For Full Reference, Download whole source code from the github link and post your comments. If you like this post, provide one star in Github or Like my Page. For any suggestions, feel free to post comments.

For more, Details Please download whole project source from Github.

Download From Github

Firebase Cloud Messaging (FCM) is the new version of GCM. It inherits the reliable and scalable GCM infrastructure, plus new features...

Firebase Cloud Messaging in Android Firebase Cloud Messaging in Android

A blog about android developement

Firebase Cloud Messaging in Android

Firebase Cloud Messaging (FCM) is the new version of GCM. It inherits the reliable and scalable GCM infrastructure, plus new features. If you are integrating messaging in a new app, start with FCM. GCM users are strongly recommended to upgrade to FCM, in order to benefit from new FCM features today and in the future.

Firebase Cloud Messaging is very easy to integrate into your Application. Just like GCM, FCM is a cross-platform messaging solution that allows you to send messages. FCM is completely free and there are no limitations

Firebase Setup

The Feature and Settings up of Application in Application is Explained in Previous post. After this, follow the tutorial as in below. In This post, I am not explaining about any Layouts. Simply explains the Java code build to FCM Application.

Adding Firebase Messaging to Your Project

  • Now come back to your android project. Go to app folder and paste google-services.json file.
  • Now go to your root level build.gradle file and add the following code
// Add this line
classpath 'com.google.gms:google-services:3.0.0'
  • Inside app level build.gradle file make the following changes.
// Add this line
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.0.0'
    compile 'com.google.firebase:firebase-core:9.0.2'
    compile 'com.google.firebase:firebase-messaging:9.0.2'
}
apply plugin: 'com.google.gms.google-services'

Implementing Firebase Cloud Messaging

Create a class named  FireBaseInstanceIDService.java and write the following code.
// Add this line
public class FireBaseInstanceIDService extends FirebaseInstanceIdService {

    private static final String TAG = FireBaseInstanceIDService.class.getSimpleName();
    public static final String REGISTRATION_SUCCESS = "RegistrationSuccess";
    public static final String REGISTRATION_TOKEN = "token";

    @Override
    public void onTokenRefresh() {
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed_token: " + refreshedToken);

        // Used to get Device token to store in database 
        Intent intent1 = new Intent(REGISTRATION_SUCCESS);
        intent1.putExtra(REGISTRATION_TOKEN, refreshedToken);
        sendBroadcast(intent1);
    }

}
Create a class named  FireBaseMessagingService.java and write the following code.
// Add this line
private static final String TAG = FireBaseMessagingService.class.getSimpleName();

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        //Displaying data in log
        //It is optional
        Log.d(TAG, "remoteMessage: " + remoteMessage);
        //Calling method to generate notification
        sendNotification(remoteMessage.getNotification().getBody());
    }

    //This method is only generating push notification
    //It is same as we did in earlier posts
    private void sendNotification(String messageBody) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("FireBase Push Notification")
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, notificationBuilder.build());
    }
  • Now we have to define the above services in our AndroidManifest.xml file. Don't forget to add Internet Permission.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidmads.firebasecloudmessaging">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        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=".FireBaseMessagingService" >
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <service android:name=".FireBaseInstanceIDService" >
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>
    </application>

</manifest>

  • Thats all. Now run your app (Make sure your device is having google play service or else it won’t work). After running you will see the token in the logcat or in your Main Screen. Copy the token.

Sending Push Notification using Firebase Console :
  • Go to firebase console and select the app you created.
  • From the left menu select notification.
  • Click on new message.
  • Enter message, select single device and paste the token you copied and click on send

For more, Details Please download whole project source from Github.

Download From Github

If you find this post is useful, Please provide star in Github and Having any trouble or doubt while using this project leave your comment.

Firebase provides more features as described in previous post . One of the very useful feature is User Authentication. Different types o...

Firebase User Authentication in Android Firebase User Authentication in Android

A blog about android developement

Firebase User authentication
Firebase provides more features as described in previous post. One of the very useful feature is User Authentication. Different types of User Authentication are,
  1. Email and Password Authentication
  2. Google Plus Authentication
  3. Facebook Authentication
  4. Github Authentication
In this post, I will explain the way to implement Firebase Email & Password authentication. To demonstrate how simplified and easy to use Firebase is, we will build a simple login / register (Firebase Authentication) demo. This separates sensitive user credentials from your application data, and lets you focus on the user interface and experience for your Application. It is suitable for Simple, Easy and Perfect way of handling Login, Registration, Forget Password and so on.

The Feature and Settings up of Application in Application is Explained in Previous post. After creating the project, Enable Firebase Email & Password authentication by selecting Authentication in Left Pane in Firebase Console and Go to Sign-in-Method as in the following Image.

Enable Authentication

I. Creating and Setting up Android Project

1. Create a new project in Android Studio from File ⇒ New Project. When it prompts you to select the default activity, select Blank Activity and proceed. While filling the project details, use the same package name which you gave in Firebase console.

2. Open AndroidManifest.xml and add the INTERNET permission as we need to make network calls.
<uses-permission android:name="android.permission.INTERNET" />

3. Paste the google-services.json file to your project’s app folder. This step is very important as your project won’t build without this file.

4. Now open the build.gradle located in project’s home directory and add firebase dependency.
build.gradle
dependencies {
 classpath 'com.android.tools.build:gradle:2.1.2'
 classpath 'com.google.gms:google-services:3.0.0'
}
5. Open app/build.gradle and add firebase auth dependency. At the very bottom of the file, add apply plugin: ‘com.google.gms.google-services’
app/build.gradle
dependencies {
    compile "com.google.firebase:firebase-auth:9.0.2"
}
apply plugin: 'com.google.gms.google-services'

II. Coding Part

1. Sign Up Method:

In Firebase Authentication, the credits entered by user might have some validation. For Example, Email ID might be in Proper email format and Password must have at-least 6 character. Firebase Provides createUserWithEmailAndPassword() to create New User in Firebase.
// Validating Credits entered by User with Firebase
btnSignUp.setOnClickListener(new View.OnClickListener() {
 @Override
    public void onClick(View view) {
  final String email = inputEmail.getText().toString();
  final String password = inputPassword.getText().toString();
  try {
   // Email ID must be valid
   // Password strength is minimum 6 characters by default in firebase registration
   // Minimum Password length throws Error as 'WEAK PASSWORD'
   if (password.length() > 0 && email.length() > 0) {
    PD.show();
    //authenticate user
    auth.createUserWithEmailAndPassword(email, password)
     .addOnCompleteListener(RegisterActivity.this, new OnCompleteListener() {
      @Override
      public void onComplete(@NonNull Task task) {
      if (!task.isSuccessful()) {
       Toast.makeText(
       RegisterActivity.this,
       "Authentication Failed",
       Toast.LENGTH_LONG).show();
      } else {
       Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
       startActivity(intent);
       finish();
      }
      PD.dismiss();
     }
    });
   } else {
     Toast.makeText(
      RegisterActivity.this,
      "Fill All Fields",
      Toast.LENGTH_LONG).show();
   }

  } catch (Exception e) {
   e.printStackTrace();
  }
 }
});

2. Sign In Method:

Firebase provides signInWithEmailAndPassword() method to sign in the user.
// Validating Login Credits with Firebase
btnLogin.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View view) {
  final String email = inputEmail.getText().toString();
  final String password = inputPassword.getText().toString();
  try {
   if (password.length() > 0 && email.length() > 0) {
    PD.show();
    // Authenticate user
    auth.signInWithEmailAndPassword(email, password)
      .addOnCompleteListener(LoginActivity.this, new OnCompleteListener() {
       @Override
       public void onComplete(@NonNull Task task) {
        if (!task.isSuccessful()) {
         Toast.makeText(
           LoginActivity.this,
           "Authentication Failed",
           Toast.LENGTH_LONG).show();
         Log.v("error", task.getResult().toString());
        } else {
         Intent intent = new Intent(LoginActivity.this, MainActivity.class);
         startActivity(intent);
         finish();
        }
        PD.dismiss();
       }
      });
   } else {
    Toast.makeText(
      LoginActivity.this,
      "Fill All Fields",
      Toast.LENGTH_LONG).show();
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
});

3. Forget Password:

Firebase provides sendPasswordResetEmail() method to reset password. Automatically, Reset Password email send to your entered email. To reset password, Click the link in your email. We can customize the Email Template.
// Method to Reset Password or Forget Password Option
auth.sendPasswordResetEmail(modeStr).addOnCompleteListener(new OnCompleteListener() {
 @Override
 public void onComplete(@NonNull Task task) {
  if (task.isSuccessful()) {
   Toast.makeText(ForgetAndChangePasswordActivity.this, "We have sent you instructions to reset your password!", Toast.LENGTH_SHORT).show();
  } else {
   Toast.makeText(ForgetAndChangePasswordActivity.this, "Failed to send reset email!", Toast.LENGTH_SHORT).show();
  }
  PD.dismiss();
 }
});

4. Change Username or Password:

Firebase provides updatePassword() to change password and updateEmail() to change Email ID.
// Method to change Password Option
user.updatePassword(modeStr)
 .addOnCompleteListener(new OnCompleteListener() {
  @Override
  public void onComplete(@NonNull Task task) {
   if (task.isSuccessful()) {
    Toast.makeText(ForgetAndChangePasswordActivity.this, "Password is updated!", Toast.LENGTH_SHORT).show();
   } else {
    Toast.makeText(ForgetAndChangePasswordActivity.this, "Failed to update password!", Toast.LENGTH_SHORT).show();
   }
   PD.dismiss();
  }
 });
 
// Method to Change Email or Username Option
user.updateEmail(modeStr)
 .addOnCompleteListener(new OnCompleteListener() {
  @Override
  public void onComplete(@NonNull Task task) {
   if (task.isSuccessful()) {
    Toast.makeText(ForgetAndChangePasswordActivity.this, "Email address is updated.", Toast.LENGTH_LONG).show();
   } else {
    Toast.makeText(ForgetAndChangePasswordActivity.this, "Failed to update email!", Toast.LENGTH_LONG).show();
   }
   PD.dismiss();
  }
 });
 

5. Delete User or Account:

Firebase Provides delete() method to delete account.
// Method to Remove Account Option
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
 user.delete()
  .addOnCompleteListener(new OnCompleteListener() {
   @Override
   public void onComplete(@NonNull Task task) {
    if (task.isSuccessful()) {
     Toast.makeText(ForgetAndChangePasswordActivity.this, "Your profile is deleted:", Toast.LENGTH_SHORT).show();
    } else {
     Toast.makeText(ForgetAndChangePasswordActivity.this, "Failed to delete your account!", Toast.LENGTH_SHORT).show();
    }
    PD.dismiss();
   }
  });
}

6. Sign out Session:

Firebase provides signOut() method to Sign out from Firebase session.
// Sign-Out option
btnSignOut.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View view) {
  auth.signOut();
  // this listener will be called when there is change in firebase user session
  FirebaseAuth.AuthStateListener authListener = new FirebaseAuth.AuthStateListener() {
   @Override
   public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
    FirebaseUser user = firebaseAuth.getCurrentUser();
    if (user == null) {
     startActivity(new Intent(MainActivity.this, LoginActivity.class));
     finish();
    }
   }
  };
 }
});

7. Checking User Session:

The following method is used to check User is Signed In or Not.
//Checking user is present or not
FirebaseAuth auth = FirebaseAuth.getInstance();
if (auth.getCurrentUser() != null) {
 Log.v("Session", "Signed In");
}

Download Source Code

In this, I explained each method to handle firebase Email/Password method and am not explaining the layout of each screen in this Project. For more, Details Please download whole project source from Github.

Download From Github

If you find this post is useful, Please provide star in Github and Having any trouble or doubt while using this project leave your comment.

With the latest news from Google I/O comes the new and upgraded Firebase. Firebase is a mobile platform that helps you quickly develop h...

Android Getting Started with Firebase Android Getting Started with Firebase

A blog about android developement

Android Getting Started with Firebase
With the latest news from Google I/O comes the new and upgraded Firebase. Firebase is a mobile platform that helps you quickly develop high-quality apps, grow your user base, and earn more money. Firebase is made up of complementary features that you can mix-and-match to fit your needs.
Features of Firebase:
Firebase comes with bunch features essential for every android app starting from authentication to hosting the app.
Advantages of using Firebase:
  1. Super easy and quick to implement.
  2. No server side configuration needed. No PHP Scripts and No Database Designs.
  3. Realtime update without using GCM.
  4. Autoscaling built-in
  5. Can start for free (only need to start paying once we hit 50 connections)
  6. Robust APIs for Javascript (including several frameworks like Angular), iOS, and Android
  7. Built-in support for authentication services like Facebook, Google, and Twitter
  8. Declarative Security Rules model allows us to enforce read/write privileges and data validation throughout the tree
Disadvantages of using Firebase:
  1. Need to build indexes manually
  2. May need to build “event log” manually as well (in separate sub-tree?)
  3. Implementation of REST API could be difficult on embedded platforms
  4. Data validation rules do not support complex objects directly (you’d need to validate individual child nodes separately)

Setting up Firebase Project:
In this post, I explained how to setup firebase for your Android Project. This method is common for all type of services offered by Firebase such as User Authentication, Realtime Database, Cloud Messaging and so on. Do the following steps for setting up your project and it is common for all services in firebase.
  1. First thing you need to do is go to https://firebase.google.com/ and make an account to gain access to their console. After you gain access to the console you can start by creating your first project.
  2. Give the package name of your project (for example FirebaseSample) in which you are going to integrate the Firebase. It redirects to Firebase Dashboard.
  3. Here, you select your project type and Here I selected Android Project.
  4. Then paste your package name as in your manifest file.(com.example.firebase).
  5. Now the google-services.json file will be downloaded when you press add app button
  6. Add this file to your app folder of your Project.

Steps to setup Firebase

Steps to setup Firebase
Steps to setup Firebase


Steps to setup Firebase


It is common to all services in Firebase, Only the application's specification are differing based on the Gradle Dependencies. The Services offered by Firebase and their Integration to android application are demonstrated in further posts.

Hi Friends, I will show you how to use Google Forms as Back-End.  For On-line application we have a separate table for feedback from...

Google Form to Android Application Google Form to Android Application

A blog about android developement


Hi Friends, I will show you how to use Google Forms as Back-End.  For On-line application we have a separate table for feedback from users. But, In off-line applications like Music player we will not connect any databases.
To get real-time feedback we can go for Firebase.

But, Firebase has some CONS:
1.Data stored in JSON like Format.
2.Free account of Firebase has Limitation and for Unlimited Access we have to pay some amount per month.

To avoid these CONS, we can connect Google Forms as Back-end

PROS of using this method:
1.It provides real time user-friendly response
2.Cost Free
3.Easy to Integrate

CREATE A GOOGLE FORM
First thing you need to do is login to drive.google.com and create a new “Google Form”. After Creating your Google Form, get your share link from Forms. Your link looks like below
https://docs.google.com/forms/d/e/1FAIpQLScIpmqndQeQG3lFbj0QkQ1Kt6tEXoPrOt314AZGQ2WKuK8IvA/viewform
This URL needs to be converted to be used for sending data from code. The conversion very easy, just replace “viewform” in the URL to “formResponse”.
Thus, our POST URL becomes
https://docs.google.com/forms/d/e/1FAIpQLScIpmqndQeQG3lFbj0QkQ1Kt6tEXoPrOt314AZGQ2WKuK8IvA/formResponse
The tricky part of using Google Forms to post data for these fields via code, we need to make a POST request with the data attached as key-value pair. Values being the data entered by your user in the app and the keys being the ids of input fields on the form.

To get the keys, right click on each TextBox and select “Inspect Element”. Take Fields name from form and which looks like entry.737865382.

Google Form to Android Application

CODING PART
In this, you have create your android project and Import any HTTP Library. In my sample, I used VOLLEY as my HTTP Library.
AndroidManifest.xml
Add INTERNET Permission in AndroidManifest file in your project.
Internet Permission
<uses-permission android:name="android.permission.INTERNET" />
Layout
Create your Layout file named as activity_main.xml and paste the following code.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.androidmads.postdatatogoogledocs.MainActivity"
    tools:showIn="@layout/activity_main">

    <android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/edtName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="Name"
            android:inputType="textPersonName" />
    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/edtPhone"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="Phone Number"
            android:inputType="phone"
            android:maxLength="10" />
    </android.support.design.widget.TextInputLayout>
</LinearLayout>
Function to post Data:
Following function is used to post data to Google Form
public void postData(final String name, final String phone) {

        progressDialog.show();
        StringRequest request = new StringRequest(
                Request.Method.POST,
                Constants.url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d("TAG", "Response: " + response);
                        if (response.length() > 0) {
                            Snackbar.make(fab, "Successfully Posted", Snackbar.LENGTH_LONG).show();
                            edtName.setText(null);
                            edtPhone.setText(null);
                        } else {
                            Snackbar.make(fab, "Try Again", Snackbar.LENGTH_LONG).show();
                        }
                        progressDialog.dismiss();
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                progressDialog.dismiss();
                Snackbar.make(fab, "Error while Posting Data", Snackbar.LENGTH_LONG).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();
                params.put(Constants.nameField, name);
                params.put(Constants.phoneField, phone);
                return params;
            }
        };
        request.setRetryPolicy(new DefaultRetryPolicy(
                50000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(request);
    }
you can view your responses in Google form's Response section or in Google sheets. To get response in Google sheet, just click excel symbol in response section of your Google form.

This concept is read from the following link http://codesmith.in/post-data-google-drive-sheet-through-mobile-app/ and this is one of my favourite post I read.
Download Source Code

Download From Github