It is a light weight library to download YouTube video as mp3 files Created By How to Download Gradle: compile 'com.ajts.an...

Youtube Video link to mp3 file Youtube Video link to mp3 file

A blog about android developement

It is a light weight library to download YouTube video as mp3 files

Created By

API

How to Download

Gradle:
compile 'com.ajts.androidmads.youtubemp3:youtubemp3:1.0.0'
Maven:
<dependency>
  <groupId>com.ajts.androidmads.youtubemp3</groupId>
  <artifactId>youtubemp3</artifactId>
  <version>1.0.0</version>
  <type>pom</type>
</dependency>

How to use this Library:

This Library is used to download mp3 file from youtube video link.
new YTubeMp3Service.Builder(MainActivity.this)
    .setDownloadUrl("https://youtu.be/nZDGC-tXCo0")
    .setFolderPath(new File(Environment.getExternalStorageDirectory(), "/YTMp3/Downloads").getPath())
    .setOnDownloadListener(new YTubeMp3Service.Builder.DownloadListener() {
        @Override
        public void onSuccess(String savedPath) {
            Log.v("exce", savedPath);
            progressDialog.dismiss();
        }

        @Override
        public void onDownloadStarted() {
        }

        @Override
        public void onError(Exception e) {
            Log.v("exce", e.getMessage());
            progressDialog.dismiss();
        }
    }).build();

Download From Github

A light weight library for exporting and importing sqlite database in android Created By How to Download Gradle: compile 'com...

SQLite Importer Exporter - Library SQLite Importer Exporter - Library

A blog about android developement


A light weight library for exporting and importing sqlite database in android

Created By

API

How to Download

Gradle:
compile 'com.ajts.androidmads.sqliteimpex:library:1.0.0'
Maven:
<dependency>
  <groupId>com.ajts.androidmads.sqliteimpex</groupId>
  <artifactId>library</artifactId>
  <version>1.0.0</version>
  <type>pom</type>
</dependency>

How to use this Library:

This Library is used to import SQLite Database from Assets or External path and Export/Backup SQLite Database to external path.
SQLiteImporterExporter sqLiteImporterExporter = new SQLiteImporterExporter(getApplicationContext(), db);

// Listeners for Import and Export DB
sqLiteImporterExporter.setOnImportListener(new SQLiteImporterExporter.ImportListener() {
    @Override
    public void onSuccess(String message) {
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onFailure(Exception exception) {
        Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_SHORT).show();
    }
});

sqLiteImporterExporter.setOnExportListener(new SQLiteImporterExporter.ExportListener() {
    @Override
    public void onSuccess(String message) {
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onFailure(Exception exception) {
        Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_SHORT).show();
    }
});

To Import SQLite from Assets

try {
    sqLiteImporterExporter.importDataBaseFromAssets();
} catch (Exception e) {
    e.printStackTrace();
}

To import from external storage

try {
    sqLiteImporterExporter.importDataBase(path);
} catch (Exception e) {
    e.printStackTrace();
}

To export to external storage

try {
    sqLiteImporterExporter.exportDataBase(path);
} catch (Exception e) {
    e.printStackTrace();
}

Download From Github

In Google I/O 2017, Google announced about Room Architecture for Android. This Architecture is used to maintain the State of Android Ap...

Room Android Architecture  Room Android Architecture

A blog about android developement

Android Mads

In Google I/O 2017, Google announced about Room Architecture for Android. This Architecture is used to maintain the State of Android Application when the orientation changes. As well as google announced about Room Architecture.

Room

We have more boiler plates while creating SQLite Database in Android even it is small. Room as a library used to remove the boiler plates like Cursors & Handlers and database can be handled with annotations and model classes. If we remember about Sugar ORM or Active Android, the same approach is dealt with Room. 
We don't want to go for any third party libraries, when the official Android libraries give you an equal, or better solution.

Life Cycle Activity

We have faced the problem mostly as that to maintain the State of Android Application when the orientation changes. The Life Cycle Activity used to handle the state easily.

Coding Part

Create a new project in Android Studio.

First, Add Google’s maven repository to your project-level build.gradle file.
allprojects {
    repositories {
        jcenter()
        maven { url 'https://maven.google.com' }
    }
}
Then, Add following dependencies to your app-level build.gradle file.
compile 'android.arch.persistence.room:runtime:1.0.0-alpha1'
annotationProcessor 'android.arch.persistence.room:compiler:1.0.0-alpha1'
compile 'android.arch.lifecycle:extensions:1.0.0-alpha1'

Creating the Model

Create a Model class and named as ProductModel.
@Entity
public class ProductModel {

    @PrimaryKey(autoGenerate = true)
    public int itemId;
    private String itemName;
    private String itemQty;
    @TypeConverters(DateConverter.class)
    private Date itemAddedDate;

    public ProductModel(int itemId, String itemName, String itemQty, Date itemAddedDate) {
        this.itemId = itemId;
        this.itemName = itemName;
        this.itemQty = itemQty;
        this.itemAddedDate = itemAddedDate;
    }

    public void setItemName(String itemName) {
        this.itemName = itemName;
    }

    public void setItemQty(String itemQty) {
        this.itemQty = itemQty;
    }

    public void setItemAddedDate(Date itemAddedDate) {
        this.itemAddedDate = itemAddedDate;
    }

    public String getItemName() {
        return itemName;
    }

    public String getItemQty() {
        return itemQty;
    }

    public Date getItemAddedDate() {
        return itemAddedDate;
    }

