Monday, July 29, 2019

Kotlin Introduction and Examples | Kotlin Hello Example | Kotlin For Loop | Kotlin While Loop | Kotlin Array | Android Kotlin


Dear Friends, Now in these days ‘Kotlin’ have been the very popular programming language for software development specially for Android Development so let us have a quick look and then in next Blog/Post we will use it in Android Projects.


Question: What is 'Kotlin'?
Answer: 'Kotlin' is a cross-platform statically typed language developed by JetBrains.

Question: What are the variable types in 'Kotlin'?
Answer: Below are the main variable types in 'Kotlin'-
Characters: 'Kotlin' uses ‘Char’ keyword for Characters. 

Booleans: 'Kotlin' uses ‘booleans’ keyword to represent Booleans which have 2 values true or false.

Number: 'Kotlin' have almost same keywords as Java for Number type- Double, Float, Long, Int, Short, Byte.

Strings: In 'Kotlin' Strings are represented by the 'String' keyword. 

Arrays: In 'Kotlin' Arrays are represented by the Array class, that has get and set functions. We will see some examples in later post. 

Question: How to use/write variables in 'Kotlin'?
Answer: Basically, there are two types of use of variables in 'Kotlin' language –
i)Read only or final variable(define with 'val' keyword)-
val num1: Int = 110 // Int with assignment
val num3: Int // without assignment
val name: String = “Manish” // String type with assignment 

ii)Reassigned variables(define with 'var' keyword)-
var num1: Int = 110 // with assignment
num1 = num1 + 90 // we change the value of Reassigned variables
var num3: Int // without assignment
var num2: 220 // with assignment but without type
var name = “Manish

Question: how to write 'Kotlin' functions?
Answer: We write 'Kotlin' function with 'fun' keyword and arguments with ':' keyword.

An Example of 'Kotlin' function to add 2 number-

fun sum(num1: Int, num2: Int): Int {
return num1 + num2
}

Question: How to use comment lines in 'Kotlin'?
Answer: It is the same as Java and other programming languages:

i)Single line or End of line comment 
//This is test comment line

ii)Multiline or Block
/*This is multiline test
Comment for 
Kotlin*/

=======Let us take some examples for better understanding======
1)HelloKotlin
class HelloKotlin
/*Kotlin fun with
Androidhub4you.com*/
fun main()
{
println("Hello from Androidhub4you.com")

}

Output: Hello from Androidhub4you.com


2)IfElseKotlin
class IfElseKotlin
/*Kotlin fun with
Androidhub4you.com*/
val num1: Int = 50
val num2: Int = 60
fun main()
{
        if (num1 > num2)
{
         println("num1 is greater than num2")
}
else
{
println("num1 is smaller than num2")
}

}

Output: num1 is smaller than num2



3)WhileLoopKotlin
class WhileLoopKotlin
/*Kotlin fun with
Androidhub4you.com*/
fun main()
{
var start = 1 //use 'var' as we want to do increment on start-varaiable
val max = 10 //use 'val' as we just want to comparaisen with max-varaible
while (start <= max)
{
println(start)
start++
}
}

Output:
1
2
3
4
5
6
7
8
9
10


4)ForLoopKotlin
class ForLoopKotlin
/*Kotlin fun with
Androidhub4you.com*/
fun main()
{
//increment one by one, it will include 15 as well
println("---Increment by 1 number, including till number---")
for (num1 in 10..15)
{
println(num1)
}
//increment one by one, it will include 15 as well
println("---Increment by 1 number, without till number---")
for (num1 in 15 until 20)
{
println(num1)
}
//increment by 2 number
println("---Increment by 2 number---")
for (num1 in 20 until 30 step 2)
{
println(num1)
}
println("---Decrement by 1 number---")
//for loop for decrement
for (num1 in 40 downTo 30)
println(num1) //we can exclude brackets if we want to write single line only
println("---Decrement by 2 number---")
//for loop for decrement
for (num1 in 50 downTo 40 step 2)
{
println(num1)
}

}

Output:
---Increment by 1 number, including till number---
10
11
12
13
14
15
---Increment by 1 number, without till number---
15
16
17
18
19
---Increment by 2 number---
20
22
24
26
28
---Decrement by 1 number---
40
39
38
37
36
35
34
33
32
31
30
---Decrement by 2 number---
50
48
46
44
42
40


5)ArrayKotlin
class ArrayKotlin
/*Kotlin fun with
Androidhub4you.com*/
fun main()
{
//use listOf keyword to store array elements
val arrayCountry = listOf("Germany", "USA", "UK", "Sweden")
//use for loop to print all elements in array
for(country in arrayCountry)
println(country)
//let us take one more example, how to create array of numbers using toList keyword
val arrayNumbers = (50..60).toList()
for (num in arrayNumbers)
println(num)

}

Output:
Germany
USA
UK
Sweden
50
51
52
53
54
55
56
57
58
59
60

Note: In order to run Kotlin programmes you may use Eclipse with Kotlin-Plugin or use IntelliJ-IDE. Let me know if need more assistance.

