Thursday, 16 November 2017

Basic data types of KOTLIN and simple examples.

In this section we describe the basic types used in Kotlin: numbers, characters, booleans, arrays, and strings.

Numbers

Kotlin handles numbers in a way close to Java, but not exactly the same. For example, there are no implicit widening conversions for numbers, and literals are slightly different in some cases.

Kotlin provides the following built-in types representing numbers (this is close to Java):

Type Bit width
Double 64
Float 32
Long 64
Int 32
Short 16
Byte 8


We can declare data types in KOTLIN as following way.
var a: Int = 0 //int var, we can reassign at runtime or anywhere in the code. 
val a:Int =0 //int val, val cannot reassign.
var a = 0 //int var
val a = 0 //int val

var a = 10.10 //Double
var a = 10.10f //Float
var a = 10.10F //Float

var a = 10L //Long

//You can use underscores to make number constants more readable:
val oneMillion=1_000_000

Every number type supports the following conversions:

toByte(): Byte

toShort(): Short

toInt(): Int

toLong(): Long

toFloat(): Float

toDouble(): Double

toChar(): Char

Operations


Here is the complete list of bitwise operations (available for Int and Long only):
  1. shl(bits) – signed shift left (Java's <<)
  2. shr(bits) – signed shift right (Java's >>)
  3. ushr(bits) – unsigned shift right (Java's >>>)
  4. and(bits) – bitwise and
  5. or(bits) – bitwise or
  6. xor(bits) – bitwise xor
  7. inv() – bitwise inversion

Ex:

var x = 1 shl 2
var x = 1 shr 2
var x = 1 ushr 2
var x = 1 and 2
var x = 1 or 2
var x = 1 xor 2
var x = 1.inv()

Also we have int() instead of ++ and dec() instead of --.

Ex:

var x = a.inc()

Characters

Characters are represented by the type Char
var c = 'a'.

Booleans

The type Boolean represents booleans, and has two values: true and false.
var b = true

Strings

Strings are represented by the type String. Strings are immutable. var s = "Hello Kotlin"

Interesting right?


If you are really interested in this code, then share this post with your friends.


Text WhatsApp message to +91-99654 70689 To join Android Developers WhatsApp group.
Join WhatsApp group by this link
Thank You



Thursday, 9 November 2017

Using Button in Kotlin | Android

Though Kotlin has lot massive features to speedup the development time, here is the simple way of using Button in Android.
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import android.widget.Toast.LENGTH_LONG
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    private var count: Int = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        myButton.setOnClickListener({
            count = count.inc()
            Toast.makeText(this, "Clicked Count " + count, LENGTH_LONG).show()
            myButton.setText("Click again")
        })
    }
}

Did you noticed, Here we used colon(:) instead of extends keyword, but here we used parentheses at end of the AppCompatActivity.
And we initialized count as Int var, where Int is one of the data type in Kotlin used to declare int variable from Java, and var defines count as variable, means, can be reinitialized at run time.
And we never declare myButton nor initialized, instead we directly accessed it from activity_main.
And inside setOnClickListener method, we didn't implement `OnClickListener` interface.

So, in simple accessing of button itself, we omitted near 10 lines of code. So imagine about full length project, near 40% of time is saved right?
So, If you think this is the right time to start with Kotlin, then start alongside with your current project. Yes, you can use Java and Kotlin in same project. If your current Activity is java, don't worry, you can create your next Activity in kotlin. Or you can convert your current Activity also to Kotlin and then continue learning Kotlin in same Activity.

Here is the full video tutorial

Interesting right?


If you are really interested in this code, then share this post with your friends.


Getting Started on Kotlin


Text WhatsApp message to +91-99654 70689 To join Android Developers WhatsApp group.
Join WhatsApp group by this link
Thank You



Thursday, 2 November 2017

Getting Started on Kotlin

Kotlin is now an official language on Android. Kotlin is expressive, concise, extensible, powerful, and a joy to read and write. It has wonderful safety features in terms of nullability and immutability.

If you're interested in using Kotlin, it's easy to get started because it works side by side with Java and C++ on Android. So you can keep your existing code, continue to use the various Android libraries, and incrementally add Kotlin code to your project. Unlike almost any other language, Kotlin is a drop-in replacement you can use bi-directionally—you can call into the Java language from Kotlin, and you can call into Kotlin from the Java language.

Of course, IDE support is also crucial, and we have it. Android Studio is built upon IntelliJ IDEA, an IDE built by JetBrains—the same company that created the Kotlin language. The JetBrains team has been working for years to make sure Kotlin works great with IntelliJ IDEA. So we're inheriting all their hard work. Starting with Android Studio 3.0, tooling support for Kotlin is bundled directly into Android Studio.

Create a new project with Kotlin

Using Kotlin with a new project requires just one extra click in the New Project wizard:
  1. In Android Studio, click File > New > New Project. Or if you've just opened Android Studio and see the Welcome to Android Studio window, click Start a new Android Studio project.
  2. On the first screen, check Include Kotlin support. That's the only difference.
  3. Click Next and continue through the wizard until you're done.



Add Kotlin to an existing project

If you want to add Kotlin code to an existing project, simply click File > New and select one of the various Android templates. If you don't see the list of templates in this menu, first open the Project window and select your app module.

Convert existing Java code to Kotlin code

In Android Studio 3.0, open a Java file and select Code > Convert Java File to Kotlin File.

Or, create a new Kotlin file (File > New > Kotlin File/Class), and then paste your Java code into that file—when prompted, click Yes to convert the code to Kotlin. You can check Don't show this dialog next time, which makes it easy to dump Java code snippets into your Kotlin files.

Use Android APIs with Kotlin

Kotlin provides complete interoperability with the Java language, so calling the Android APIs often looks exactly like the matching Java code. Except now you can combine those method calls with Kotlin's syntax features.

Here are a few examples of what it looks like to call Android APIs in Kotlin, compared to the same code in Java language:

Declare Activity in Java

public class MyActivity extends AppCompatActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity);
  }
}