    public int getItemId() {
        return itemId;
    }
}
Here,
  1. @Entity annotation is used to tell the Model Class as Database Table. 
  2. @PrimaryKey annotation is used to set Primary Key for Table and autoGenerate = true is used to set Auto Increment to Primary Key. 
  3. @TypeConverters annotation is used to convert the Date into String and Vice-Versa. The DateConverter is class created by your own as like below.

Creating Type Converter

Create a class and named as DateConverter and Paste the following code.
class DateConverter {

    @TypeConverter
    public static Date toDate(Long timestamp) {
        return timestamp == null ? null : new Date(timestamp);
    }

    @TypeConverter
    public static Long toTimestamp(Date date) {
        return date == null ? null : date.getTime();
    }
}
This Converter is used to convert date to string and vice versa. Because, We cannot save Date format in SQLite Directly.

Creating Data Access Object(DAO)

Create a class and named as ProductModelDao.class and paste the following code.
Here, the Query for storing and retrieving data from Local DB performed.
@Dao
@TypeConverters(DateConverter.class)
public interface ProductModelDao {
    
    @Query("select * from ProductModel")
    LiveData<List<ProductModel>> getAllProducts();

    @Query("select * from ProductModel where itemId = :itemId")
    ProductModel getProductById(int itemId);

    @Insert(onConflict = REPLACE)
    void addProduct(ProductModel ProductModel);

    @Update(onConflict = REPLACE)
    void updateProduct(ProductModel ProductModel);

    @Delete
    void deleteProduct(ProductModel ProductModel);
    
}
  1. @Dao annotation indicate this interface as DAO. 
  2. @Query annotation indicate the data surrounded is Queries to retrieve data from DB. 
  3. @Insert, @Update, @Delete,annotations used to insert, update and delete the data stored in DB respectively. 
  4. onConflict indicates that to replace the data when conflicts occurs while performing the tasks..

Creating Database

Create a abstract class and named as AppDataBase.class and pass the following code.
@Database(entities = {ProductModel.class}, version = 1)
public abstract class AppDataBase extends RoomDatabase {
    private static AppDataBase INSTANCE;

    public static AppDataBase getDatabase(Context context) {
        if (INSTANCE == null) {
            INSTANCE = Room.databaseBuilder(context.getApplicationContext(), AppDataBase.class, "product_db")
                    .build();
        }
        return INSTANCE;
    }

    public static void destroyInstance() {
        INSTANCE = null;
    }

    public abstract ProductModelDao itemAndPersonModel();
}
  1. @Database annotation indicate this class as Database of our Application. 
  2. entities is an array of tables or entities and separated by comma. 
  3. version is used to denote the version of the database.
This class is used to create the database and get an instance of it. We can create the database using
Room.databaseBuilder(context.getApplicationContext(), AppDataBase.class, "product_db")
.build();
Create Android View Model for Retrieving all the data from DB.
public class ProductListViewModel extends AndroidViewModel {

    private final LiveData<List<ProductModel>> itemAndPersonList;
    private AppDataBase appDatabase;

    public ProductListViewModel(Application application) {
        super(application);
        appDatabase = AppDataBase.getDatabase(this.getApplication());
        itemAndPersonList = appDatabase.itemAndPersonModel().getAllProducts();
    }

    public LiveData<List<ProductModel>> getItemAndPersonList() {
        return itemAndPersonList;
    }

    public void deleteItem(ProductModel borrowModel) {
        new deleteAsyncTask(appDatabase).execute(borrowModel);
    }

    private static class deleteAsyncTask extends AsyncTask<ProductModel, Void, Void> {

        private AppDataBase db;
        deleteAsyncTask(AppDataBase appDatabase) {
            db = appDatabase;
        }
        @Override
        protected Void doInBackground(final ProductModel... params) {
            db.itemAndPersonModel().deleteProduct(params[0]);
            return null;
        }

    }

}
Create Android View Model for Retrieve a single data from DB as well as the code update the Data.
public class AddProductViewModel extends AndroidViewModel {

    private AppDataBase appDatabase;

    public AddProductViewModel(Application application) {
        super(application);
        appDatabase = AppDataBase.getDatabase(this.getApplication());
    }

    public void addProduct(final ProductModel borrowModel) {
        new addAsyncTask(appDatabase).execute(borrowModel);
    }

    private static class addAsyncTask extends AsyncTask {

        private AppDataBase db;

        addAsyncTask(AppDataBase appDatabase) {
            db = appDatabase;
        }

        @Override
        protected Void doInBackground(final ProductModel... params) {
            db.itemAndPersonModel().addProduct(params[0]);
            return null;
        }

    }
}
Create Android View Model for Retrieve a insert the Data.
public class UpdateProductViewModel extends AndroidViewModel {

    private AppDataBase appDatabase;

    public UpdateProductViewModel(Application application) {
        super(application);
        appDatabase = AppDataBase.getDatabase(this.getApplication());
    }

