Deepshikha Puri, the young Indian Entrepreneur heading the mobile development trade from years to successive extent, has worked with numerous clients and many tremendous brands in this industry of mobile encompassing in India and overseas maintaining promising work relationships with each of them with an impression to manage it's whole thing.

Monday, January 28, 2019

Video Demo:



Basically a navigation drawer is used to show a main menu of application. The user can see the drawer when they swipe their finger from left to right or a vice verse. They can also open the drawer by tapping on hamburger icon. This tutorial will help you to install and understand the flow of react native navigation drawer. You can also download the source code from below.

create navigation drawer in react native navigation drawer in react native example


navigation drawer react native tutorial navigation drawer using react native

Step 1->
To create your project run this command:
sudo npm install -g react-native-cli
Step 2-> 
Now initialise your project name. Replace your project name with MovingScreen:
react-native init MovingScreen
Step 3->
Install Navigation library in your project:
npm install --save react-navigation
Step 4->
Also need to install the gesture library otherwise you will get an issue
npm install --save react-native-gesture-handler
Step 5->
link your gesture library in your project:
react-native link react-native-gesture-handler
Step 6->
For android you need to change your MainActivity with following functionations. Path: ProjectName->Android-> app->src->java->MainActivity.java

MainActivity.Java:
package com.navigationdrawer; import com.facebook.react.ReactActivity; import com.facebook.react.ReactActivityDelegate; import com.facebook.react.ReactRootView; import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView; public class MainActivity extends ReactActivity { /** * Returns the name of the main component registered from JavaScript. * This is used to schedule rendering of the component. */ @Override protected String getMainComponentName() { return "NavigationDrawer"; }
@Override protected ReactActivityDelegate createReactActivityDelegate() { return new ReactActivityDelegate(this, getMainComponentName()) { @Override protected ReactRootView createRootView() { return new RNGestureHandlerEnabledRootView(MainActivity.this); } }; }
}
Now you can start work on your React native project

App.js:
import React, {Component} from 'react'; import {createDrawerNavigator, createAppContainer} from 'react-navigation' import HomeScreen from './Screens/HomeScreen' import SettingScreen from './Screens/SettingScreen' import ProfileScreen from './Screens/ProfileScreen';
export default class App extends Component { render() { return ( <MyAppdrawer></MyAppdrawer> ); } }
const MyDrawerNavigator = createDrawerNavigator({ Home: { screen: HomeScreen, }, Settings: { screen: SettingScreen, }, Profile:{ screen: ProfileScreen } });
const MyAppdrawer = createAppContainer(MyDrawerNavigator);

HomeScreen.js:
import React, {Component} from 'react' import {View,Text, Image, StyleSheet,StatusBar, TouchableOpacity} from 'react-native'
export default class HomeScreen extends Component{
menuClick(){ this.props.navigation.openDrawer() }

render(){ return( <View style={styles.container}> <StatusBar backgroundColor='#FF7043'></StatusBar>
<View style={styles.topBar}> <View style={styles.leftHeader}> <TouchableOpacity style={styles.imgClick} onPress={this.menuClick.bind(this)}> <Image style={styles.imgMenu} source={require('../assets/menu.png')}></Image> </TouchableOpacity> </View>
<Text style={styles.txtBar}>Home Screen</Text> <View style={styles.rightHeader}></View></View> <View style={styles.contentBar}>
<Image style={styles.imgHome}source={require('../assets/mansion.png')}></Image> </View>
</View> ) } }
const styles = StyleSheet.create({ container:{ flex:1, flexDirection:'column', }, topBar:{ height:40, flexDirection:'row', alignItems:'center', justifyContent:'space-between', backgroundColor: '#FF5722', },
leftHeader:{ flex:1, marginLeft:10, justifyContent:'flex-start', },
rightHeader:{ flex:1, justifyContent:'flex-end', },
txtBar:{ color: '#ffffff', },
contentBar:{ flex:1, justifyContent:'center', alignItems:'center' },
imgMenu:{ width:20, height:20,
},
imgClick:{ width:40, height:40, justifyContent:'center' },
imgHome:{ width: 200, height: 200 }, })