Declare Activity in Kotlin

class MyActivity : AppCompatActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity)
  }
}

On-click listener in Java

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View view) {
    //TODO: Do your code
  }
});

On-click listener in Kotlin

val fab = findViewById(R.id.fab) as FloatingActionButton
fab.setOnClickListener {
  //TODO: Do your code
}

Item click listener in Java

private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
    = new BottomNavigationView.OnNavigationItemSelectedListener() {
  @Override
  public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()) {
      case R.id.navigation_home:
        mTextMessage.setText(R.string.title_home);
        return true;
      case R.id.navigation_dashboard:
        mTextMessage.setText(R.string.title_dashboard);
        return true;
    }
    return false;
  }
};

Item click listener in Kotlin

private val mOnNavigationItemSelectedListener
    = BottomNavigationView.OnNavigationItemSelectedListener { item ->
  when (item.itemId) {
    R.id.navigation_home -> {
      mTextMessage.setText(R.string.title_home)
      return@OnNavigationItemSelectedListener true
    }
    R.id.navigation_dashboard -> {
      mTextMessage.setText(R.string.title_dashboard)
      return@OnNavigationItemSelectedListener true
    }
 }
 false
}

Here is the Get Started with Kotlin video.

Interesting right?


If you are really interested in this code, then share this post with your friends.


Text WhatsApp message to +91-99654 70689 To join Android Developers WhatsApp group.
Join WhatsApp group by this link
Thank You



Monday, 30 October 2017

Simple ConstraintLayout tutorial in Android.

A ConstraintLayout is a ViewGroup which allows you to position and size widgets in a flexible way.

There are currently various types of constraints that you can use:
  • Relative positioning
  • Margins
  • Centering positioning
  • Circular positioning
  • Visibility behavior
  • Dimension constraints
  • Chains
  • Virtual Helpers objects

In this tutorial we will look about Relative positioning more detailly.

Relative positioning


Relative positioning is one of the basic building block of creating layouts in ConstraintLayout. Those constraints allow you to position a given widget relative to another one. You can constrain a widget on the horizontal and vertical axis:
  • Horizontal Axis: left, right, start and end sides
  • Vertical Axis: top, bottom sides and text baseline
Here is the list of available constraints.
  • layout_constraintLeft_toLeftOf
  • layout_constraintLeft_toRightOf
  • layout_constraintRight_toLeftOf
  • layout_constraintRight_toRightOf
  • layout_constraintTop_toTopOf
  • layout_constraintTop_toBottomOf
  • layout_constraintBottom_toTopOf
  • layout_constraintBottom_toBottomOf
  • layout_constraintBaseline_toBaselineOf
  • layout_constraintStart_toEndOf
  • layout_constraintStart_toStartOf
  • layout_constraintEnd_toStartOf
  • layout_constraintEnd_toEndOf
They all take a reference id to another widget, or the parent (which will reference the parent container, i.e. the ConstraintLayout):
For example
<?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"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <View
        android:id="@+id/view1"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@android:color/holo_green_dark"
        app:layout_constraintBottom_toTopOf="@+id/view3"
        app:layout_constraintEnd_toStartOf="@+id/view2"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <View
        android:id="@+id/view2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@android:color/holo_orange_dark"
        app:layout_constraintBottom_toTopOf="@+id/view3"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/view1"
        app:layout_constraintTop_toTopOf="parent" />

    <View
        android:id="@+id/view3"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@android:color/holo_blue_dark"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/view1" />

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello Constraint Layout"
        android:textColor="@android:color/holo_red_dark"
        android:textSize="20sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