    public ProductModel readProduct(final int itemId) {
        try {
            return new readAsyncTask(appDatabase).execute(itemId).get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void updateProduct(final ProductModel borrowModel) {
        new UpdateProductViewModel.updateAsyncTask(appDatabase).execute(borrowModel);
    }

    private static class updateAsyncTask extends AsyncTask<ProductModel, Void, Void> {

        private AppDataBase db;

        updateAsyncTask(AppDataBase appDatabase) {
            db = appDatabase;
        }

        @Override
        protected Void doInBackground(final ProductModel... params) {
            db.itemAndPersonModel().updateProduct(params[0]);
            return null;
        }

    }

    private static class readAsyncTask extends AsyncTask<Integer, Void, ProductModel> {

        private AppDataBase db;

        readAsyncTask(AppDataBase appDatabase) {
            db = appDatabase;
        }

        @Override
        protected ProductModel doInBackground(final Integer... params) {
            return db.itemAndPersonModel().getProductById(params[0]);
        }
    }
}

Creating Custom Adapter

Create Adapter for Recyclerview and Paste the Following code.
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewHolder> {

    private List<ProductModel> ProductModelList;
    private View.OnLongClickListener longClickListener;
    private View.OnClickListener clickListener;

    public RecyclerViewAdapter(List<ProductModel> ProductModelList,
                               View.OnLongClickListener longClickListener,
                               View.OnClickListener clickListener) {
        this.ProductModelList = ProductModelList;
        this.longClickListener = longClickListener;
        this.clickListener = clickListener;
    }

    @Override
    public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new RecyclerViewHolder(LayoutInflater.from(parent.getContext())
                .inflate(R.layout.recycler_item, parent, false));
    }

    @Override
    public void onBindViewHolder(final RecyclerViewHolder holder, int position) {
        ProductModel productModel = ProductModelList.get(position);
        holder.itemTextView.setText(productModel.getItemName());
        holder.nameTextView.setText(productModel.getItemQty());
        holder.dateTextView.setText(productModel.getItemAddedDate().toLocaleString().substring(0, 11));
        holder.itemView.setTag(productModel);
        holder.itemView.setOnLongClickListener(longClickListener);
        holder.itemView.setOnClickListener(clickListener);
    }

    @Override
    public int getItemCount() {
        return ProductModelList.size();
    }

    public void addItems(List<ProductModel> ProductModelList) {
        this.ProductModelList = ProductModelList;
        notifyDataSetChanged();
    }

    static class RecyclerViewHolder extends RecyclerView.ViewHolder {
        private TextView itemTextView;
        private TextView nameTextView;
        private TextView dateTextView;

        RecyclerViewHolder(View view) {
            super(view);
            itemTextView = view.findViewById(R.id.itemTextView);
            nameTextView = view.findViewById(R.id.nameTextView);
            dateTextView = view.findViewById(R.id.dateTextView);
        }
    }
}
To use the View models inside our Application, use LifeCycleActivity instead of extending the Activity. and Access the view models by
public class MainActivity extends AppCompatLifeCycleActivity implements View.OnLongClickListener, View.OnClickListener {