ProfileScreen.js:
import React ,{Component} from 'react' import {View,StyleSheet,StatusBar,Text,Image,TouchableOpacity} from 'react-native'
export default class ProfileScreen extends Component{
menuClick(){ this.props.navigation.openDrawer() }
render(){ return( <View style={styles.container}> <StatusBar backgroundColor='#FF7043'></StatusBar>
<View style={styles.topBar}> <View style={styles.menuView}> <TouchableOpacity style={styles.imgClick} onPress={this.menuClick.bind(this)}> <Image style={styles.imgMenu} source={require('../assets/menu.png')} ></Image> </TouchableOpacity> </View> <Text style={styles.topTxt}>Profile Screen</Text> <View style={styles.menuViewright}></View></View>
<View style={styles.contentBar}> <Image source={require('../assets/boy.png')} style={styles.imgSetting}></Image> </View> </View> ) }
}
const styles = StyleSheet.create({ container:{ flex:1, }, imgClick:{ width:40, height:40, alignItems:'center', justifyContent:'center' },
topBar:{ height: 40, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', backgroundColor: '#FF5722', },
menuView:{ flex:1, flexDirection: 'row', justifyContent: 'flex-start',
}, menuViewright:{ flex:1, flexDirection: 'row', justifyContent: 'flex-end',
},
topTxt:{ color:'white', flex:1, },
contentBar:{ flex:1, justifyContent:'center', alignItems:'center' },
imgMenu:{ height:20, marginLeft:10, width:20, },
imgClick:{ width:40, height:40, justifyContent:'center' },
imgSetting:{ width: 200, height: 200 }, })

SettingScreen.js:
import React ,{Component} from 'react' import {View,Text,StyleSheet, StatusBar,Image,TouchableOpacity} from 'react-native'
export default class SettingScreen extends Component{
menuClick(){ this.props.navigation.openDrawer() }
render(){ return(
<View style={styles.container}> <StatusBar backgroundColor='#FF7043'></StatusBar> <View style={styles.topBar}> <View style={styles.headerLeft}> <TouchableOpacity style={styles.imgClick} onPress={this.menuClick.bind(this)}> <Image source={require('../assets/menu.png')} style={styles.imgMenu}></Image> </TouchableOpacity> </View>

<Text style={styles.topTxt}>Setting Screen</Text> <View style={styles.headerRight}></View> </View>
<View style={styles.contentBar}> <Image source={require('../assets/setting2.png')} style={styles.imgSetting}></Image> </View> </View> ) } }
const styles=StyleSheet.create({
container:{ flex:1 },
topBar:{ height: 40, backgroundColor:'#FF5722', flexDirection:'row', alignItems:'center', },
headerLeft:{ flex:1, marginLeft:10, justifyContent:'flex-start', },
headerRight:{ flex:1, justifyContent:'flex-end' },
topTxt:{ color: '#FFFFFF', },
contentBar:{ flex:1, justifyContent:'center', alignItems:'center' },
imgMenu:{ height:20, width:20, },
imgClick:{ width:40, height:40, justifyContent:'center' },
imgSetting:{ width: 200, height: 200 }, })

DOWNLOAD SOURCE CODE FROM HERE

Tuesday, January 15, 2019

Video Demo:

Basically a react native navigation is Javascript library to move from one screen to another screen. This tutorial will help you to install and understand the flow of React navigation. You can download the source code from below.

navigation between screens react native navigation in react native

react native navigation react native navigation example

Step 1->
To create your project run this command:
sudo npm install -g react-native-cli
Step 2-> 
Now initialise your project name. Replace your project name with MovingScreen:
react-native init MovingScreen
Step 3->
Install Navigation library in your project:
npm install --save react-navigation
Step 4->
Also need to install the gesture library otherwise you will get an issue
npm install --save react-native-gesture-handler
Step 5->
link your gesture library in your project:
react-native link react-native-gesture-handler
Step 6->
For android you need to change your MainActivity with following functionations.
Path: ProjectName->Android-> app->src->java->MainActivity.java

MainActivity.Java:
package com.movingscreens; import com.facebook.react.ReactActivity; import com.facebook.react.ReactActivityDelegate; import com.facebook.react.ReactRootView; import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView; public class MainActivity extends ReactActivity { /** * Returns the name of the main component registered from JavaScript. * This is used to schedule rendering of the component. */ @Override protected String getMainComponentName() { return "MovingScreens"; }
@Override protected ReactActivityDelegate createReactActivityDelegate() { return new ReactActivityDelegate(this, getMainComponentName()) { @Override protected ReactRootView createRootView() { return new RNGestureHandlerEnabledRootView(MainActivity.this); } }; } }
Now you can start work on your React native project

App.js:
import React, {Component} from 'react'; import {createStackNavigator,createAppContainer} from 'react-navigation' import HomeScreen from './Screens/HomeScreen'; import ProfileScreen from './Screens/ProfileScreen'; import ContactScreen from './Screens/ContactScreen'; import MainScreen from './Screens/MainScreen'
export default class App extends Component { render() { return <AppNavigationContainer/> } } const AppNavigator = createStackNavigator({ Main:MainScreen, Home: HomeScreen, Profile: ProfileScreen, Contact:ContactScreen }, { initialRouteName: 'Main', navigationOptions: { headerTitleStyle: { fontWeight: "bold", color: "red", }, headerTintColor: "red" } }) const AppNavigationContainer = createAppContainer(AppNavigator);
Now create a new folder in your project with the name of Screens and add the following files in this folder

MainScreen.js:
import React ,{Component} from 'react' import {View, Text,StyleSheet,Button, StatusBar} from 'react-native' export default class MainScreen extends Component{ static navigationOptions = { headerTintColor: 'white', title: 'Moving between screens', headerStyle: { backgroundColor: '#FF5722' }, headerTitleStyle: { fontWeight: '300', color: 'white', fontFamily: 'Nunito-Regular', justifyContent: 'center', alignItems: 'center', fontSize: 16}, } homeClick(){ this.props.navigation.navigate('Home') } contactClick(){ this.props.navigation.navigate('Contact') } profileClick(){ this.props.navigation.navigate('Profile') } render(){ return( <View style={style.Container}> <StatusBar backgroundColor='#FF7043'></StatusBar> <View style={style.btnContainer}> <Button title='Home' color='#FF5722' onPress={this.homeClick.bind(this)}></Button> </View > <View style={style.btnContainer}> <Button title='Contact' color='#FF5722' onPress={this.contactClick.bind(this)}> </Button> </View> <View style={style.btnContainer}> <Button title='Profile' color='#FF5722' onPress={this.profileClick.bind(this)}></Button> </View> </View> ) } } const style = StyleSheet.create({ Container:{ flex:1, justifyContent: 'center', alignItems: 'center', width: '100%' }, btnContainer:{ width:'70%', height:50, position:'relative', justifyContent: 'center', alignContent:'center', } });

HomeScreen.js:
import React , {Component} from 'react' import {View, Text,StyleSheet} from 'react-native'
export default class HomeScreen extends Component{ static navigationOptions = { headerTintColor: 'white', title: 'Moving between screens', headerStyle: { backgroundColor: '#FF5722' }, headerTitleStyle: { fontWeight: '300', color: 'white', fontFamily: 'Nunito-Regular', justifyContent: 'center', alignItems: 'center', fontSize: 16}, } render(){ return( <View style={styles.Container}> <Text style={styles.txtStyle}>Home Screen</Text> </View> ) } }
const styles= StyleSheet.create({ Container:{ flex:1, justifyContent:'center', alignItems:'center' }, txtStyle:{ alignItems:'center', fontWeight: 'bold', fontFamily: 'Nunito-Regular', fontSize: 25, }, })

ContactScreen.js:
import React ,{Component} from 'react' import {View , Text, StyleSheet} from 'react-native' export default class ContactScreen extends Component{ static navigationOptions = { headerTintColor: 'white', title: 'Moving between screens', headerStyle: { backgroundColor: '#FF5722' }, headerTitleStyle: { fontWeight: '300', color: 'white', fontFamily: 'Nunito-Regular', justifyContent: 'center', alignItems: 'center', fontSize: 16}, } render(){ return( <View style={styles.Container}> <Text style={styles.txtStyle}>Contact us</Text> </View> ) } } const styles = StyleSheet.create({ Container:{ justifyContent:'center', alignItems:'center', flex:1, }, txtStyle:{ alignItems:'center', fontWeight: 'bold', fontFamily: 'Nunito-Regular', fontSize: 25, }, })

ProfileScreen.js:
import React ,{Component} from 'react' import {View, Text,StyleSheet} from 'react-native' export default class ProfileScreen extends Component{ static navigationOptions = { headerTintColor: 'white', title: 'Moving between screens', headerStyle: { backgroundColor: '#FF5722' }, headerTitleStyle: { fontWeight: '300', color: 'white', fontFamily: 'Nunito-Regular', justifyContent: 'center', alignItems: 'center', fontSize: 16}, } render(){ return( <View style={styles.Container}> <Text style={styles.txtStyle}>Profile Screen</Text> </View> ) } } const styles= StyleSheet.create({ Container:{ flex:1, justifyContent:'center', alignItems:'center' }, txtStyle:{ alignItems:'center', fontWeight: 'bold', fontFamily: 'Nunito-Regular', fontSize: 25, }, })

DOWNLOAD SOURCE CODE FROM HERE

Saturday, May 12, 2018

Video Demo:


JSON means JavaScript Object Notation. Json parsing is used when our app wants to exchange data with our server. There are alots of tutorial in Json paring in android java But there are limited tutorial of json parsing in android using kotlin. So here I am showing tutorial of Jsonparsing in android Kotlin. Download source code from here


json parsing android kotlin

Add this dependency in your gradle file:

compile 'com.squareup.okhttp3:okhttp:3.8.1'

activity_main.xml:


    



MainActivity.kt:


package com.deepshikha.kotlin.jsonparsing

import android.app.ProgressDialog
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.ListView
import okhttp3.*
import org.json.JSONArray
import org.json.JSONObject
import java.io.IOException
import kotlin.collections.ArrayList

class MainActivity : AppCompatActivity() {

    lateinit var dialog:ProgressDialog
    lateinit var lv_details: ListView

    var al_details:ArrayList = ArrayList();
    val client = OkHttpClient()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        dialog= ProgressDialog.show(this@MainActivity,"Alert","Loading")
        lv_details = findViewById(R.id.lv_details) as ListView
        run("https://api.androidhive.info/contacts/")


    }

    fun run(url: String) {
        dialog.show()
        val request = Request.Builder()
                .url(url)
                .build()

        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                dialog.dismiss()

            }

            override fun onResponse(call: Call, response: Response) {
                var str_response = response.body()!!.string()
                val json_contact:JSONObject = JSONObject(str_response)

                var jsonarray_contacts:JSONArray= json_contact.getJSONArray("contacts")

                var i:Int = 0
                var size:Int = jsonarray_contacts.length()

                al_details= ArrayList();

                for (i in 0.. size-1) {
                    var json_objectdetail:JSONObject=jsonarray_contacts.getJSONObject(i)


                    var model:Model= Model();
                    model.id=json_objectdetail.getString("id")
                    model.name=json_objectdetail.getString("name")
                    model.email=json_objectdetail.getString("email")
                    model.address=json_objectdetail.getString("address")
                    model.gender=json_objectdetail.getString("gender")

                    al_details.add(model)


                }

                runOnUiThread {
                    //stuff that updates ui
                    val obj_adapter : CustomAdapter
                    obj_adapter = CustomAdapter(applicationContext,al_details)
                    lv_details.adapter=obj_adapter
                }

                dialog.dismiss()

            }

        })

    }


}