This xml will create following output.

Explaination

    <View
        android:id="@+id/view1"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@android:color/holo_green_dark"
        app:layout_constraintBottom_toTopOf="@+id/view3"
        app:layout_constraintEnd_toStartOf="@+id/view2"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
this code block indicates the system to align this view's bottom should be top of the view3, End should be start of the view2, Start should be start of the parent layout and Top should be top of the parent layout.
    <View
        android:id="@+id/view2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@android:color/holo_orange_dark"
        app:layout_constraintBottom_toTopOf="@+id/view3"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/view1"
        app:layout_constraintTop_toTopOf="parent" />
this code block indicates the system to align this view's bottom should be top of the view3, End should be end of the parent, Start should be end of the view1 layout and Top should be top of the parent layout.
    <View
        android:id="@+id/view3"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@android:color/holo_blue_dark"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/view1" />
this code block indicates the system to align this view's bottom should be bottom of the parent, End should be end of the parent, Start should be start of the parent layout and Top should be bottom of the view1.
    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello Constraint Layout"
        android:textColor="@android:color/holo_red_dark"
        android:textSize="20sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
this code block indicates the system to align this view's bottom should be bottom of the parent layout , End should be end of the parent layout , Start should be start of the parent layout and Top should be bottom of the parent layout, this is center alignment of the parent vertically and horizontally.

If you want to align center of parent horizontally only, then you should use
  • app:layout_constraintEnd_toEndOf="parent"
  • app:layout_constraintStart_toStartOf="parent"
If you want to align center of parent vertically only, then you should use
  • app:layout_constraintBottom_toBottomOf="parent"
  • app:layout_constraintTop_toTopOf="parent"
And also you can use
  • layout_constraintHorizontal_bias
  • layout_constraintVertical_bias
For example the following will make the left side with a 30% bias instead of the default 50%, such that the left side will be shorter, with the widget leaning more toward the left side
   <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello Constraint Layout"
        android:textColor="@android:color/holo_red_dark"
        android:textSize="20sp"
        android:textStyle="bold"
        app:layout_constraintHorizontal_bias="0.3"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />



Here is the full video tutorial

Interesting right?


If you are really interested in this code, then share this post with your friends.


Thank You



Wednesday, 25 October 2017

Simple way to show menu items on list item get selected

Here is the most easier way to showing menu items on list items get selected. Your Activity will look like this
public class MainActivity extends AppCompatActivity {

    private RecyclerView myList;
    private int selectedCount;
    private ArrayList list;
    private MyListAdapter adapter;

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

        myList = (RecyclerView) findViewById(R.id.myList);
        myList.setHasFixedSize(true);
        myList.setLayoutManager(new LinearLayoutManager(this));

        list = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            list.add(new Item("Row " + (i + 1)));
        }

        adapter = new MyListAdapter(list, this);
        myList.setAdapter(adapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return selectedCount > 0;
    }

    public void onLongClicked(int adapterPosition) {
        list.get(adapterPosition).isSelected = true;
        selectedCount++;
        adapter.notifyDataSetChanged();
        invalidateOptionsMenu();
    }

    public void onClicked(int adapterPosition) {
        if (selectedCount > 0) {
            Item item = list.get(adapterPosition);
            if (item.isSelected) {
                selectedCount--;
            } else {
                selectedCount++;
            }
            item.setSelected(!item.isSelected);
            adapter.notifyDataSetChanged();
            invalidateOptionsMenu();
        }
    }
}
And your adapter will look like,
public class MyListAdapter extends RecyclerView.Adapter {
    private ArrayList myList;
    private MainActivity activity;

    public MyListAdapter(ArrayList myList, MainActivity mainActivity) {
        this.myList = myList;
        activity = mainActivity;
    }

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

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        holder.textView.setText(myList.get(position).text);

        if (myList.get(position).isSelected) {
            holder.view.setBackgroundColor(ContextCompat.getColor(activity, R.color.colorAccent));
        }else {
            holder.view.setBackgroundColor(Color.WHITE);
        }
        holder.view.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                activity.onLongClicked(holder.getAdapterPosition());
                return true;
            }
        });

        holder.view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                activity.onClicked(holder.getAdapterPosition());
            }
        });
    }

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

    public class ViewHolder extends RecyclerView.ViewHolder {
        View view;
        TextView textView;

        public ViewHolder(View itemView) {
            super(itemView);
            view = itemView;
            textView = itemView.findViewById(R.id.text);
        }
    }
}
And your Item class will look like,
public class Item {
    boolean isSelected;
    String text;

