Introduction: After the announcement of Google on Google I/O 2017, we have seen the series of tutorials in Kotlin. If you are new to...

Kotlin HTTP Example (Using Fuel Http) Kotlin HTTP Example (Using Fuel Http)

A blog about android developement

kotlin

Introduction:

After the announcement of Google on Google I/O 2017, we have seen the series of tutorials in Kotlin. If you are new to Kotlin you can learn Kotlin from our previous articles. We had been crossed Basics of Kotlin and Hello World function, How to use ListView, RecyclerView in Kotlin and How to implement SQLite storage in Kotlin with CRUD operations.

In this article, we will learn how to make server call (i.e. HTTP Connection) from Kotlin powered application to web services.

Coding Part:
I have divided the coding part into 3 steps as shown in the following.
  1. Creating new project.
  2. Setting up the project with Fuel HTTP.
  3. Implementing the Fuel HTTP Service Call.
Let’s start coding for Fuel HTTP.
Step 1: Creating new project:
  1. Open Android Studio and Select Create new project.
  2. Name the project as your wish and tick the Kotlin checkbox support.
  3. Then Select your Activity type (For Example: Navigation Drawer Activity, Empty Activity, etc.).
  4. Then Click “finish” button to create new project in Android Studio
Step 2: Setting up the project:
Now, we will setting up the project for Fuel HTTP.
1.      Open your app level build.gradle file and add the following line.
implementation 'com.github.kittinunf.fuel:fuel-android:1.6.0'
2.      If you are using Android Studio Version below 3.0, the add the following (Optional Step)
compile 'com.github.kittinunf.fuel:fuel-android:1.6.0'
3.       Then Click “Sync Now” to download the library and add to the project.
After this, you are ready to implement HTTP Service Call from your Application.
Step 3: Fuel HTTP implementation:
Now, we will setting up the project for Fuel HTTP.
1.      Open your AndroidManifest.xml and Add permission to access internet.
<uses-permission android:name="android.permission.INTERNET"/>
2.   Open your activity_main.xml file and create the User Interface as you wanted or Paste the following code.
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.androidmads.kotlinfuelhttpsample.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="vertical">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:text="GET Request's Response"
            android:textColor="#000000" />

        <TextView
            android:id="@+id/tvGetResponse"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:background="#e1e1e1"
            android:padding="10dp"
            android:text="" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:background="@color/colorPrimary"
            android:onClick="httpGetJson"
            android:text="GET RESPONSE"
            android:textColor="#ffffff" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:text="POST Request's Response"
            android:textColor="#000000" />

        <TextView
            android:id="@+id/tvPostResponse"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:background="#e1e1e1"
            android:padding="10dp"
            android:text="" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:background="@color/colorPrimary"
            android:onClick="httpPostJson"
            android:text="POST RESPONSE"
            android:textColor="#ffffff" />

    </LinearLayout>
</ScrollView>
Layout Preview
1.       Then Open your Activity file and here I am opening MainActivity.java file.
2.      Initialize the fuel library by the following code
FuelManager.instance.basePath = "http://demosmushtaq.16mb.com";
Here, you must specify the base address of your service. It will start or initialize the library.
GET REQUEST
We will use “Fuel.get()” to make server call with Get method. The following code shows how to implement this.
Fuel.get("<Service Link without base path>")
.responseJson { request, response, result ->
 Log.v(“response”, result.get().content)
}
POST REQUEST
We will use “Fuel.post()” to make server call with Post method. The following code shows how to implement this.
Fuel.post("<Service Link without base path>", listOf("<key>" to "<value>"))
.responseJson { request, response, result ->
 Log.v(“response”, result.get().content)
}
You can get the response as string or json by specify the response type “responseString” or “responseJson” respectively.You can pass the data to service using “listOf” method. It is an optional value. You can also access the without the parameters to be passed
You can get response from the result using “result.get().content” as mentioned in the code above.

Full Code of MainActivity:
You can find the full code implementation of MainActivty.kt in the following.
class MainActivity : AppCompatActivity() {

    var tvGetResponse: TextView? = null
    var tvPostResponse: TextView? = null
    var progress: ProgressDialog? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initViewsAndWidgets()
        FuelManager.instance.basePath = "http://demosmushtaq.16mb.com";
    }

    private fun initViewsAndWidgets() {
        tvGetResponse = findViewById(R.id.tvGetResponse)
        tvPostResponse = findViewById(R.id.tvPostResponse)
        progress = ProgressDialog(this)
        progress!!.setTitle("Kotlin Fuel Http Sample")
        progress!!.setMessage("Loading...")
    }

    fun httpGetJson(view: View) {
        try {
            progress!!.show()
            Fuel.get("api/get_sample.php").responseJson { request, response, result ->
                tvGetResponse!!.text = result.get().content
            }
        } catch (e: Exception) {
            tvGetResponse!!.text = e.message
        } finally {
            progress!!.dismiss()
        }
    }

    fun httpPostJson(view: View) {
        try {
            progress!!.show()
            Fuel.post("api/post_sample.php", listOf("version_index" to "1")).responseJson { request, response, result ->
                tvPostResponse!!.text = result.get().content
            }
        } catch (e: Exception) {
            tvPostResponse!!.text = e.message
        } finally {
            progress!!.dismiss()
        }
    }
}