adapter_layout.xml:


    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/ll_main"
    android:background="#e4e2e2"
    android:padding="5dp"
    android:orientation="vertical">

            android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv_name"
        android:textSize="15dp"
        android:layout_margin="5dp"
        android:textColor="#000000"/>

            android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv_email"
        android:layout_margin="5dp"
        android:textSize="15dp"
        android:textColor="#000000"/>

            android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv_address"
        android:layout_margin="5dp"
        android:textSize="15dp"
        android:textColor="#000000"/>




CustomAdapter.kt:

package com.deepshikha.kotlin.jsonparsing

import android.content.Context
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView

/**
 * Created by deepshikha on 1/11/17.
 */

class CustomAdapter(context: Context,al_details:ArrayList) : BaseAdapter(){

    private val mInflator: LayoutInflater
    private val al_details:ArrayList

    init {
        this.mInflator = LayoutInflater.from(context)
        this.al_details=al_details
    }

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

    override fun getItem(position: Int): Any {
        return al_details.get(position)
    }

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

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? {
        val view: View?
        val vh: ListRowHolder
        if (convertView == null) {
            view = this.mInflator.inflate(R.layout.adapter_layout, parent, false)
            vh = ListRowHolder(view)
            view.tag = vh
        } else {
            view = convertView
            vh = view.tag as ListRowHolder
        }

        vh.tv_name.text = al_details.get(position).name
        vh.tv_email.text = al_details.get(position).email
        vh.tv_address.text = al_details.get(position).address
        if (position%2==0) {
            vh.ll_main.setBackgroundColor(Color.parseColor("#e4e2e2"))
        }else{
            vh.ll_main.setBackgroundColor(Color.parseColor("#FFFFFF"))

        }
        return view
    }
}