    private ProductListViewModel viewModel;
    private RecyclerViewAdapter recyclerViewAdapter;
    private RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MainActivity.this, AddActivity.class));
            }
        });
        recyclerView = findViewById(R.id.recyclerView);
        recyclerViewAdapter = new RecyclerViewAdapter(new ArrayList<ProductModel>(), this, this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        recyclerView.setAdapter(recyclerViewAdapter);

        viewModel = ViewModelProviders.of(this).get(ProductListViewModel.class);

        viewModel.getItemAndPersonList().observe(MainActivity.this, new Observer<List<ProductModel>>() {
            @Override
            public void onChanged(@Nullable List<ProductModel> itemAndPeople) {
                recyclerViewAdapter.addItems(itemAndPeople);
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppDataBase.destroyInstance();
    }

    @Override
    public boolean onLongClick(View v) {
        ProductModel productModel = (ProductModel) v.getTag();
        viewModel.deleteItem(productModel);
        return true;
    }

    @Override
    public void onClick(View v) {
        ProductModel productModel = (ProductModel) v.getTag();
        Intent i = new Intent(MainActivity.this, UpdateActivity.class);
        i.putExtra("itemId",productModel.itemId);
        startActivity(i);
    }
}
Here, AppCompatLifeCycleActivity is custom Activity inherited with AppCompatActivity and LifeCycleActivity's feature. Create a class and Named as AppCompatLifeCycleActivity.class and paste the following code.
public class AppCompatLifeCycleActivity extends AppCompatActivity 
                   implements LifecycleRegistryOwner {

    private final LifecycleRegistry mRegistry = new LifecycleRegistry(this);

    @Override
    public LifecycleRegistry getLifecycle() {
        return mRegistry;
    }
}
I did this, because of we cannot use setSupportActionbaras like in AppCompatActivity with NoActionBar Theme. You Can simply use LifeCycleActivitywith WithActionBar Themes.
I have added the Add Product and Update Product Activity Screens in the Samples. You Download in the Download Section. If you have any doubt regarding this, feel free to comment in the comment section.

Download Code

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

Download From Github

In this tutorial, we will learn how to build ListView and RecyclerView with Custom Adapter in Kotlin. Everybody knows what is Listvi...

RecyclerView & ListView in Kotlin RecyclerView & ListView in Kotlin

A blog about android developement



In this tutorial, we will learn how to build ListView and RecyclerView with Custom Adapter in Kotlin. Everybody knows what is Listview and Recyclerview. So, without any introduction about them we will jump into the coding part of the Tutorial.

Coding Part

Kotlin ListView Example

We should follow the same steps to create Activity with associated layout file for example MainActivity.kt with activity_main.xml

Create ListView Adapter

Create new class and named as MoviesListViewAdapter and paste the following.
class MoviesListViewAdapter(private val activity: Activity, moviesList: List) : BaseAdapter() {

    private var moviesList = ArrayList()

    init {
        this.moviesList = moviesList as ArrayList
    }

    override fun getCount(): Int {
        return moviesList.size
    }

    override fun getItem(i: Int): Any {
        return i
    }

    override fun getItemId(i: Int): Long {
        return i.toLong()
    }

    @SuppressLint("InflateParams", "ViewHolder")
    override fun getView(i: Int, convertView: View?, viewGroup: ViewGroup): View {
        var vi: View = convertView as View
        val inflater = activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        vi = inflater.inflate(R.layout.movie_list_row, null)
        val title = vi.findViewById(R.id.title)
        val genre = vi.findViewById(R.id.genre)
        val year = vi.findViewById(R.id.year)
        title.text = moviesList[i].title
        genre.text = moviesList[i].genre
        year.text = moviesList[i].year
        return vi
    }
}
Then Assign the adapter to ListView like below
listView = findViewById(R.id.listView) as ListView
adapter = MoviesListViewAdapter(this, movieList)
(listView as ListView).adapter = adapter

Kotlin RecyclerView Example

Create RecyclerView Adapter

Create new class and named as MoviesRecyclerAdapter and paste the following.
class MoviesRecyclerAdapter(private val moviesList: List) : RecyclerView.Adapter() {

    inner class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        var title: TextView = view.findViewById(R.id.title)
        var year: TextView = view.findViewById(R.id.year)
        var genre: TextView = view.findViewById(R.id.genre)

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val itemView = LayoutInflater.from(parent.context)
                .inflate(R.layout.movie_list_row, parent, false)

        return MyViewHolder(itemView)
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        val Movies = moviesList[position]
        holder.title.text = Movies.title
        holder.genre.text = Movies.genre
        holder.year.text = Movies.year
    }

    override fun getItemCount(): Int {
        return moviesList.size
    }
}
Then Assign the adapter to RecyclerView like below
recyclerView = findViewById(R.id.recyclerView) as RecyclerView
mAdapter = MoviesRecyclerAdapter(movieList)
val mLayoutManager = LinearLayoutManager(applicationContext)
recyclerView!!.layoutManager = mLayoutManager
recyclerView!!.itemAnimator = DefaultItemAnimator()
recyclerView!!.adapter = mAdapter
In this tutorial, I am not covered the basics of creating listview and recyclerview. You can find the full example in download section

Download Code

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

Kotlin Android Extensions is an important Kotlin plugin that is similar to Butterknife. It will allow to recover views in android. I...

Kotlin Android Extensions Kotlin Android Extensions

A blog about android developement


Kotlin Android Extensions is an important Kotlin plugin that is similar to Butterknife. It will allow to recover views in android.

Implementation

Add the following plugins in your app level build.gradle file
apply plugin:'com.android.application'
apply plugin:'kotlin-android'
apply plugin:'kotlin-android-extensions'

Coding Part

Create a new layout file in res folder, name it as activity_main.xml and paste the following codes
<?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:gravity="center"
    android:orientation="vertical"
    tools:context="com.androidmads.kotlinsample_helloworld.MainActivity">

    <TextView
        android:id="@+id/helloTxtView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

    <TextView
        android:id="@+id/helloAndroidExtension"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Hello World!" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        app:srcCompat="@mipmap/ic_launcher" />

</LinearLayout>
Create a new Kotlin file and name it as MainActivity.kt Import the following line, which is used to recover the views in android.
import kotlinx.android.synthetic.main.activity_main.*;
The following code refers that how to use Kotlin Extension. Here helloAndroidExtension is the Id of the textview and click listener for this textview is done as in below code
// Hello Program for Kotlin Android Extension 
// helloAndroidExtension is the id of the TextView
helloAndroidExtension.text = "Example for Kotlin Android Extension";
We can apply the same Approach with imageview by assigning ImageSource from Drawable folder and see the code below.
imageView.setImageResource(R.mipmap.ic_launcher_round)

Full Code

The following shows, how to use Kotlin Android extensions
package com.androidmads.kotlinsample_helloworld

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*;

class MainActivity : AppCompatActivity() {

    // Declaration
    var helloTextView: TextView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Initialization
        helloTextView = findViewById(R.id.helloTxtView) as TextView
        // Assigning data to TextView in runtime
        helloTextView!!.text = "Hello Kotlin!";

        // Click Listener in Kotlin
        helloTextView!!.setOnClickListener({
            Toast.makeText(applicationContext, "Hello TextView Clicked",
                    Toast.LENGTH_LONG).show();
        })

        // Hello Program for Kotlin Android Extension
        helloAndroidExtension.text = "Example for Kotlin Android Extension";

        imageView.setImageResource(R.mipmap.ic_launcher_round)
    }
}

Download Code:

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

Hi Friends. In this tutorial, we will learn how to implement firebase phone authentication with it's origin. Digits is an Simple...

Firebase Phone Authentication - Example Firebase Phone Authentication - Example

A blog about android developement

Hi Friends. In this tutorial, we will learn how to implement firebase phone authentication with it's origin.

Digits is an Simple User Phone Authentication Service to create easy login experience. Now Digits is acquired by Google's Firebase and it provides free service for limited amount of authentication per month. However, if you need to sign in a very high volume of users with phone authentication, you might need to upgrade your pricing plan. See the pricing page. 

You can use Firebase Authentication to sign in a user by sending an SMS message to the user's phone. The user signs in using a one-time code contained in the SMS message.

Setup Firebase

To setup firebase in your project, read previous post. After setting up, open Authentication sign in method and enable phone authentication method.


You should Add SHA Fingerprint in your application. To get SHA Fingerprint use the following Code with Command Prompt in Windows
keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

Coding Part