Download Code: 

You can download sample code from the following GitHub link.

In this tutorial, we will learn how to do Optical Character Recognition in Android using Vision API. Here, we will just import the Go...

Optical Character Recognition using Google Vision API on Android Optical Character Recognition using Google Vision API on Android

A blog about android developement




In this tutorial, we will learn how to do Optical Character Recognition in Android using Vision API. Here, we will just import the Google Vision API Library with Android Studio and implement the OCR for retrieving text from image.

Android Mobile Vision API:

The Mobile Vision API provides a framework for finding objects in photos and video. The framework includes detectors, which locate and describe visual objects in images or video frames, and an event driven API that tracks the position of those objects in video. The Mobile Vision API includes face, bar code, and text detectors, which can be applied separately or together. 
This is not only used to get text from image as well as for structuring the text retrieved. It will divide the captured text in the following categories.
  • TextBlock - In this category, the scanned paragraph is captured.
  • Line - In this category, the line of text captured from Textblock takes place.
  • Element- In this category, the word captured from line takes place.

Coding Part:

Step 1
We will start coding for OCR. Create New Android Project. Add the following line in your app level build.gradle file to import the library.

For Android Studio before 3.0
compile'com.google.android.gms:play-services-vision:11.8.0'
From Android Studio 3.0
implementation 'com.google.android.gms:play-services-vision:11.8.0'
Step 2
Open your Manifest file and add the following code block to instruct the app to install or download the dependencies at the time of installing the app.
<meta-data android:name="com.google.android.gms.vision.DEPENDENCIES"
android:value="ocr"/>
Step 3
Open your activity_main.xml file and paste the following code. It just the designer part of the application.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="15dp">
    <ImageView
        android:id="@+id/image_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scaleType="centerInside" />
    <Button
        android:id="@+id/btnProcess"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Process" />
    <TextView
        android:id="@+id/txtView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="No Text"
        android:layout_gravity="center"
        android:textSize="25sp" />
</LinearLayout>
Open your MainActivity.java file and initialize the widget used in your designer. Add the following code to start Optical Character Recognition.
// To get bitmap from resource folder of the application.
bitmap = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.ocr_sample);
// Starting Text Recognizer
TextRecognizer txtRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
if (!txtRecognizer.isOperational())
{
        // Shows if your Google Play services is not up to date or OCR is not supported for the device
 txtView.setText("Detector dependencies are not yet available");
}
else
{
 // Set the bitmap taken to the frame to perform OCR Operations.
        Frame frame = new Frame.Builder().setBitmap(bitmap).build();
 SparseArray items = txtRecognizer.detect(frame);
 StringBuilder strBuilder = new StringBuilder();
 for (int i = 0; i < items.size(); i++)
 {
  TextBlock item = (TextBlock)items.valueAt(i);
  strBuilder.append(item.getValue());
  strBuilder.append("/");
                // The following Process is used to show how to use lines & elements as well
                for (int i = 0; i < items.size(); i++) {
                        TextBlock item = (TextBlock) items.valueAt(i);
                        strBuilder.append(item.getValue());
                        strBuilder.append("/");
                        for (Text line : item.getComponents()) {
                            //extract scanned text lines here
                            Log.v("lines", line.getValue());
                            for (Text element : line.getComponents()) {
                                //extract scanned text words here
                                Log.v("element", element.getValue());
                            }
                        }
                    }
 }
 txtView.setText(strBuilder.toString());
}
txtRecognizer.isOperational() is used to check the device has the support for Google Visison API. The output of the TextRecognizer can be retrieved by using SparseArray and StringBuilder.

TextBlock:

I have used TextBlock to retrieve the paragraph from the image using OCR.

Lines:

You can get the line from the TextBlock using
textblockName.getComponents()

Element:

You can get the line from the TextBlock using
lineName.getComponents()

Demo:

The output of this app is

Download Code:

You can the download code for this post from Github. If you like this, tutorial star it on Github.

In this tutorial, we will learn how to implement SQLite Operations in Android with Kotlin . It is similar to the way of implementing SQL...

Android SQLite Tutorial - Kotlin Android SQLite Tutorial - Kotlin

A blog about android developement

In this tutorial, we will learn how to implement SQLite Operations in Android with Kotlin. It is similar to the way of implementing SQLite using Java. To learn the basics of Kotlin click here.

Project Setup:

Create new Project with Kotlin Support in Android Studio 3.0 or If you are using Android Studio version below 3.0 then setup Kotlin Plugin.

Coding Part

Create a kotlin class named as Tasks.kt and paste the following code
class Tasks {