private class ListRowHolder(row: View?) {
    public val tv_name: TextView
    public val tv_email: TextView
    public val tv_address: TextView
    public val ll_main: LinearLayout

    init {
        this.tv_name = row?.findViewById(R.id.tv_name) as TextView
        this.tv_email = row?.findViewById(R.id.tv_email) as TextView
        this.tv_address = row?.findViewById(R.id.tv_address) as TextView
        this.ll_main = row?.findViewById(R.id.ll_main) as LinearLayout
    }


} 

Model.kt:


package com.deepshikha.kotlin.jsonparsing

/**
 * Created by deepshikha on 31/10/17.
 */
public class Model{
    lateinit var id:String
    lateinit var name:String
    lateinit var email:String
    lateinit var address:String
    lateinit var gender:String

    constructor(id: String,name:String,email:String,address:String,gender:String) {
        this.id = id
        this.name = name
        this.email = email
        this.address = address
        this.gender = gender
    }

    constructor()


}

Saturday, April 28, 2018

change theme programmatically android

Themes and Styles on Android allow us to separate the details of our app design from the UI structure and behavior, Similar to Stylesheets in web design. Download source code from here

activity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:id="@+id/rl_header"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/colorPrimary"></RelativeLayout>

    <Button
        android:id="@+id/btn_red"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        android:layout_marginRight="10dp"
        android:text="Red" />

    <Button
        android:id="@+id/btn_yellow"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        android:layout_marginRight="10dp"
        android:text="Yellow" />


    <Button
        android:id="@+id/btn_green"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        android:layout_marginRight="10dp"
        android:text="Green" />

    <Button
        android:id="@+id/btn_purple"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        android:layout_marginRight="10dp"
        android:text="Purple" />