Add the dependency for Firebase Authentication to your app-level build.gradle file:
dependencies {
    ...
    compile 'com.google.firebase:firebase-auth:11.0.0'
}
// Add to the bottom of the file
apply plugin: 'com.google.gms.google-services'
Add the dependency for Play Services to your project-level build.gradle file:
dependencies {
    ...
    classpath 'com.google.gms:google-services:3.1.0'
}

Send a verification code to the user's phone

To initiate phone number sign-in, present the user an interface that prompts them to type their phone number. Send OTP to user by pass their phone number to the PhoneAuthProvider.verifyPhoneNumber method to request that Firebase verify the user's phone number. For example,
PhoneAuthProvider.getInstance().verifyPhoneNumber(
                phoneNumber,        // Phone number to verify
                60,                 // Timeout duration
                TimeUnit.SECONDS,   // Unit of timeout
                this,               // Activity (for callback binding)
                mCallbacks);        // OnVerificationStateChangedCallbacks
mCallbacks is used to know the verification status and the callback method is implemented as in the following
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
    @Override
    public void onVerificationCompleted(PhoneAuthCredential credential) {
        Log.d(TAG, "onVerificationCompleted:" + credential);
        signInWithPhoneAuthCredential(credential);
    }

    @Override
    public void onVerificationFailed(FirebaseException e) {
        Log.w(TAG, "onVerificationFailed", e);
        if (e instanceof FirebaseAuthInvalidCredentialsException) {
            mPhoneNumberField.setError("Invalid phone number.");
        } else if (e instanceof FirebaseTooManyRequestsException) {
            Snackbar.make(findViewById(android.R.id.content), "Quota exceeded.",
                    Snackbar.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onCodeSent(String verificationId,
                           PhoneAuthProvider.ForceResendingToken token) {
        Log.d(TAG, "onCodeSent:" + verificationId);
        mVerificationId = verificationId;
        mResendToken = token;
    }
};
onVerificationCompleted(PhoneAuthCredential)
This method is called, when the user number verified successfully.

onVerificationFailed(FirebaseException)
This method is called, when error occurred during verification.

onCodeSent(String verificationId, PhoneAuthProvider.ForceResendingToken)
This method is called when the verification code is send to user via SMS.

Create a PhoneAuthCredential object

The phone auth credits are created as in the following snippet
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
// verificationId can be found in onCodeSent function in callback functionality
// code is retrieved from SMS send by Firebase
Then we can verify and store the Phone Authentication user details by using the following method.
mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener() {
                @Override
                public void onComplete(@NonNull Task task) {
                    if (task.isSuccessful()) {
                        Log.d(TAG, "signInWithCredential:success");
                        FirebaseUser user = task.getResult().getUser();
                        startActivity(new Intent(PhoneAuthActivity.this, MainActivity.class));
                        finish();
                    } else {
                        Log.w(TAG, "signInWithCredential:failure", task.getException());
                        if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                            mVerificationField.setError("Invalid code.");
                        }
                    }
                }
            });

Sign Out

To sign out from your Application just use signout method in your Auth method.
FirebaseAuth mAuth = FirebaseAuth.getInstance();
mAuth.signOut();

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.  

Hello guys, In this tutorial we will learn how to create Circular Image View in Android without using any additional Libraries such as ...

Circle Image View using Glide and Picasso in Android Circle Image View using Glide and Picasso in Android

A blog about android developement


Hello guys, In this tutorial we will learn how to create Circular Image View in Android without using any additional Libraries such as CircleImageView.
// This Library is very Popular and Widely used for Circle Image View
compile 'de.hdodenhof:circleimageview:2.1.0'
Nowadays, Every Android Developers uses Glide or Picasso Image HTTP Libraries to Image in Image Views. If we uses any additional Libraries to get Circle Shaped Image View may lead to increase the size of an APK. To avoid this, Glide and Picasso provides solution to create Circle Image View.

First, we will see how create circle image using Picasso.

Circle Transformation using Picasso

Download Picasso by Gradle in Android
// This Library is created by Square.Inc
compile 'com.squareup.picasso:picasso:2.5.2'
The following snippet is used to load image into ImageView using Picasso
Picasso.with(getApplicationContext()).load("http://i.imgur.com/DvpvklR.png")
       .placeholder(R.mipmap.ic_launcher)
       .error(R.mipmap.ic_launcher)
       .into((ImageView) findViewById(R.id.picassoImageView));
To create circle image, create a class named as PicassoCircleTransformation and paste the following code
public class PicassoCircleTransformation implements Transformation {

    @Override
    public Bitmap transform(Bitmap source) {
        int size = Math.min(source.getWidth(), source.getHeight());

        int x = (source.getWidth() - size) / 2;
        int y = (source.getHeight() - size) / 2;

        Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size);
        if (squaredBitmap != source) {
            source.recycle();
        }

        Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig());

        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        BitmapShader shader = new BitmapShader(squaredBitmap,
                BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
        paint.setShader(shader);
        paint.setAntiAlias(true);

        float r = size / 2f;
        canvas.drawCircle(r, r, r, paint);

        squaredBitmap.recycle();
        return bitmap;
    }

    @Override
    public String key() {
        return "circle";
    }
}
Then load the transformation as like the following
Picasso.with(getApplicationContext()).load("http://i.imgur.com/DvpvklR.png")
      .placeholder(R.mipmap.ic_launcher)
      .error(R.mipmap.ic_launcher)
      .transform(new PicassoCircleTransformation())
      .into((ImageView) findViewById(R.id.picassoImageView));
Now we will see, how to create circle transformation using Glide

Circle Transformation using Glide