    var id: Int = 0
    var name: String = ""
    var desc: String = ""
    var completed: String = "N"

}
DatabaseHandler
Create a Kotlin class named as DatabaseHandler.kt. It is used to Handle the database operations of SQLite with Kotlin. The Parent of this class is SQLiteOpenHelper. Paste the following code in DatabaseHandler.kt
class DatabaseHandler(context: Context) : SQLiteOpenHelper(context, DatabaseHandler.DB_NAME, null, DatabaseHandler.DB_VERSION) {

    override fun onCreate(db: SQLiteDatabase) {
        val CREATE_TABLE = "CREATE TABLE $TABLE_NAME ($ID INTEGER PRIMARY KEY, $NAME TEXT,$DESC TEXT,$COMPLETED TEXT);"
        db.execSQL(CREATE_TABLE)
    }

    override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
        val DROP_TABLE = "DROP TABLE IF EXISTS $TABLE_NAME"
        db.execSQL(DROP_TABLE)
        onCreate(db)
    }
}

CRUD Operations of SQLite

Now we need to write methods for handling all database read and write operations. Here we are implementing following methods for our tasks table.

Insert data to Table
The following code is used to add tasks to SQLite.
fun addTask(tasks: Tasks): Boolean {
 val db = this.writableDatabase
 val values = ContentValues()
 values.put(NAME, tasks.name)
 values.put(DESC, tasks.desc)
 values.put(COMPLETED, tasks.completed)
 val _success = db.insert(TABLE_NAME, null, values)
 db.close()
 Log.v("InsertedId", "$_success")
 return (Integer.parseInt("$_success") != -1)
}
Get all data from Table
The following code is used to get all tasks from SQLite.
fun task(): List {
 val taskList = ArrayList()
 val db = writableDatabase
 val selectQuery = "SELECT  * FROM $TABLE_NAME"
 val cursor = db.rawQuery(selectQuery, null)
 if (cursor != null) {
  if (cursor.moveToFirst()) {
   do {
    val tasks = Tasks()
    tasks.id = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ID)))
    tasks.name = cursor.getString(cursor.getColumnIndex(NAME))
    tasks.desc = cursor.getString(cursor.getColumnIndex(DESC))
    tasks.completed = cursor.getString(cursor.getColumnIndex(COMPLETED))
    taskList.add(tasks)
   } while (cursor.moveToNext())
  }
 }
 cursor.close()
 return taskList
}
Get particular data from Table
The following code is used to get particular task from SQLite.
fun getTask(_id: Int): Tasks {
 val tasks = Tasks()
 val db = writableDatabase
 val selectQuery = "SELECT  * FROM $TABLE_NAME WHERE $ID = $_id"
 val cursor = db.rawQuery(selectQuery, null)

 cursor?.moveToFirst()
 tasks.id = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ID)))
 tasks.name = cursor.getString(cursor.getColumnIndex(NAME))
 tasks.desc = cursor.getString(cursor.getColumnIndex(DESC))
 tasks.completed = cursor.getString(cursor.getColumnIndex(COMPLETED))
 cursor.close()
 return tasks
}
Update data to Table
The following code is used to update particular task to SQLite.
fun updateTask(tasks: Tasks): Boolean {
 val db = this.writableDatabase
 val values = ContentValues()
 values.put(NAME, tasks.name)
 values.put(DESC, tasks.desc)
 values.put(COMPLETED, tasks.completed)
 val _success = db.update(TABLE_NAME, values, ID + "=?", arrayOf(tasks.id.toString())).toLong()
 db.close()
 return Integer.parseInt("$_success") != -1
}
Delete data from Table
The following code is used to delete particular or all task(s) from SQLite.
// delete particular data
fun deleteTask(_id: Int): Boolean {
 val db = this.writableDatabase
 val _success = db.delete(TABLE_NAME, ID + "=?", arrayOf(_id.toString())).toLong()
 db.close()
 return Integer.parseInt("$_success") != -1
}

// delete all data
fun deleteAllTasks(): Boolean {
 val db = this.writableDatabase
 val _success = db.delete(TABLE_NAME, null, null).toLong()
 db.close()
 return Integer.parseInt("$_success") != -1
}
Full Code of DatabaseHandler
class DatabaseHandler(context: Context) : SQLiteOpenHelper(context, DatabaseHandler.DB_NAME, null, DatabaseHandler.DB_VERSION) {

    override fun onCreate(db: SQLiteDatabase) {
        val CREATE_TABLE = "CREATE TABLE $TABLE_NAME ($ID INTEGER PRIMARY KEY, $NAME TEXT,$DESC TEXT,$COMPLETED TEXT);"
        db.execSQL(CREATE_TABLE)
    }