</LinearLayout>


MainActivity.kt:


package changetheme.deepshikha.com.changetheme

import android.graphics.Color
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity(), View.OnClickListener {

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

    private fun init() {

    }

    private fun listener() {
        btn_red.setOnClickListener(this)
        btn_yellow.setOnClickListener(this)
        btn_green.setOnClickListener(this)
        btn_purple.setOnClickListener(this)
    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btn_red -> {
                fn_changethemecolor(resources.getColor(R.color.theme_red), resources.getColor(R.color.red))
            }

            R.id.btn_yellow -> {
                fn_changethemecolor(resources.getColor(R.color.theme_yellow), resources.getColor(R.color.yellow))
            }

            R.id.btn_green -> {
                fn_changethemecolor(resources.getColor(R.color.theme_green), resources.getColor(R.color.green))
            }

            R.id.btn_purple -> {
                fn_changethemecolor(resources.getColor(R.color.theme_purple), resources.getColor(R.color.purple))
            }
        }
    }


    /**
     * Method for change theme color
     */
    fun fn_changethemecolor(color: Int, header_color: Int) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            val window = window
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            window.statusBarColor = color

        }
        rl_header.setBackgroundColor(header_color)

    }
}


Saturday, April 21, 2018

create custom toast class android

A toast is used to display simple feedback about an operation in popup and automatically fade out after timeout. In this tutorial I am create a custom toast by using custom layout. Download source code from here:

activity_main:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp">


    <Button
        android:id="@+id/btn_refresh"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="Refresh Toast" />

    <Button
        android:id="@+id/btn_error2"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginTop="10dp"
        android:text="Info" />

    <Button
        android:id="@+id/btn_network"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginTop="10dp"
        android:text="Network Toast" />

    <Button
        android:id="@+id/btn_error"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginTop="10dp"
        android:text="Error Toast" />

</LinearLayout>

custom_toast.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/custom_toast_container"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="8dp"
    android:background="#DAAA">
    <ImageView android:src="@drawable/ic_launcher_background"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/iv_image"
        android:layout_marginRight="8dp"
        />
    <TextView android:id="@+id/tv_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#FFF"
        />
</LinearLayout>