Thanks,
Manish

Sunday, January 31, 2016

Android Material Design Demo | Android Lolypop Material Design Example | Material Design Collaps Layout | Material Design SnackBar

Hello Friends,
Here a useful example for android material design, important steps are given below-

1)Create a new android project using visual studio.
2)open your build.gradle file from src folder and import below dependencies-
compile 'com.android.support:design:22.2.1'compile 'com.android.support:cardview-v7:22.2.1'
 
  
3) And now import full code from GIT-HUB and modify according to your use-

https://github.com/manishsri01/MaterialDesign

 




Important Code:
1)Calling fragments from navigation drawer-
@Overridepublic void onNavigationDrawerItemSelected(int position) {
    // update the main content by replacing fragments  
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    switch (position) {

        case 0:
            FloatingFragment homeFragment = new FloatingFragment();
            transaction.replace(R.id.container, homeFragment);
            transaction.commit();
            break;
        case 1:
            SnackBarFragment snackbar = new SnackBarFragment();
            transaction.replace(R.id.container, snackbar);
            transaction.commit();
            break;
        case 2:
            CollapsFragment collasps = new CollapsFragment();
            transaction.replace(R.id.container, collasps);
            transaction.commit();
            break;

    }
}
 
2)Ssnackbar action-
 
package com.android.materialdesign.fragment;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.android.materialdesign.R;

public class SnackBarFragment extends Fragment {

   @Override   public void onCreate(Bundle savedInstanceState) {
      // TODO Auto-generated method stub      super.onCreate(savedInstanceState);
   }

   @Override   public View onCreateView(LayoutInflater inflater, ViewGroup container,
                      Bundle savedInstanceState) {

      final View v = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_snackbar,
            container, false);

      FloatingActionButton fab = (FloatingActionButton)v.findViewById(R.id.fab);
      fab.setOnClickListener(new View.OnClickListener() {
         @Override         public void onClick(View view) {
            Snackbar.make(v.findViewById(R.id.coordinatorLayout), "I am a Snackbar", 
                 Snackbar.LENGTH_LONG).setAction("Action", new View.OnClickListener() {
               @Override               public void onClick(View v) {
                  Toast.makeText(getActivity(), "Snackbar Action", Toast.LENGTH_LONG).show();
               }
            }).show();
         }
      });

      return  v;
   }

}


 3)Floating point-

package com.android.materialdesign.fragment;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.android.materialdesign.R;

public class FloatingFragment extends Fragment {

   @Override   public void onCreate(Bundle savedInstanceState) {
      // TODO Auto-generated method stub      super.onCreate(savedInstanceState);
   }

   @Override   public View onCreateView(LayoutInflater inflater, ViewGroup container,
                      Bundle savedInstanceState) {

      View v = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_floating,
            container, false);
      FloatingActionButton fab = (FloatingActionButton)v.findViewById(R.id.fab);

      fab.setOnClickListener(new View.OnClickListener() {
         @Override         public void onClick(View view) {
            Toast.makeText(getActivity(),"work in progress..",Toast.LENGTH_SHORT).show();
         }
      });

      return  v;
   }

}


DOWNLOAD ZIP CODE

Thanks,
Manish

Monday, December 28, 2015

PHP Web-Services to Return JSON Array | PHP Web services | Simple JSON Array web services




<?php
//open database connection
$con = mysql_connect('localhost','root','root') or die('Cannot connect to the DB');
mysql_select_db('mydb',$con);

//make a sql query to store data
$sql="SELECT * from `mydb`.`user`";
$qur=mysql_query($sql);

//check the database response is it true or false
 if($qur){
 if (mysql_num_rows($qur)>0) {
//write data into json array
$info = array();

while ($row = mysql_fetch_assoc($qur))
{
     $arr = array();
     $arr["name"] = $row["name"];
     $arr["email"] = $row["email"];
     $info[] = $arr;
}

$json=array("status"=>1,"message"=>"done","result"=>$info);

}
else{
$json=array("status"=>0,"message"=>"No Record found!");
}
}
else{
$json=array("status"=>0,"message"=>"error");
}


OutPut:

{
    "status": 1,
    "message": "done",
    "result": [
        {
            "name": "manish",
            "email": "manish@gmail.com"
        },
        {
            "name": "Test",
            "email": "test@tes.com"
        }      
 ]
}

Thanks,
Manish

Thursday, November 26, 2015

PHP Login web service | PHP code for login | PHP Simple webservices



<?php
//take the values from client as json
$json = file_get_contents('php://input');
//open database connection
$con = mysql_connect('localhost','root','root') or die('Cannot connect to the DB');
mysql_select_db('mydb',$con);
//take json values into data variable
$data = json_decode($json);

//make a sql query to store data
$sql="SELECT * from `mydb`.`user` WHERE email = '".$data->{'email'}."' AND password = '".$data->{'password'}."'";
$qur=mysql_query($sql);