Download Glide by Gradle in Android
// This Library is created by Bumptech
compile 'com.github.bumptech.glide:glide:3.7.0'
The following snippet is used to load image into ImageView using Glide
Glide.with(getApplicationContext()).load("http://i.imgur.com/DvpvklR.png")
        .thumbnail(0.5f)
        .crossFade()
        .placeholder(R.mipmap.ic_launcher)
        .error(R.mipmap.ic_launcher)
        .diskCacheStrategy(DiskCacheStrategy.ALL)
        .into((ImageView) findViewById(R.id.glideImageView));
To create circle image, create a class named as GlideCircleTransformation and paste the following code
public class GlideCircleTransformation implements Transformation {

  private BitmapPool mBitmapPool;

  public GlideCircleTransformation(Context context) {
    this(Glide.get(context).getBitmapPool());
  }

  public GlideCircleTransformation(BitmapPool pool) {
    this.mBitmapPool = pool;
  }

  @Override
  public Resource transform(Resource resource, int outWidth, int outHeight) {
    Bitmap source = resource.get();
    int size = Math.min(source.getWidth(), source.getHeight());

    int width = (source.getWidth() - size) / 2;
    int height = (source.getHeight() - size) / 2;

    Bitmap bitmap = mBitmapPool.get(size, size, Bitmap.Config.ARGB_8888);
    if (bitmap == null) {
      bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
    }

    Canvas canvas = new Canvas(bitmap);
    Paint paint = new Paint();
    BitmapShader shader =
            new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
    if (width != 0 || height != 0) {
      // source isn't square, move viewport to center
      Matrix matrix = new Matrix();
      matrix.setTranslate(-width, -height);
      shader.setLocalMatrix(matrix);
    }
    paint.setShader(shader);
    paint.setAntiAlias(true);

    float r = size / 2f;
    canvas.drawCircle(r, r, r, paint);

    return BitmapResource.obtain(bitmap, mBitmapPool);
  }

  @Override public String getId() {
    return "GlideCircleTransformation()";
  }
}
Then load the transformation in Glide as like the following
Glide.with(getApplicationContext()).load("http://i.imgur.com/DvpvklR.png")
        .thumbnail(0.5f)
        .crossFade()
        .placeholder(R.mipmap.ic_launcher)
        .error(R.mipmap.ic_launcher)
        .bitmapTransform(new GlideCircleTransformation(getApplicationContext()))
        .diskCacheStrategy(DiskCacheStrategy.ALL)
        .into((ImageView) findViewById(R.id.glideImageView));

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

I found these snippets from Wasabeef Transformations Libraries for Glide and Picasso.
Post your doubts and comments in the comments section.  

Hello Guys, we already knew that Google announced Kotlin is a new first class language for Android Development. So, we started t...

Kotlin - Basics Kotlin - Basics

A blog about android developement


Hello Guys, we already knew that Google announced Kotlin is a new first class language for Android Development. So, we started the Kotlin series for learning Kotlin for android. We have seen the "Hello World" Program for Android in our previous post. 

You can download Intellij idea Commuinty Edition or use Kotlin Online Compiler provided by Intellij

In this post, we will learn the basics of kotlin.

1. Hello World

The Following Snippet shows the Hello world Program and is similar to Java.
fun main(args: Array <string>) {
    println("Hello, world!")
}

2. Variables and Constants

The Following Snippet shows the How to use Variables and Constants with Datatype in Kotlin.
  1. Variables can be re-assigned 
  2. // Variable - Values Can be reassigned
    var a = 10
    a = a + 10
    println(a)
  3. Constants cannot be re-assigned and if we did will error as "val cannot be reassigned"
  4. // Constants - Values cannot reassigned
    val x = 10
    println(x)
  5. We can specify the Data types for Variables and Constants
  6. // Concate String Values
    println(str+"Mad")
    println("${str}Mad - Kotlin Series")
The following snippet shows how to use variables and constants.
fun main(args: Array<string>) {
    // Variable - Values Can be reassigned
    var a = 10
    a = a + 10
    println(a)
    // Constants - Values cannot reassigned
    val x = 10
    println(x)
    // Variables - with Datatype
    var str : String = "Android"
    println(str)
    // Concate String Values
    println(str+"Mad")
    println("${str}Mad - Kotlin Series")
}

3. If Else

The Following Snippet shows the If Else Statement in Kotlin.
fun main(args: Array<string>) {
    var arun = 10
    var dharun = 15
    var elder = if(arun > dharun)"Arun" else "Dharun"
 
    println("Elder is ${elder}")
}

4. When

Switch statement is not present in Kotlin and is replaced by When.
fun main(args: Array<string>) {
    var elder = "Dharun"
    when(elder){
        "Arun"->{
            println("Elder is Arun")
        }
        "Dharun"->{
            println("Elder is Dharun")
        }
        else->{
            println("No Answer")
        }
    }
}

5. Loops

The Following snippet shows Loops in Kotlin.
// For Loop
fun main(args: Array<string>) {
    for(i in 1..10){
        println(i)
    }
}
// While Loop
fun main(args: Array<string>) {
    var x = 1;
    while(x<=10){
        println(x)
        x++
    }
}

6. Arrays and Lists

The Following snippet shows Arrays in Kotlin.
fun main(args: Array<String>) {
    var x = arrayOf(1,2,3,4);
    for(i in x){
        println(i)
    }
}
We can apply any type in like float, string ...
fun main(args: Array) {
    var x = arrayOf(1,2,3,4,"Androidmads");
    for(i in x){
        println(i)
    }
}
It Can be controlled by apply Data types as in the following Snippet
fun main(args: Array<String>) {
    var x = arrayOf<String>("Android","Mads","Kotlin","Series");
    for(i in x){
        println(i)
    }
}
Lists are similar to arrays
fun main(args: Array<String>) {
    var x = listOf<String>("Android","Mads","Kotlin","Series");
    for(i in x){
        println(i)
    }
}

