Tuesday, March 26, 2019

Recommended android app architecture

Fallowing architecture of all awesome component demonstrate how a awesome android app design



Wednesday, February 7, 2018

Kotlin - Basic Types

Numbers

The representation of numbers in Kotlin is pretty similar to Java, however, Kotlin does not allow internal conversion of different data types. Following table lists different variable lengths for different numbers.

Type

Size
Double
64


Float
32


Long
64
Int
32


Short
16
Byte
8







 
 
Characters



Kotlin represents character using char. Character should be declared in a single quote like ‘c’. Please enter the following code in our coding ground and see how Kotlin interpret s the character variable. Character variable cannot be declared like number variables. Kotlin variable can be declared in two ways - one using “var” and another using “val”.


fun main(args: Array<String>) {

val letter: Char // defining a variable

letter = 'A' // Assigning a value to it

println("$letter")


}


Boolean



Boolean is very simple like other programming languages. We have only two values for Boolean – either true or false. In the following example, we will see how Kotlin interprets Boolean.


fun main(args: Array<String>) {

val letter: Boolean // defining a variable

letter = true // Assinging a value to it println("Your character value is "+"$letter")

}



Strings



Strings are character arrays. Like Java, they are immutable in nature. We have two kinds of string available in Kotlin - one is called raw String and another is called escaped String. In the following example, we will make use of these strings.


fun main(args: Array<String>) {

var rawString :String ="I am Raw String!"

val escapedString : String ="I am escaped String!\n" println("Hello!"+escapedString) println("Hey!!"+rawString)


}





Arrays



Arrays are a collection of homogeneous data. Like Java, Kotlin supports arrays of different data types. In the following example, we will make use of different arrays.


fun main(args: Array<String>) {

val numbers: IntArray = intArrayOf(1, 2, 3, 4, 5)


println("Hey!! I am array Example"+numbers[2])


}



Collections



Collection is a very important part of the data structure, which makes the software development easy for engineers. Kotlin has two types of collection - one is immutable collection (which means lists, maps and sets that cannot be editable) and another is mutable collection (this type of collection is editable). It is very important to keep in mind the type of collection used in your application, as Kotlin system does not represent any specific difference in them.


fun main(args: Array<String>) {

val numbers: MutableList<Int> = mutableListOf(1, 2, 3) //mutable List

val readOnlyView: List<Int> = numbers // immutable list

println("my immutable list--"+numbers) // prints "[1, 2, 3]"

numbers.add(4)

println("my immutable list after addition --"+numbers) // prints


"[1, 2, 3, 4]"

println(readOnlyView)

readOnlyView.clear() // -> does not compile


//gives error

}




In collection, Kotlin provides some useful methods such as first(), last(), filter(), etc. All these methods are self-descriptive and easy to implement . Moreover, Kotlin follows the same structure such as Java while implementing collection. You are free to implement any collection of your choice such as Map and Set.


fun main(args: Array<String>) {


val items = listOf(1, 2, 3, 4)

println("First Element of our list----"+items.first())

println("First Element of our list----"+items.last())

println("Even Numbers of our List ----"+items.filter { it % 2 == 0 })
//
returns [2, 4]


val readWriteMap = hashMapOf("foo" to 1, "bar" to 2)

println(readWriteMap["foo"])
// prints "1"







val strings = hashSetOf("a", "b", "c", "c")

println("My Set Values are"+strings)

}



Ranges


Ranges is another unique characteristic of Kotlin. Like Haskell, it provides an operator that helps you iterate through a range. Internally, it is implemented using rangeTo() and its operator form is (..).

In the following example, we will see how Kotlin interprets this range operator.


fun main(args: Array<String>) {

val i:Int =2

for (j in 1..4)

print(j) // prints "1234"

if (i in 1..10) { // equivalent of 1 <= i && i <= 10 println("we found your number --"+i)

}


}





















Thursday, January 12, 2017

Use SQLCipher in android to encrypt your SQLite database


package com.example.database;
import android.content.Context;
import net.sqlcipher.database.SQLiteDatabase;
import net.sqlcipher.database.SQLiteOpenHelper;

public class SQLCipherOpenHelper extends SQLiteOpenHelper {