MainActivity.kt:
package com.deepshikha.customtoast

import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.custom_toast.view.*

class MainActivity : AppCompatActivity(), View.OnClickListener {

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

        listener()
    }

    private fun listener() {
        btn_refresh.setOnClickListener(this)
        btn_error2.setOnClickListener(this)
        btn_network.setOnClickListener(this)
        btn_error.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btn_error2 -> {
                var toast: Toast = Toast(this)
                toast.createToast(this, "Dummy data is benign information", Gravity.BOTTOM, Toast.LENGTH_SHORT, "#eab04c", R.drawable.ic_info_black_24dp)
            }

            R.id.btn_refresh -> {

                var toast: Toast = Toast(this)
                toast.createToast(this, "Data has been Refreshed", Gravity.BOTTOM, Toast.LENGTH_SHORT, "#2ba622", R.drawable.ic_autorenew_black_24dp)

            }

            R.id.btn_network -> {

                var toast: Toast = Toast(this)
                toast.createToast(this, "Check your Internet connection", Gravity.BOTTOM, Toast.LENGTH_SHORT, "#7c5ffa", R.drawable.ic_network_check_black_24dp)

            }

            R.id.btn_error -> {
                var toast: Toast = Toast(this)
                toast.createToast(this, "Error: Server not found", Gravity.BOTTOM, Toast.LENGTH_SHORT, "#ec1e1e", R.drawable.ic_error_outline_black_24dp)
            }
        }
    }

    fun Toast.createToast(context: Context, message: String, gravity: Int, duration: Int, backgroucolor: String, imagebackgroud: Int) {
        val inflater: LayoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        /*first parameter is the layout you made
        second parameter is the root view in that xml
         */
        val layout = inflater.inflate(R.layout.custom_toast, (context as Activity).findViewById(R.id.custom_toast_container))

        layout.findViewById(R.id.tv_message).text = message
        layout.setBackgroundColor(Color.parseColor(backgroucolor))
        layout.findViewById(R.id.iv_image).iv_image.setImageResource(imagebackgroud)
        setGravity(gravity, 0, 100)
        setDuration(Toast.LENGTH_LONG);

        setView(layout);
        show()
    }

}

Saturday, March 17, 2018

android parcelable tutorial

In Android Parcelable interface is used to transfer the Arraylist or Object from one Activity to another activity. Parcelable is faster then serialization. Download the source code from below.

activity_main.xml:
<?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="wrap_content"
    android:layout_height="wrap_content"
    tools:context="com.deepshikha.parcelable.MainActivity">

    <ListView
        android:id="@+id/lv_category"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout_editor_absoluteX="8dp" />
</android.support.constraint.ConstraintLayout>


adapter_category.xml:



<android.support.constraint.ConstraintLayout 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"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <ImageView
        android:id="@+id/iv_image"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.029"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.02"
        tools:ignore="VectorDrawableCompat" />

    <TextView
        android:id="@+id/tv_name"
        android:layout_width="200dp"
        android:layout_height="30dp"
        android:layout_marginEnd="68dp"
        android:layout_marginLeft="10dp"
        android:ellipsize="end"
        android:maxLines="1"
        android:paddingLeft="20dp"
        android:paddingRight="10dp"
        android:singleLine="true"
        android:text="TextView"
        android:textColor="#000000"
        android:textSize="15sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintLeft_toRightOf="@+id/iv_image"
        app:layout_constraintTop_toTopOf="@+id/iv_image" />

    <TextView
        android:id="@+id/tv_des"
        android:layout_width="0dp"
        android:layout_height="60dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:ellipsize="end"
        android:maxLines="2"
        android:text="TextView"
        android:textColor="#000000"
        android:textSize="12sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.36"
        app:layout_constraintLeft_toRightOf="@+id/iv_image"
        app:layout_constraintTop_toBottomOf="@+id/tv_name" />
</android.support.constraint.ConstraintLayout>
MainActivity.java:
package com.deepshikha.parcelable;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.deepshikha.parcelable.Model.Category;