    public Item(String text) {
        this.text = text;
    }

    public boolean isSelected() {
        return isSelected;
    }

    public void setSelected(boolean selected) {
        isSelected = selected;
    }
}
And your activity_main layout will look like,
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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.guna.testapplication.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

</android.support.design.widget.CoordinatorLayout>
And your content_main layout will look like,
<?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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.guna.testapplication.MainActivity"
    tools:showIn="@layout/activity_main">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/myList"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</android.support.constraint.ConstraintLayout>
And your menu_main will look like,
<menu 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"
    tools:context="com.guna.testapplication.MainActivity">
    <item
        android:id="@+id/action_share"
        android:title="@string/share"
        app:showAsAction="ifRoom" />

    <item
        android:id="@+id/action_delete"
        android:orderInCategory="100"
        android:title="@string/delete"
        app:showAsAction="never" />
</menu>
And your my_list_item layout will look like

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="1dp"
    android:background="#fff"
    android:orientation="vertical">

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp" />
</LinearLayout>


Here is the full video tutorial

Interesting right?


If you are really interested in this code, then share this post with your friends.


Thank You



Saturday, 14 October 2017

Do you know final size of this ArrayList?

I bet, You will never expect this strange answer. I am leaving it to you right now. Here is the code.
Integer[] list = {2, 4, 6, 8, 10};
ArrayList integerArrayList = new ArrayList<>();
integerArrayList.addAll(Arrays.asList(list));
for (int i = 0; i < integerArrayList.size(); i++) {
    if (integerArrayList.get(i) % 2 == 0) {
        integerArrayList.remove(i);
    }
}

Do you know the size of integerArrayList now? If your answer is 0, then its wrong. Shocked right? Here is the explanation. Let's deep dive into the code now. Add a Log inside the if statement.
Integer[] list = {2, 4, 6, 8, 10};
ArrayList integerArrayList = new ArrayList<>();
integerArrayList.addAll(Arrays.asList(list));
for (int i = 0; i < integerArrayList.size(); i++) {
    if (integerArrayList.get(i) % 2 == 0) {
        Log.v(TAG, "Current list data : " + integerArrayList.toString() + ", integerArrayList.get(" + i + ") : " + integerArrayList.get(i));
        integerArrayList.remove(i);
    }
}

Here is the Logcat output for this Log
Current list data : [2, 4, 6, 8, 10], integerArrayList.get(0) : 2
Current list data : [4, 6, 8, 10], integerArrayList.get(1) : 6
Current list data : [4, 8, 10], integerArrayList.get(2) : 10
So, now you may know.
In our for loop, at our first iteration we have 5 digits in our list, i is 0, size is 5, 0 < 5 condition passed, so we are removing 0th position, which is 2.
At our second iteration we have 4 digits in our list, i is 1, size is 4, 1 < 4 condition passed, and we are removing 1st position, which is 6.
At our third iteration we have 3 digits in our list, i is 2, size is 3, 2 < 3 condition passed, and we are removing 2nd position, which is 10.
At our fourth iteration we have 2 digits remaining in our list, i is 3, size is 2, 3 < 2 condition failed, so finally we have 2 digits our list, they are 4 and 8, still they are dividable by 2.

Interesting right?

If you are really interested in this strange code, then share your solution as comment. How will you remove all of the numbers in the given list which is dividable by 2 or n.



Thank You



Wednesday, 11 October 2017

Bypassing onCreate() on up navigation in Android Activity.


You may provide one back button in Android Activity's Toolbar at Top left corner. Default back button is enough. But in recent times this icon is provided for good design looking purpose only.

So simple design looking code shouldn't recreate the previous Activity right?

But in Android up navigation from one Activity to previous Activity will recreate the previous Activity. So the previous Activity's onCreate() method will get called. But sometime we don't want to recreate the previous Activity. Just resume is enough. So we may avoid unwanted coding execution which already executed.

But did you noticed that bottom default back button will not recreate the Activity. It will just resume the Activity which is in paused state already.

So we may use this default back button's code in up navigation also. Then while tapping up navigation icon also our previous Activity will resume instead of recreate.

Here is the code sample
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                //To resume previous activity on up navigation this simple code is enough.
                //By this we can simply resume previous activity.
                onBackPressed();
                break;
        }
        return true;
    }
Detailed video tutorial



I hope this post is useful to you. kindly share your feedback as comment here.



Thank You