    override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
        val DROP_TABLE = "DROP TABLE IF EXISTS $TABLE_NAME"
        db.execSQL(DROP_TABLE)
        onCreate(db)
    }

    fun addTask(tasks: Tasks): Boolean {
        val db = this.writableDatabase
        val values = ContentValues()
        values.put(NAME, tasks.name)
        values.put(DESC, tasks.desc)
        values.put(COMPLETED, tasks.completed)
        val _success = db.insert(TABLE_NAME, null, values)
        db.close()
        Log.v("InsertedId", "$_success")
        return (Integer.parseInt("$_success") != -1)
    }

    fun getTask(_id: Int): Tasks {
        val tasks = Tasks()
        val db = writableDatabase
        val selectQuery = "SELECT  * FROM $TABLE_NAME WHERE $ID = $_id"
        val cursor = db.rawQuery(selectQuery, null)

        cursor?.moveToFirst()
        tasks.id = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ID)))
        tasks.name = cursor.getString(cursor.getColumnIndex(NAME))
        tasks.desc = cursor.getString(cursor.getColumnIndex(DESC))
        tasks.completed = cursor.getString(cursor.getColumnIndex(COMPLETED))
        cursor.close()
        return tasks
    }

    fun task(): List {
        val taskList = ArrayList()
        val db = writableDatabase
        val selectQuery = "SELECT  * FROM $TABLE_NAME"
        val cursor = db.rawQuery(selectQuery, null)
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                do {
                    val tasks = Tasks()
                    tasks.id = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ID)))
                    tasks.name = cursor.getString(cursor.getColumnIndex(NAME))
                    tasks.desc = cursor.getString(cursor.getColumnIndex(DESC))
                    tasks.completed = cursor.getString(cursor.getColumnIndex(COMPLETED))
                    taskList.add(tasks)
                } while (cursor.moveToNext())
            }
        }
        cursor.close()
        return taskList
    }

    fun updateTask(tasks: Tasks): Boolean {
        val db = this.writableDatabase
        val values = ContentValues()
        values.put(NAME, tasks.name)
        values.put(DESC, tasks.desc)
        values.put(COMPLETED, tasks.completed)
        val _success = db.update(TABLE_NAME, values, ID + "=?", arrayOf(tasks.id.toString())).toLong()
        db.close()
        return Integer.parseInt("$_success") != -1
    }

    fun deleteTask(_id: Int): Boolean {
        val db = this.writableDatabase
        val _success = db.delete(TABLE_NAME, ID + "=?", arrayOf(_id.toString())).toLong()
        db.close()
        return Integer.parseInt("$_success") != -1
    }

    fun deleteAllTasks(): Boolean {
        val db = this.writableDatabase
        val _success = db.delete(TABLE_NAME, null, null).toLong()
        db.close()
        return Integer.parseInt("$_success") != -1
    }

    companion object {
        private val DB_VERSION = 1
        private val DB_NAME = "MyTasks"
        private val TABLE_NAME = "Tasks"
        private val ID = "Id"
        private val NAME = "Name"
        private val DESC = "Desc"
        private val COMPLETED = "Completed"
    }
}

Add Tasks

The following code is used to call Insert Function in DatabaseHandler
val tasks: Tasks = Tasks()
tasks.name = input_name.text.toString()
tasks.desc = input_desc.text.toString()
if (swt_completed.isChecked)
 tasks.completed = "Y"
else
 tasks.completed = "N"
success = dbHandler?.addTask(tasks) as Boolean

Update Tasks

The following code is used to call update Function in DatabaseHandler
val tasks: Tasks = Tasks()
tasks.id = intent.getIntExtra("Id", 0)
tasks.name = input_name.text.toString()
tasks.desc = input_desc.text.toString()
if (swt_completed.isChecked)
 tasks.completed = "Y"
else
 tasks.completed = "N"
success = dbHandler?.updateTask(tasks) as Boolean

Delete Tasks

The following code is used to call delete Functions in DatabaseHandler
// Delete Task
val success = dbHandler?.deleteTask(intent.getIntExtra("Id", 0)) as Boolean
// Delete All Tasks
dbHandler!!.deleteAllTasks()

Read Tasks

The following code is used to call read Functions in DatabaseHandler
// Read All Tasks
val tasks: Tasks = dbHandler!!.getTask(intent.getIntExtra("Id",0))
// Read Particular Task
dbHandler = DatabaseHandler(this)
listTasks = (dbHandler as DatabaseHandler).task()
In this tutorial, I have used Recyclerview. To implement Recyclerview click here.

Full Code of this tutorial

Create MainActivity.kt and Paste the following code
class MainActivity : AppCompatActivity() {