//check the database response it is true or false
 if($qur){
 if (mysql_num_rows($qur)>= 1 ) {
$json=array("status"=>1,"message"=>"done");
}
else{
$json=array("status"=>0,"message"=>"email or password not match!");
}
}
else{
$json=array("status"=>0,"message"=>"error");
}
//close the database connection
mysql_close($con);
//set header
header('Content-type: application/json');
//print the result as json object
echo json_encode($json);
?>

Sunday, October 18, 2015

Android Fragmnet Example code with full stack maintain | Fragment demo application | Simple Fragment example with action bar back button stack handle

Hello Friends,

Today I am going to share code for how to create android fragment and how to handle back stack. Have a look at below code or you can download full code from GIT server.



1)LoginActivity.java-

package com.androidhub4you.fragmentdemo;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
public class LoginActivity extends ActionBarActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        findViewById(R.id.button__activity_main).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent mIntent=new Intent(LoginActivity.this,MainActivity.class);
                startActivity(mIntent);
            }
        });
    }
}


2)activity_login.xml

<RelativeLayout 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">
    <TextView
        android:layout_width="wrap_content"
        android:text="Login Activity"
        android:textSize="26sp"
        android:textStyle="bold"
        android:layout_marginTop="20dp"
        android:layout_centerHorizontal="true"
        android:layout_height="wrap_content" />
    <TextView
        android:layout_above="@+id/button__activity_main"
        android:layout_width="match_parent"
        android:text="(From Login Activity we will open Main Activity and inside Main Activity we will add Main Fragment in container)"
        android:textSize="18sp"
        android:textStyle="bold"
        android:gravity="center"
        android:layout_marginBottom="50dp"
        android:layout_centerHorizontal="true"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/button__activity_main"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="15dp"
        android:text="Open Main Activity"
        android:textSize="20sp"
        android:layout_centerInParent="true"
        android:paddingTop="15dp" />
</RelativeLayout>

  
 3)MainActivity.java-
package com.androidhub4you.fragmentdemo; import android.app.FragmentTransaction; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; /** * Manish Srivastava */ public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.v("<<main activity>>", "<<screen>>"); //display home back button ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayShowHomeEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); //In side Create method of MainActivity we will add main fragment FragmentTransaction transaction = getFragmentManager().beginTransaction(); FragmentMain fragmentMain = new FragmentMain(); transaction.addToBackStack("fragmentMain"); transaction.replace(R.id.container, fragmentMain); transaction.commit(); } @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_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: handleBackStack(); break; case R.id.action_settings: //do nothing break; } return super.onOptionsItemSelected(item); } //handle back stack from hardware back button and top action bar home back button public boolean handleBackStack() { //on back press check the count of fragment in stack int count = getFragmentManager().getBackStackEntryCount(); Log.v("<<Fragment in stack>>",String.valueOf(count)); if (count == 1) { //if count is 0 then finish main activity finish(); }else { //else remove one fragment from the stack FragmentTransaction transaction = getFragmentManager().beginTransaction(); getFragmentManager().popBackStackImmediate(); transaction.commit(); } return true; } //set action bar title name public void setActionBarTitle(String title) { getSupportActionBar().setTitle(title); } //handle the hardware back press @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode==KeyEvent.KEYCODE_BACK){ handleBackStack(); return true; } return super.onKeyDown(keyCode, event); } }
4)activity_main.xml-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

5)FragmentMain.java-
package com.androidhub4you.fragmentdemo;

import android.app.FragmentTransaction;
import android.os.Bundle;
import android.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

/**
 * Manish Srivastava
 */
public class FragmentMain extends Fragment {


    public FragmentMain() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_main, container, false);
        final Button mButtonFragmentMain=(Button)view.findViewById(R.id.button__fragment_main);

        Log.v("<< main fragment>>","<<screen>>");

        mButtonFragmentMain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //call the child fragment
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                FragmentChild fragmentChild = new FragmentChild();
                transaction.addToBackStack("fragmentChild");
                transaction.replace(R.id.container, fragmentChild);
                transaction.commit();

            }
        });

        //call the main activity set tile method
        ((MainActivity)getActivity()).setActionBarTitle("Home Fragment");

        return view;
    }
}
6)fragment_main.xml-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:text="Main Fragment Screen"
        android:textSize="26sp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/button__fragment_main"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:paddingBottom="15dp"
        android:paddingTop="15dp"
        android:text="Open Child Fragment"
        android:textSize="20sp" />
</RelativeLayout>
7)FragmentChild.java-
package com.androidhub4you.fragmentdemo;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Manish Srivastava
 */
public class FragmentChild extends Fragment {


    public FragmentChild() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_child, container, false);

        //call the main activity set tile method
        ((MainActivity)getActivity()).setActionBarTitle("Child Fragment");


        return view;
    }
}

8)fragment_child.xml-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Child Fragment Screen"
        android:textSize="26sp"
        android:textStyle="bold" />
</RelativeLayout>

DOWNLOAD FULL CODE 
 
Thanks!
Manish