import java.lang.reflect.Array;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ArrayList al_category = new ArrayList<>();
    ListView lv_category;
    Button btn_next;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    private void init() {
        lv_category = (ListView) findViewById(R.id.lv_category);

        al_category.add(new Category("C", "C is a general-purpose, imperative computer programming language, supporting structured programming, lexical variable scope and recursion, while a static type system prevents many unintended operations.", R.drawable.ic_clogo));
        al_category.add(new Category("Css", "Cascading Style Sheets (CSS) is a style sheet language used for describing the presentation of a document written in a markup language", R.drawable.ic_css));
        al_category.add(new Category("Java", "Java is a general-purpose computer-programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible.", R.drawable.ic_java));
        al_category.add(new Category("PHP", "PHP is a server-side scripting language designed for web development but also used as a general-purpose programming language.", R.drawable.ic_php));
        al_category.add(new Category("JavaScript", "JavaScript, often abbreviated as JS, is a high-level, interpreted programming language. It is a language which is also characterized as dynamic, weakly typed, prototype-based and multi-paradigm.", R.drawable.ic_javascript));


        CategoryAdapter categoryAdapter = new CategoryAdapter(getApplicationContext(), al_category);
        lv_category.setAdapter(categoryAdapter);

        lv_category.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id) {

                Intent intent = new Intent(getApplicationContext(), CategoryDetails.class);
//                intent.putParcelableArrayListExtra("value",al_category);
                intent.putExtra("value", al_category.get(position));
                startActivity(intent);

            }
        });
    }

    public class CategoryAdapter extends ArrayAdapter {

        public CategoryAdapter(Context context, ArrayList users) {
            super(context, 0, users);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // Get the data item for this position
            Category category = getItem(position);
            // Check if an existing view is being reused, otherwise inflate the view
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.adapter_category, parent, false);
            }
            // Lookup view for data population
            TextView tvName = (TextView) convertView.findViewById(R.id.tv_name);
            TextView tv_des = (TextView) convertView.findViewById(R.id.tv_des);
            ImageView iv_image = (ImageView)convertView.findViewById(R.id.iv_image);

            // Populate the data into the template view using the data object
            tvName.setText(category.getStr_name());
            iv_image.setImageResource(category.getInt_image());
            tv_des.setText(category.getStr_des());

            // Return the completed view to render on screen
            return convertView;
        }
    }
}

Category.java:
package com.deepshikha.parcelable.Model;

import android.os.Parcel;
import android.os.Parcelable;

/**
 * Created by deepshikha on 22/2/18.
 */

public class Category implements Parcelable {
    String str_name, str_des;
    int int_image;

    public Category(String str_name, String str_des, int int_image) {
        this.str_name = str_name;
        this.str_des = str_des;
        this.int_image = int_image;
    }

    public String getStr_name() {
        return str_name;
    }

    public void setStr_name(String str_name) {
        this.str_name = str_name;
    }

    public String getStr_des() {
        return str_des;
    }

    public void setStr_des(String str_des) {
        this.str_des = str_des;
    }

    public int getInt_image() {
        return int_image;
    }

    public void setInt_image(int int_image) {
        this.int_image = int_image;
    }


    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(this.str_name);
        dest.writeString(this.str_des);
        dest.writeInt(this.int_image);
    }

    public Category() {
    }

    protected Category(Parcel in) {
        this.str_name = in.readString();
        this.str_des = in.readString();
        this.int_image = in.readInt();
    }

    public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
        @Override
        public Category createFromParcel(Parcel source) {
            return new Category(source);
        }

        @Override
        public Category[] newArray(int size) {
            return new Category[size];
        }
    };
}

activity_category_details.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.deepshikha.parcelable.CategoryDetails">


    <ImageView
        android:id="@+id/iv_image"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:src="@drawable/ic_clogo"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.084" />

    <TextView
        android:id="@+id/tv_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="TextView"
        android:textColor="#000000"
        android:textSize="20sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.028"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/iv_image"
        app:layout_constraintVertical_bias="0.004" />

    <TextView
        android:id="@+id/tv_des"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:text="TextView"
        android:textColor="#000000"
        android:textSize="12sp"
        app:layout_constraintHorizontal_bias="0.108"
        app:layout_constraintLeft_toLeftOf="@+id/tv_name"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tv_name" />
</android.support.constraint.ConstraintLayout>

CategoryDetails.java:
package com.deepshikha.parcelable;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.deepshikha.parcelable.Model.Category;

import java.lang.reflect.Array;
import java.util.ArrayList;

public class CategoryDetails extends AppCompatActivity {