    var taskRecyclerAdapter: TaskRecyclerAdapter? = null;
    var fab: FloatingActionButton? = null
    var recyclerView: RecyclerView? = null
    var dbHandler: DatabaseHandler? = null
    var listTasks: List = ArrayList()
    var linearLayoutManager: LinearLayoutManager? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initViews()
        initOperations()
        //initDB()
    }

    fun initDB() {
        dbHandler = DatabaseHandler(this)
        listTasks = (dbHandler as DatabaseHandler).task()
        taskRecyclerAdapter = TaskRecyclerAdapter(tasksList = listTasks, context = applicationContext)
        (recyclerView as RecyclerView).adapter = taskRecyclerAdapter
    }

    fun initViews() {
        val toolbar = findViewById(R.id.toolbar) as Toolbar
        setSupportActionBar(toolbar)
        fab = findViewById(R.id.fab) as FloatingActionButton
        recyclerView = findViewById(R.id.recycler_view) as RecyclerView
        taskRecyclerAdapter = TaskRecyclerAdapter(tasksList = listTasks, context = applicationContext)
        linearLayoutManager = LinearLayoutManager(applicationContext)
        (recyclerView as RecyclerView).layoutManager = linearLayoutManager
    }

    fun initOperations() {
        fab?.setOnClickListener { view ->
            val i = Intent(applicationContext, AddOrEditActivity::class.java)
            i.putExtra("Mode", "A")
            startActivity(i)
        }
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        val id = item.itemId
        if (id == R.id.action_delete) {
            val dialog = AlertDialog.Builder(this).setTitle("Info").setMessage("Click 'YES' Delete All Tasks")
                    .setPositiveButton("YES", { dialog, i ->
                        dbHandler!!.deleteAllTasks()
                        initDB()
                        dialog.dismiss()
                    })
                    .setNegativeButton("NO", { dialog, i ->
                        dialog.dismiss()
                    })
            dialog.show()
            return true
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onResume() {
        super.onResume()
        initDB()
    }
}
Create AddOrEditActivity.kt and Paste the following code
class AddOrEditActivity : AppCompatActivity() {

    var dbHandler: DatabaseHandler? = null
    var isEditMode = false

    public override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_add_edit)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        initDB()
        initOperations()
    }

    private fun initDB() {
        dbHandler = DatabaseHandler(this)
        btn_delete.visibility = View.INVISIBLE
        if (intent != null && intent.getStringExtra("Mode") == "E") {
            isEditMode = true
            val tasks: Tasks = dbHandler!!.getTask(intent.getIntExtra("Id",0))
            input_name.setText(tasks.name)
            input_desc.setText(tasks.desc)
            swt_completed.isChecked = tasks.completed == "Y"
            btn_delete.visibility = View.VISIBLE
        }
    }

    private fun initOperations() {
        btn_save.setOnClickListener({
            var success: Boolean = false
            if (!isEditMode) {
                val tasks: Tasks = Tasks()
                tasks.name = input_name.text.toString()
                tasks.desc = input_desc.text.toString()
                if (swt_completed.isChecked)
                    tasks.completed = "Y"
                else
                    tasks.completed = "N"
                success = dbHandler?.addTask(tasks) as Boolean
            } else {
                val tasks: Tasks = Tasks()
                tasks.id = intent.getIntExtra("Id", 0)
                tasks.name = input_name.text.toString()
                tasks.desc = input_desc.text.toString()
                if (swt_completed.isChecked)
                    tasks.completed = "Y"
                else
                    tasks.completed = "N"
                success = dbHandler?.updateTask(tasks) as Boolean
            }

            if (success)
                finish()
        })

        btn_delete.setOnClickListener({
            val dialog = AlertDialog.Builder(this).setTitle("Info").setMessage("Click 'YES' Delete the Task.")
                    .setPositiveButton("YES", { dialog, i ->
                        val success = dbHandler?.deleteTask(intent.getIntExtra("Id", 0)) as Boolean
                        if (success)
                            finish()
                        dialog.dismiss()
                    })
                    .setNegativeButton("NO", { dialog, i ->
                        dialog.dismiss()
                    })
            dialog.show()
        })
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        val id = item.itemId
        if (id == android.R.id.home) {
            finish()
            return true
        }
        return super.onOptionsItemSelected(item)
    }
}

Download Code:

You can the download code for this post from Github. If you like this, tutorial star it on Github.

Unified SMS Sending API for Android This is a common interface for sms services that provide the possibility for programmatically send ...

Unified SMS Sending API for Android Unified SMS Sending API for Android

A blog about android developement

Unified SMS Sending API for Android

This is a common interface for sms services that provide the possibility for programmatically send SMS.

Support SMS Services

Nexmo
Twilio
Twizo
Msg91

How to Download

You can download the library using Gradle or Maven

Gradle

compile 'com.ajts.library.unifiedsms:unifiedsmslibrary:1.0.0'

Maven

<dependency>
  <groupId>com.ajts.library.unifiedsms</groupId>
  <artifactId>unifiedsmslibrary</artifactId>
  <version>1.0.0</version>
  <type>pom</type>
</dependency>

How to Use

SMS API Initialization

SMS sms = new SMS();

Nexmo SMS Service

Nexmo nexmo = new Nexmo("[Nexmo API Key]", "[Nexmo API Secret]");
sms.sendSMS(nexmo, "[Sender Name]", "[To number with country code]", "[Text Message]", new SMSCallback() {
    @Override
    public void onResponse(Call call, Response response) {
        Log.v("nexmo", response.toString());
    }

    @Override
    public void onFailure(Call call, Exception e) {

    }
});

Twilio SMS Service