7. Classes

The Following snippet shows how to declare / create objects for class in Kotlin. Create a class named it as "Model.kt"
class Model {
    var name : String = ""
}
fun main(args: Array<String>) {
    // In Java Object Created by ClassObject obj = new ClassObject();
    var model = Model()
    model.name = "Androidmads" 
}

8. Constructors

The Following snippet shows how to use constructor in Kotlin.
class Model(val name:String, val age:Int)
We can also the following method
class Model{
   constructor(name:String, age:Int) {

   }
}
fun main(args: Array<String>) {
    // In Java Object Created by ClassObject obj = new ClassObject();
    var model = Model("Androidmads",20)
    println("${model.name}")
}

9. Null Handling

In Java, Null value may leads to Null Pointer Exception. But, In Kotlin,Null Handling to variables is done as in the following snippet
fun main(args: Array<String>) {
    var name:String? = null
    // Just prints Null and does not throw NullPointerException  
    println("${name}")
}
Hope you Like this. Post Comments about this article in Comment Section 

Google officially announced Kotlin as a first class language for Android development at Google I/O 2017. From Android Studio 3.0, Kotl...

Hello World - Kotlin Hello World - Kotlin

A blog about android developement

Google officially announced Kotlin as a first class language for Android development at Google I/O 2017. From Android Studio 3.0, Kotlin is included as Support for Android Studio. In this post, we will start the development of Android Application with Kotlin.

To Getting Started, you have to download Android Studio 3.0 Canary 1 or Add the Kotlin plugin in your existing Android Studio.

Create Android Project with Kotlin

Create new project in Android studio check the Kotlin support and start as usual with Android Studio 3.0. 
Android Studio 3.0
But for Android Studio with version less than 3.0, we have install plugin form Plugins menu manually by Selecting File-->Settings-->Plugins-->Browse Repositories--> Search and Select Kotlin. Then Click Install

Now inside activity_main.xml create the following UI
<?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.androidmads.kotlinsample_helloworld.MainActivity">

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

</android.support.constraint.ConstraintLayout>
In Android Studio 3.0, by default you have Kotin Activity. For Android Studio with Version less than 3.0, can convert their Java activity into Kotlin Activity.
Install Kotlin Plugin
  1. Select Tools --> Kotlin --> Configure Kotlin --> Click Sync Now. 
  2. Open Quick Search or Click Ctrl + Shift + A for Windows Users. 
  3. Search and Select convert java to kotlin or simply Selct Ctrl + Shift + Alt + K for Windows Users. 
Now your MainActivity.kt looks like in the following.
package com.androidmads.kotlinsample_helloworld

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import android.widget.Toast

class MainActivity : AppCompatActivity() {

    // Declaration
    var helloTextView: TextView? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Initialization
        helloTextView = findViewById(R.id.helloTxtView) as TextView
        // Assigning data to TextView in runtime
        helloTextView!!.text = "Hello Kotlin!";

        // Click Listener in Kotlin
        helloTextView!!.setOnClickListener({
            Toast.makeText(applicationContext, "Hello TextView Clicked", Toast.LENGTH_LONG).show();
        })
    }
}
Kotlin is a new Programming Language for Android Development. I hope Java is not deprecated for Android Development. Please tell what do you think about this tutorial as well as the future of Java in Android development in Comment Section.

Introduction In this article, we will learn about one of the greatest APIs for Android provided by Google, called Place Picker API. Th...

Android Place Picker API Android Place Picker API

A blog about android developement


Introduction

In this article, we will learn about one of the greatest APIs for Android provided by Google, called Place Picker API. This API is used to Pick a Place from Google Maps Application without any Map Integration.
The Place Picker provides a UI dialog that displays an interactive map and a list of nearby places, including places corresponding to geographical addresses and local businesses. Users can choose a place, and your app can then retrieve the details of the selected place.

Place Picker API

The Place Picker provides a UI dialog that displays an interactive map and a list of nearby places, including places corresponding to geographical addresses and local businesses. Users can choose a place, and your app can then retrieve the details of the selected place. To know more, click here.

Steps

I have divided this Implementation into 4 steps as shown in the following.
  • Step 1: Creating New Project with Android Studio
  • Step 2: Enabling the API in Google Console.
  • Step 3: Setting up the library and AndroidManifest for the project.
  • Step 4: Implementation of the Place Picker API.

Step 1 - Creating New Project with Android Studio

  1. Open Android Studio and Select "Create new project".
  2. Name the project as per your wish and select your activity template.
  3. Click “finish” button to create the new project in Android Studio.

Step 2 - Enabling the API in Google Developer Console

  1. For using Google Places API, We need to know SHA1 Key, which is used in Google Developer Console. You can get your SHA1 Key using Command Prompt.
    keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android
  2. Open Google Developer Console.
  3. Create New Project or you can use your Existing Project.
  4. Go to Dashboard and click Enable API.
  5. Click Google Places API for Android and Select Enable.
  6. Create new API Key, which is used later.