    Category category;
    ImageView iv_image;
    TextView tv_name, tv_des;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_category_details);
        category = getIntent().getParcelableExtra("value");

        init();

    }

    private void init() {
        iv_image = (ImageView) findViewById(R.id.iv_image);
        tv_des = (TextView) findViewById(R.id.tv_des);
        tv_name = (TextView) findViewById(R.id.tv_name);

        tv_name.setText(category.getStr_name());
        tv_des.setText(category.getStr_des());
        iv_image.setImageResource(category.getInt_image());
    }
}


DOWNLOAD SOURCE CODE FROM HERE.


Saturday, March 3, 2018

Video Demo:




TabLayout provides a horizontal layout to display tabs. We can show the number of layout in single screen. In this tutorial, I am using the two fragments to shows the tab data. DOWNLOAD SOURCE CODE FROM BELOW:

tablayout in android kotlin
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical">

    <android.support.design.widget.TabLayout
        android:id="@+id/tb_fragments"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#17d236"
        app:tabIndicatorColor="#000000"
        app:tabSelectedTextColor="#ffffff"
        app:tabTextColor="#000000">

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

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

    </FrameLayout>

</LinearLayout>
MainActivity.kt:
package com.deepshikha.tablayoutkotlin

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.design.widget.TabLayout
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() , TabLayout.OnTabSelectedListener {
    lateinit var homefragment:HomeFragment
    lateinit var contactfragment:ContactFragment

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

    private fun init() {
        supportActionBar!!.hide()

        homefragment= HomeFragment()
        contactfragment= ContactFragment()

        val firstTab = tb_fragments.newTab()
        firstTab.setText("Home")
        firstTab.setIcon(R.drawable.home)
        tb_fragments.addTab(firstTab)

        val secondTab = tb_fragments.newTab()
        secondTab.setText("Email")
        secondTab.setIcon(R.drawable.email)
        tb_fragments.addTab(secondTab)

        tb_fragments.setOnTabSelectedListener(this)

        supportFragmentManager
                .beginTransaction()
                .add(R.id.fl_container,homefragment)
                .commit()
    }

    override fun onTabReselected(tab: TabLayout.Tab?) {
    }

    override fun onTabUnselected(tab: TabLayout.Tab?) {

    }

    override fun onTabSelected(tab: TabLayout.Tab?) {
        when(tab!!.position){
            0-> {
                supportFragmentManager
                        .beginTransaction()
                        .replace(R.id.fl_container, homefragment)
                        .commit()
            }

            1-> {
                supportFragmentManager
                        .beginTransaction()
                        .replace(R.id.fl_container, contactfragment)
                        .commit()
            }

        }
    }

}

fragment_home.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    
    <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/webview"></WebView>

</LinearLayout>


HomeFragment.kt:
package com.deepshikha.tablayoutkotlin

import android.app.ProgressDialog
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import android.webkit.WebViewClient

/**
 * Created by deepshikha on 2/2/18.
 */
public class HomeFragment : Fragment() {
    lateinit var view12: View
    var mywebview: WebView? = null
    lateinit var progressdialog: ProgressDialog
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

        view12 = inflater!!.inflate(R.layout.fragment_home, container, false)
        init()
        return view12
    }

    private fun init() {

        progressdialog = ProgressDialog.show(activity, "Please Wait", "Loading");
        mywebview = view12.findViewById(R.id.webview)
        mywebview!!.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                view?.loadUrl(url)
                return true
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                progressdialog.dismiss()
            }
        }
        mywebview!!.loadUrl("http://deepshikhapuri.blogspot.in/")


//        webview = view12.findViewById(R.id.webview) as WebView
//        val webSettings = webview.settings
//        webSettings.javaScriptEnabled = true
//
//        webview.loadUrl("http://deepshikhapuri.blogspot.in/")
//        webview.setweb

    }
}
fragment_contact.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    android:orientation="vertical">

    <TextView
        android:textColor="#000000"
        android:text="deepshikhapuri.here@gmail.com"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"/>

</RelativeLayout>

ContactFragment.kt:
package com.deepshikha.tablayoutkotlin

import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

/**
 * Created by deepshikha on 2/2/18.
 */
public class ContactFragment:Fragment(){
    lateinit var view12: View

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
           view12 = inflater!!.inflate(R.layout.fragment_contact, container, false)
        return view12
    }
}

DOWNLOAD SOURCE CODE FROM HERE