Twilio twilio = new Twilio("[Twilio Account SID]", "[Twilio Auth Token]");
sms.sendSMS(twilio, "[Sender Name]", "[To number with country code]", "[Text Message]", new SMSCallback() {
    @Override
    public void onResponse(Call call, Response response) {
        Log.v("twilio", response.toString());
    }

    @Override
    public void onFailure(Call call, Exception e) {

    }
});

Twizo SMS Service

Twizo twizo = new Twizo("[Twizo Key]");
sms.sendSMS(twizo, "[Sender Name]", "[To number with country code]", "[Text Message]", new SMSCallback() {
    @Override
    public void onResponse(Call call, Response response) {
        Log.v("twizo", response.toString());
    }

    @Override
    public void onFailure(Call call, Exception e) {

    }
});

Msg91 SMS Service

Msg91 msg91 = new Msg91("[Msg91-Auth-Key]");
sms.sendSMS(msg91, "[Sender Name]", "[To number]", "[Text Message]", "[Country Code]", new SMSCallback() {
    @Override
    public void onResponse(Call call, Response response) {
        Log.v("msg91", response.toString());
    }

    @Override
    public void onFailure(Call call, Exception e) {
        Log.v("msg91", e.toString());
    }
});

Issue Tracker

Note:

If you find any issues regarding this API, you can make issue in Github with SMS API Issues Label

In this tutorial, we will learn how to validate forms in Android using Saripaar Library. Android Saripaar is a simple, feature-rich and...

Android Form Validation using Saripaar Validator Android Form Validation using Saripaar Validator

A blog about android developement


In this tutorial, we will learn how to validate forms in Android using Saripaar Library. Android Saripaar is a simple, feature-rich and powerful rule-based UI form validation library for Android. It is the Simplest UI validation library available for Android. To learn about Butter Knife, read my previous article.

Advantages of using Saripaar:

  1. Simple to Use.
  2. Easily Customizable
  3. Supports all annotation services in Android like Butter Knife, Android Annotations, Robo Guice, etc.,

Project Setup:

In this tutorial, I have used Saripaar with Butter Knife. Open Project Level Gradle file and paste the following
dependencies {
 classpath 'com.android.tools.build:gradle:2.3.3'
 classpath 'com.jakewharton:butterknife-gradle-plugin:8.8.1'
}
Open App level Gradle file and add the following dependencies
apply plugin: 'com.jakewharton.butterknife'
...
dependencies {
    ...
    compile 'com.mobsandgeeks:android-saripaar:2.0.2'
    compile 'com.jakewharton:butterknife:8.8.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
}

Examples:

The following example is used to validate email id with EditText. 
@BindView(R.id.email)
@NotEmpty
@Email
EditText emailEditText;
@NotEmpty is used to make mandatory input of EditText.
@Email is used to validate Email input.
@BindView used for Butter Knife
The following example is used to validate Password with Confirm Password.
@BindView(R.id.password)
@Password(min = 6, scheme = Password.Scheme.ALPHA_NUMERIC_MIXED_CASE_SYMBOLS)
EditText passwordEditText;
@BindView(R.id.conf_password)
@ConfirmPassword
EditText confirmPasswordEditText;
@Password is used to validate password with ALPHA_NUMERIC_MIXED_CASE_SYMBOLS
@ConfirmPassword used to match @Password input with Confirm Password input.
The following example is used to validate with custom pattern and custom message.
@BindView(R.id.phone)
@Pattern(regex = "^[7-9][0-9]{9}$", message = "Invalid Mobile Number")
EditText phoneEditText;
@Pattern is used to validate custom pattern.
regex is used to set custom pattern.
message used to set custom message.

Validation Process:

You can set validation listener like below.
public class MainActivity extends AppCompatActivity 
   implements Validator.ValidationListener {
   
   ...   

    @Override
    public void onValidationSucceeded() {
        Toast.makeText(this, "Validation Success", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onValidationFailed(List errors) {
        for (ValidationError error : errors) {
            View view = error.getView();
            String message = error.getCollatedErrorMessage(this);

            // Display error messages ;)
            if (view instanceof EditText) {
                ((EditText) view).setError(message);
            } else {
                Toast.makeText(this, message, Toast.LENGTH_LONG).show();
            }
        }
    }
   
}
The Form validated with the following code
validator = new Validator(this);
validator.setValidationListener(this);
...
@OnClick(R.id.submit)
public void onButtonClick(View view) {
 validator.validate();
}

Download Code:

You can the download code for this post from Github. If you like this, tutorial star it on Github.

Hi, Friends. In this post we will see how to integrate Telegram Bot in Android. It is a light weight library used to manage your Telegram...

Telegram Bot for Android Telegram Bot for Android

A blog about android developement

Hi, Friends. In this post we will see how to integrate Telegram Bot in Android. It is a light weight library used to manage your Telegram Bot in your Android application. We can send Messages from our own Android Application to Telegram Users.

Project Setup

Open app level build.gradle file and add the following dependency.
compile 'com.ajts.library.telegrambot:telegrambotlibrary:1.0.0'

Coding Part

Open your Activity file (e.g.,MainActivity.java) and initialize telegram bot library with your bot token.
Telegram telegram = new Telegram("<bot-token>");

I have used the services offered by this library.

Authorizing Telegram Bot

It is used to Authorize or Get the details of your bot

telegram.getMe(new TelegramCallback<GetMe>() {
    @Override
    public void onResponse(Call call, final GetMe getMe) {
        Log.v("response.body()", getMe.isOk() + "");
    }

    @Override
    public void onFailure(Call call, Exception e) {

    }
});

We can send Text Messages to telegram as well as with Markdown or HTML

Send Text Message

telegram.sendMessage("<Channel-Name or Chat-ID>", "TelegramBotLibrary", new TelegramCallback<Message>() {
    @Override
    public void onResponse(Call call, Message response) {
        Log.v("response.body()", response.isOk() + "");
    }

    @Override
    public void onFailure(Call call, Exception e) {

    }
});

Send Text Message with Html and Markdown

Html

telegram.sendMessage("<Channel-Name or Chat-ID>",
    "<i>TelegramBotLibrary</i>",
    Telegram.ParseMode.HTML,
    new TelegramCallback<Message>() {
        @Override
        public void onResponse(Call call, Message response) {
            Toast.makeText(MainActivity.this, response.isOk() + "", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailure(Call call, Exception e) {

        }
    });

Markdown

telegram.sendMessage("<Channel-Name or Chat-ID>",
    "*TelegramBotLibrary*",
    Telegram.ParseMode.Markdown,
    new TelegramCallback<Message>() {
        @Override
        public void onResponse(Call call, Message response) {
            Toast.makeText(MainActivity.this, response.isOk() + "", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailure(Call call, Exception e) {

        }
    });
We can send Media files to telegram as well.

Send Photo

telegram.sendPhoto("<Channel-Name or Chat-ID>",
    TelegramMediaType.Image.png,
    new File(imagePickedPath),
    "telegram photo",
    new TelegramCallback<Message>() {
        @Override
        public void onResponse(Call call, Message response) {
            Toast.makeText(MainActivity.this, response.isOk() + "", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailure(Call call, Exception e) {

        }
    });

Send Video

telegram.sendVideo("<Channel-Name or Chat-ID>",
    TelegramMediaType.Video.mp4,
    new File(videoPickedPath),
    "telegram video",
    new TelegramCallback<Message>() {
        @Override
        public void onResponse(Call call, Message response) {
            Toast.makeText(MainActivity.this, response.isOk() + "", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailure(Call call, Exception e) {

        }
    });

Send Audio

telegram.sendAudio("<Channel-Name or Chat-ID>",
    TelegramMediaType.Audio.mp3,
    new File(audioPickedPath),
    "telegram audio",
    new TelegramCallback<Message>() {
        @Override
        public void onResponse(Call call, Message response) {
            Toast.makeText(MainActivity.this, response.isOk() + "", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailure(Call call, Exception e) {

        }
    });

Send Document

telegram.sendDocument("<Channel-Name or Chat-ID>",
    TelegramMediaType.Document.file,
    new File(documentPickedPath),
    "telegram document",
    new TelegramCallback<Message>() {
        @Override
        public void onResponse(Call call, Message response) {
            Toast.makeText(MainActivity.this, response.isOk() + "", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailure(Call call, Exception e) {

        }
    });

Send Location

telegram.sendLocation("<Channel-Name or Chat-ID>",
    "<Latitude>",
    "<Longitude>",
    new TelegramCallback<Message>() {
        @Override
        public void onResponse(Call call, Message response) {
            Toast.makeText(MainActivity.this, response.isOk() + "", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailure(Call call, Exception e) {

        }
    });

Send Venue

telegram.sendVenue("<Channel-Name or Chat-ID>",
    "<Latitude>",
    "<Longitude>",
    "<Address>",
    "<Country>",
    new TelegramCallback<Message>() {
        @Override
        public void onResponse(Call call, Message response) {
            Toast.makeText(MainActivity.this, response.isOk() + "", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailure(Call call, Exception e) {

        }
    });

Download Code

You can the download code for this post from Github. If you like this, tutorial star it on Github.

In this tutorial, we will learn how to implement same Navigation Drawer for different activities. Navigation Drawer is an important wi...

Navigation Drawer Activity in Android Navigation Drawer Activity in Android

A blog about android developement

navdarwer

In this tutorial, we will learn how to implement same Navigation Drawer for different activities. Navigation Drawer is an important widget in android application. We can use fragments in navigation view to change screens based on the menu selection. It may lead to back stack issue. Instead of using fragments we can use this approach and is very easy to implement.

Coding part

Create new project, select Navigation drawer activity and click "finish".
Rename MainActivity into BaseActivity and paste the following code.
public class BaseActivity extends AppCompatActivity
 implements NavigationView.OnNavigationItemSelectedListener {

DrawerLayout drawer;
FloatingActionButton fab;
NavigationView navigationView;

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

 fab = (FloatingActionButton) findViewById(R.id.fab);
 drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
 ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
   this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
 drawer.setDrawerListener(toggle);
 toggle.syncState();

 navigationView = (NavigationView) findViewById(R.id.nav_view);
 navigationView.setNavigationItemSelectedListener(this);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
 int id = item.getItemId();
 if (id == R.id.nav_activity1) {
  startAnimatedActivity(new Intent(getApplicationContext(), FirstActivity.class));
 } else if (id == R.id.nav_activity2) {
  startAnimatedActivity(new Intent(getApplicationContext(), SecondActivity.class));
 }

 drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
 drawer.closeDrawer(GravityCompat.START);
 return true;
}
Open content_main.xml and paste the following code.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.androidmads.navdraweractivity.BaseActivity"
    tools:showIn="@layout/app_bar_main" />
here, the FrameLayout has the id as "content_frame" is used to hold the activity's view.
Create New Activity and named as FirstActivity.java and change the parent of this class from AppCompatActivity to BaseActivity as we created. Replace setContentView in onCreate method as shown below
setContentView(R.layout.activity_first)
to
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//inflate your activity layout here!
@SuppressLint("InflateParams")
View contentView = inflater.inflate(R.layout.activity_first, null, false);
drawer.addView(contentView, 0);
Here,
  • activity_first is the designer layout of the activity FirstActivity.java
Full code for FirstActivity.java is given below
public class FirstActivity extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        //inflate your activity layout here!
        @SuppressLint("InflateParams")
        View contentView = inflater.inflate(R.layout.activity_first, null, false);
        drawer.addView(contentView, 0);
        navigationView.setCheckedItem(R.id.nav_activity1);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Hello First Activity", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_first, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_menu_first) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                finishAffinity();
            } else {
                super.onBackPressed();
            }
        }
    }
}
here, the parent of FirstActivity is BaseActivity. In this way you can use same NavigationView for all activities. 

Note:Don't forget to change your launcher activity into FirstActivity. 

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.


If you like this tutorial, like & share our facebook page.

SQLite to Excel Version 1.0.2 released included with the following features Features 1.0.2 Added support to add new column from ex...

SQLiteToExcel v1.0.2 SQLiteToExcel v1.0.2

A blog about android developement

SQLite2Excel
SQLite to Excel Version 1.0.2 released included with the following features

Features

1.0.2

Added support to add new column from excel while importing, if the column is not exists with your Existing SQLite Database.

How to Download

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

How to Use

The steps to use this Library

<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");
or To drop table while importing the Excel, use the following
ExcelToSQLite excelToSQLite = new ExcelToSQLite(getApplicationContext(), "helloworld.db", true);
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) {

    }
});

Using SQLite2XL

Mail me with your Google Play URL and I'll add your app to the list :)
Icon
App
Get it on Google Play

Wiki

Please visit the wiki for a complete guide on SQLite2XL.

Okio is a library that complements java.io and java.nio to make it much easier to access, store, and process your data. Simply Okio is...

Download file using Okio in Android Download file using Okio in Android

A blog about android developement


Okio is a library that complements java.io and java.nio to make it much easier to access, store, and process your data. Simply Okio is a modern I/O API for Java. 

In this post, we will see how to download image or any file using Okio. Okio is component for OkHttp

Coding Part

Create a new project in Android Studio.

Add following dependencies to your app-level build.gradle file.
compile 'com.squareup.okhttp3:okhttp:3.6.0'
Don't forget to add the following permission in your AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Implementation

Paste the following code in your Activity and Here, I have kept as MainActivity.java
public void downloadImg(View view) {
 try {
  Request request = new Request.Builder()
    .url(imageLink)
    .build();
  new OkHttpClient().newCall(request).enqueue(new Callback() {
   @Override
   public void onFailure(Call call, IOException e) {
   }

   @Override
   public void onResponse(Call call, Response response) 
    throws IOException {
    if (!folder.exists()) {
     boolean folderCreated = folder.mkdir();
     Log.v("folderCreated", folderCreated + "");
    }
    file = new File(folder.getPath() + "/savedImg.png");
    if (file.exists()) {
     boolean fileDeleted = file.delete();
     Log.v("fileDeleted", fileDeleted + "");
    }
    boolean fileCreated = file.createNewFile();
    Log.v("fileCreated", fileCreated + "");
    BufferedSink sink = Okio.buffer(Okio.sink(file));
    sink.writeAll(response.body().source());
    sink.close();
    new DownloadImage(file).execute();
   }
  });
 } catch (Exception e) {
  e.printStackTrace();
 }
}
It is similar to Java I/O API. It has two important components as BufferSource and BufferSink.
  • BufferSource is like InputStream in Java I/O API and BufferSink is like OutputStream.
  • You can view any Source as an InputStream, and you can view any InputStream as a Source. Similarly for Sink and OutputStream. 

Demo


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