    private final static String SQL_KEY = "akshay123";//password
    public static String DATABASE_NAME = "myDB.sqlite";
    public static int DATABASE_VERSION = 5;
    private static SQLCipherOpenHelper mInstance;
    public Context mContext;

    public synchronized static SQLCipherOpenHelper getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new SQLCipherOpenHelper(context);
        }
        return mInstance;
    }
    public SQLCipherOpenHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        SQLiteDatabase.loadLibs(context);
    }

//    public SQLCipherOpenHelper(Context context) {
//        super(context, context.getExternalFilesDir(null).getAbsolutePath() + "/" +
// DATABASE_NAME, null, DATABASE_VERSION);
// SQLiteDatabase.loadLibs(context);
//
//    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(MyController.CREATE_TABLE); 
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
        onCreate(db);
        db.execSQL(MyController.ADD_REPORT_TITLE);
    }

    public synchronized SQLiteDatabase getWritableDatabase() {

        return super.getWritableDatabase(SQL_KEY);
    }

    public synchronized SQLiteDatabase getReadableDatabase() {

        return super.getReadableDatabase(SQL_KEY);
    }

    public static void removeInstance() {
        mInstance = null;
    }

}



Thursday, July 14, 2016

Download image and save in your SD card

/** * Download image 
* @param imageurl remote image url 
* @param localpath your sd card path 
* @return file object 
*/
private File getPath(String imageurl, String localpath) {
    String filepath = null;
    File file = null;
    InputStream inputStream = null;
    try {

        URL url = new URL(imageurl);
        HttpURLConnection urlConnection = (HttpURLConnection) url
                .openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        urlConnection.setConnectTimeout(20000);
        try {
            urlConnection.connect();
            inputStream = urlConnection.getInputStream();
        } catch (SocketTimeoutException e) {

            return file;
        } catch (Exception e) {

            return file;
        }
        if (localpath != null) {
            file = new File(localpath);

            FileOutputStream fileOutput = new FileOutputStream(
                    file);

            int totalSize = urlConnection.getContentLength();
            int downloadedSize = 0;
            byte[] buffer = new byte[1024];
            int bufferLength = 0;
            if (inputStream != null) {
                while ((bufferLength = inputStream.read(buffer)) > 0) {
                    fileOutput.write(buffer, 0, bufferLength);
                    downloadedSize += bufferLength;               }
            }

            fileOutput.close();
           

        }
    } catch (Exception e) {
        e.printStackTrace();
        Log.i("ImageDownload", "Exception in DownloadRunnable" + e);
    }
    Log.i("filepath:", " " + filepath);
    return file;

}

Thursday, July 30, 2015

How to open android applications by web browsers

It is very simple to open android application by android browser i.e.  web deep linking .

Step 1:- Add intent-filter in your activity which need to open by web browser it is either main activity or other activity .
  e.g.

 <activity
            android:name=".YourActivity"
            android:label="@string/title_activity_your_deep_linking">
            <intent-filter>
                <data android:scheme="yourScheme" />
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
            </intent-filter>

  Step 2:- Create request link which will be executed by mobile browsers .

 <html>
<body>
<a href="yourScheme:?key1=4444&amp;key2=E110123&amp;type=wabpage&amp;status=1&amp;extra=value">click to open App</a>
</body>
</html
Note :yourScheme is app scheme followed by query string .

 Step 3:- Get data in YourActivity class by following android APIs .

  Uri uri = getIntent().getData();
 String key1= uri.getQueryParameter("key1").toString();
 String key2= uri.getQueryParameter("key2").toString();
                                        ...
                                        ...
                                        ...




Enjoy  android interesting feature  which will help you for referring for android application by browsers . 

Thursday, July 23, 2015

Handler vs AsyncTask vs Thread

 A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.
There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.
      1.   AsyncTask and Handler are written in Java (internally they use a Thread), so everything              you        can do with Handler or AsyncTask, you can achieve using a Thread too.
     2.     An AsyncTask is used to do some background computation and publish the result to the        UI  thread (with optional progress updates). Since you're not concerned with UI, then                   a Handler or Threadseems more appropriate.

          3.  Handler allows you to send and process Message and Runnable objects associated with     a  thread's MessageQueue.
         4.  When Handler communicates, it just gives a message to caller thread and it will wait to  process. Complicated? Just remember that Handler can communicate with the caller thread in  a safe way.