Step 3 - Setting up the library and AndroidManifest for the project

  1. Add Google Play service library dependency in your app level build.gradle file. Here, I used the following dependency. You can change as per your Android SDK.
    compile 'com.google.android.gms:play-services:9.2.0'
  2. Then click “Sync Now” to add the library.
  3. Now open your Manifest File (AndroidManifest.xml) and the following permission.
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />  
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />  
    <uses-permission android:name="android.permission.INTERNET" />
  4. Add the following meta data to apply the API KEY.
    <meta-data  
        android:name="com.google.android.geo.API_KEY"  
        android:value="Your_API_Key"/>

Step 4 - Implementation of Place Picker API

  1. Add the following to initialize the API.
    //Declaration of Google API Client  
    private GoogleApiClient mGoogleApiClient;  
    private int PLACE_PICKER_REQUEST = 1;  
    In the onCreate method of the Activity initialize the GoogleApiClient.
    mGoogleApiClient = new GoogleApiClient  
                    .Builder(this)  
                    .addApi(Places.GEO_DATA_API)  
                    .addApi(Places.PLACE_DETECTION_API)  
                    .enableAutoManage(this, this)  
                    .build();
  2. Implement the onStart and onStop method and do the client connection task.
    @Override  
    protected void onStart() {  
        super.onStart();  
        mGoogleApiClient.connect();  
    }  
      
    @Override  
    protected void onStop() {  
        mGoogleApiClient.disconnect();  
        super.onStop();  
    } 
  3. Start Place Picker Intent using the following snippet.
    PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();  
    try {  
        startActivityForResult(builder.build(MainActivity.this), PLACE_PICKER_REQUEST);  
    } catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException e) {  
        e.printStackTrace();  
    }
  4. After this, you will get Google Maps Screen like below. It has an interactive map and a list of nearby places, including places corresponding to geographical addresses and local businesses. Users can choose a place, and your app can then retrieve the details of the selected place. The Details can be retrieved in onActivityResult method of your Activity.
    @Override  
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        if (requestCode == PLACE_PICKER_REQUEST) {  
            if (resultCode == RESULT_OK) {  
                Place place = PlacePicker.getPlace(data, this);  
                StringBuilder stBuilder = new StringBuilder();  
                String placename = String.format("%s", place.getName());  
                String latitude = String.valueOf(place.getLatLng().latitude);  
                String longitude = String.valueOf(place.getLatLng().longitude);  
                String address = String.format("%s", place.getAddress());  
                stBuilder.append("Name: ");  
                stBuilder.append(placename);  
                stBuilder.append("\n");  
                stBuilder.append("Latitude: ");  
                stBuilder.append(latitude);  
                stBuilder.append("\n");  
                stBuilder.append("Logitude: ");  
                stBuilder.append(longitude);  
                stBuilder.append("\n");  
                stBuilder.append("Address: ");  
                stBuilder.append(address);  
                tvPlaceDetails.setText(stBuilder.toString());  
            }  
        }
    }

Demo:

Figure 1:
Place Picker Intent Builder Output
Figure 2:
Place Picker Dialog (after selecting the place)
Figure 3:
Output of the Intent Builder from onActivityResult.

Full code of MainActivity.java

public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {  
  
    private GoogleApiClient mGoogleApiClient;  
    private int PLACE_PICKER_REQUEST = 1;  
    private TextView tvPlaceDetails;  
    private FloatingActionButton fabPickPlace;  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
  
        initViews();  
  
        mGoogleApiClient = new GoogleApiClient  
                .Builder(this)  
                .addApi(Places.GEO_DATA_API)  
                .addApi(Places.PLACE_DETECTION_API)  
                .enableAutoManage(this, this)  
                .build();  
  
  
        fabPickPlace.setOnClickListener(new View.OnClickListener() {  
            @Override  
            public void onClick(View view) {  
                PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();  
                try {  
                    startActivityForResult(builder.build(MainActivity.this), PLACE_PICKER_REQUEST);  
                } catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException e) {  
                    e.printStackTrace();  
                }  
            }  
        });  
    }  
  
    private void initViews() {  
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);  
        setSupportActionBar(toolbar);  
        fabPickPlace = (FloatingActionButton) findViewById(R.id.fab);  
        tvPlaceDetails = (TextView) findViewById(R.id.placeDetails);  
    }  
  
    @Override  
    protected void onStart() {  
        super.onStart();  
        mGoogleApiClient.connect();  
    }  
  
    @Override  
    protected void onStop() {  
        mGoogleApiClient.disconnect();  
        super.onStop();  
    }  
  
    @Override  
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {  
        Snackbar.make(fabPickPlace, connectionResult.getErrorMessage() + "", Snackbar.LENGTH_LONG).show();  
    }  
  
    @Override  
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        if (requestCode == PLACE_PICKER_REQUEST) {  
            if (resultCode == RESULT_OK) {  
                Place place = PlacePicker.getPlace(data, this);  
                StringBuilder stBuilder = new StringBuilder();  
                String placename = String.format("%s", place.getName());  
                String latitude = String.valueOf(place.getLatLng().latitude);  
                String longitude = String.valueOf(place.getLatLng().longitude);  
                String address = String.format("%s", place.getAddress());  
                stBuilder.append("Name: ");  
                stBuilder.append(placename);  
                stBuilder.append("\n");  
                stBuilder.append("Latitude: ");  
                stBuilder.append(latitude);  
                stBuilder.append("\n");  
                stBuilder.append("Logitude: ");  
                stBuilder.append(longitude);  
                stBuilder.append("\n");  
                stBuilder.append("Address: ");  
                stBuilder.append(address);  
                tvPlaceDetails.setText(stBuilder.toString());  
            }  
        }  
    }  
}  

Download Code:

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

Post your doubts and comments in the comments section.