Friday, 28 June 2019

Android[Kotlin] Login and Register example with PHP MySQL

Android (Kotlin) Login andRegister example with PHP MySQL 


Output :


Create Table:



PHP Files

config.php

<?php
$host="localhost";
$user="root";
$password="";
$db = "kotlin_example";
 
$con = mysqli_connect($host,$user,$password,$db);
 
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }else{  //echo "Connect"; 
  
   
   }
 
?>

login.php

<?php
 
if($_SERVER['REQUEST_METHOD']=='POST'){
include_once("config.php");
$postdata = file_get_contents("php://input");
 if (isset($postdata)) {
  $request1 = json_decode($postdata);
  $email = $request1->email;
  $password = $request1->password;
   
  if( $email == '' || $password == '' ){
   echo json_encode(array( "status" => "false","message" => "Parameter missing!") );
   }else{
    $query= "SELECT * FROM user WHERE email='$email' AND password='$password'";
          $result= mysqli_query($con, $query);
    
          if(mysqli_num_rows($result) > 0){  
           $query= "SELECT * FROM user WHERE email='$email' AND password='$password'";
                       $result= mysqli_query($con, $query);
                $emparray = array();
                       if(mysqli_num_rows($result) > 0){  
                       while ($row = mysqli_fetch_assoc($result)) {
                                      $emparray[] = $row;
                                    }
                       }
             echo json_encode(array( "status" => "true","message" => "Login successfully!", "data" => $emparray) );
          }else{ 
           echo json_encode(array( "status" => "false","message" => "Invalid email or password!") );
          }
           mysqli_close($con);
   }
 }
} else{
 echo json_encode(array( "status" => "false","message" => "Error occured, please try again!") );
}
?>

register.php

<?php
 
if($_SERVER['REQUEST_METHOD']=='POST'){
       include_once("config.php");
    
 $postdata = file_get_contents("php://input");
 if (isset($postdata)) {
  $request1 = json_decode($postdata);
  $email = $request1->email;
  $username = $request1->username;
  $password = $request1->password;
   
   if($email == '' || $username == '' || $password == ''){
          echo json_encode(array( "status" => "false","message" => "Parameter missing!") );
   }else{
     
          $query= "SELECT * FROM user WHERE username='$username'";
          $result= mysqli_query($con, $query);
    
          if(mysqli_num_rows($result) > 0){  
             echo json_encode(array( "status" => "false","message" => "Username already exist!") );
          }else{ 
      $query = "INSERT INTO user (email,username,password) VALUES ('$email','$username','$password')";
     if(mysqli_query($con,$query)){
        
         $query= "SELECT * FROM user WHERE username='$username'";
                       $result= mysqli_query($con, $query);
                $emparray = array();
                       if(mysqli_num_rows($result) > 0){  
                       while ($row = mysqli_fetch_assoc($result)) {
                                      $emparray[] = $row;
                                    }
                       }
        echo json_encode(array( "status" => "true","message" => "Successfully registered!" , "data" => $emparray) );
      }else{
       echo json_encode(array( "status" => "false","message" => "Error occured, please try again!") );
     }
      }
              mysqli_close($con);
   }
 }
} else{
 echo json_encode(array( "status" => "false","message" => "Error occured, please try again!") );
}
 
 ?>

get_user_detail.php

<?php
 
$response = array();
include_once("config.php");
 
if (isset($_GET["id"])) {
    $id = $_GET['id'];
    $query= "SELECT * FROM user WHERE id='$id'";
 
 $result= mysqli_query($con, $query);
 $emparray = array();
 if(mysqli_num_rows($result) > 0){  
  while ($row = mysqli_fetch_assoc($result)) {
   $emparray[] = $row;
         echo json_encode(array( "status" => "true", "data" => $emparray) );
  }
 }
 else{ 
  echo json_encode(array( "status" => "false","message" => "No User Found!") );
 }
  
}else {
 echo json_encode(array( "status" => "false","message" => "Required field(s) is missing!") );
}
?>

build.gradle

implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support:cardview-v7:28.0.0'

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.loginregistration">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application            
       android:allowBackup="true"            
       android:icon="@mipmap/ic_launcher"            
       android:label="@string/app_name"            
       android:roundIcon="@mipmap/ic_launcher_round"            
       android:supportsRtl="true"            
       android:theme="@style/AppTheme">
        <activity android:name=".HomeActivity">
        </activity>
        <activity android:name=".RegisterActivity">
        </activity>
        <activity android:name=".LoginActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

User.kt

package com.loginregistration

class User {

    var id:String? = null    
    var username:String? = null    
    var email:String? = null


    override fun toString(): String {
        return "User(id=$id, username=$username, email=$email)"    }

}

HttpTask.kt

package com.loginregistration

import android.os.AsyncTask
import android.util.Log
import android.widget.Toast
import org.json.JSONArray
import org.json.JSONObject
import java.io.*
import java.net.HttpURLConnection
import java.net.URL

class HttpTask(callback: (String?) -> Unit) : AsyncTask<String, Unit, String>()  {

    var callback = callback

    override fun doInBackground(vararg params: String): String? {
        val url = URL(params[1])
        val httpClient = url.openConnection() as HttpURLConnection
        httpClient.setReadTimeout(10*1000)
        httpClient.setConnectTimeout(10*1000)
        httpClient.requestMethod = params[0]

        if (params[0] == "POST") {
            httpClient.instanceFollowRedirects = false            
            httpClient.doOutput = true            
            httpClient.doInput = true            
            httpClient.useCaches = false            
            httpClient.setRequestProperty("Content-Type", "application/json; charset=utf-8")
        }
        try {
            if (params[0] == "POST") {
                httpClient.connect()
                val os = httpClient.getOutputStream()
                val writer = BufferedWriter(OutputStreamWriter(os, "UTF-8"))
                writer.write(params[2])
                writer.flush()
                writer.close()
                os.close()
            }
            if (httpClient.responseCode == HttpURLConnection.HTTP_OK) {
                val stream = BufferedInputStream(httpClient.inputStream)
                val data: String = readStream(inputStream = stream)
                return data
            } else {
                println("ERROR ${httpClient.responseCode}")
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            httpClient.disconnect()
        }

        return null    }

    fun readStream(inputStream: BufferedInputStream): String {
        val bufferedReader = BufferedReader(InputStreamReader(inputStream))
        val stringBuilder = StringBuilder()
        bufferedReader.forEachLine { stringBuilder.append(it) }        
        return stringBuilder.toString()
    }

    override fun onPostExecute(result: String?) {
        super.onPostExecute(result)
        callback(result)
    }
}


activity_login.xml

<?xml version="1.0" encoding="utf-8"?><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:background="@color/colorBackground"        
      android:paddingBottom="20dp"        
      android:paddingLeft="20dp"        
      android:paddingRight="20dp"        
      android:paddingTop="20dp"        
      tools:context=".LoginActivity">

    <android.support.v4.widget.NestedScrollView            
       android:layout_width="match_parent"            
       android:layout_height="match_parent"            
       android:id="@+id/nestedScrollView">

        <android.support.v7.widget.LinearLayoutCompat                
          android:layout_width="match_parent"                
          android:layout_height="match_parent"                
          android:orientation="vertical">

            <android.support.v7.widget.AppCompatTextView                    
              android:layout_width="wrap_content"                    
              android:layout_height="wrap_content"                    
              android:layout_gravity="center_horizontal"                    
              android:layout_marginTop="40dp"                    
              android:text="JR"                    
              android:textSize="100sp"/>

            <android.support.design.widget.TextInputLayout                    
              android:id="@+id/textInputLayoutEmail"                    
              android:layout_width="match_parent"                    
              android:layout_height="wrap_content"                    
              android:layout_marginTop="40dp">

                <android.support.design.widget.TextInputEditText                        android:id="@+id/textInputEditTextEmail"                        android:layout_width="match_parent"                        android:layout_height="wrap_content"                        android:hint="@string/hint_email"                        android:inputType="text"                        android:maxLines="1"                        android:textColor="@android:color/white"/>
            </android.support.design.widget.TextInputLayout>

            <android.support.design.widget.TextInputLayout                    android:id="@+id/textInputLayoutPassword"                    android:layout_width="match_parent"                    android:layout_height="wrap_content"                    android:layout_marginTop="20dp">

                <android.support.design.widget.TextInputEditText                        android:id="@+id/textInputEditTextPassword"                        android:layout_width="match_parent"                        android:layout_height="wrap_content"                        android:hint="@string/hint_password"                        android:inputType="textPassword"                        android:maxLines="1"                        android:textColor="@android:color/white"/>
            </android.support.design.widget.TextInputLayout>

            <android.support.v7.widget.AppCompatButton                    android:id="@+id/appCompatButtonLogin"                    android:layout_width="match_parent"                    android:layout_height="wrap_content"                    android:layout_marginTop="40dp"                    android:background="@color/colorTextHint"                    android:text="@string/text_login"/>

            <android.support.v7.widget.AppCompatTextView                    android:id="@+id/textViewLinkRegister"                    android:layout_width="fill_parent"                    android:layout_height="wrap_content"                    android:layout_marginTop="30dp"                    android:gravity="center"                    android:text="@string/text_not_member"                    android:textSize="16dp"/>
        </android.support.v7.widget.LinearLayoutCompat>

    </android.support.v4.widget.NestedScrollView>

    <ProgressBar            android:id="@+id/progressBar"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:textColor="@android:color/white"            android:textSize="100sp"            android:layout_centerInParent="true"/>

</RelativeLayout>

LoginActivity.kt

package com.loginregistration

import android.content.Intent
import android.os.AsyncTask
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.design.widget.TextInputEditText
import android.support.design.widget.TextInputLayout
import android.support.v4.widget.NestedScrollView
import android.support.v7.widget.AppCompatButton
import android.support.v7.widget.AppCompatTextView
import android.util.Log
import android.view.View
import android.widget.ProgressBar
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_register.*
import org.json.JSONArray
import org.json.JSONObject
import java.io.*
import java.net.HttpURLConnection
import java.net.URL

class LoginActivity : AppCompatActivity(), View.OnClickListener {

    private val activity = this@LoginActivity
    private lateinit var nestedScrollView: NestedScrollView

    private lateinit var textInputLayoutEmail: TextInputLayout
    private lateinit var textInputLayoutPassword: TextInputLayout

    private lateinit var textInputEditTextEmail: TextInputEditText
    private lateinit var textInputEditTextPassword: TextInputEditText

    private lateinit var appCompatButtonLogin: AppCompatButton

    private lateinit var textViewLinkRegister: AppCompatTextView

    private lateinit var inputValidation: InputValidation

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

        supportActionBar!!.hide()
        initViews()
        initListeners()
        initObjects()

    }

    private fun initViews() {
        val progressBar = findViewById<ProgressBar>(R.id.progressBar)
        progressBar.visibility = View.INVISIBLE
        nestedScrollView = findViewById<View>(R.id.nestedScrollView) as NestedScrollView

        textInputLayoutEmail = findViewById<View>(R.id.textInputLayoutEmail) as TextInputLayout
        textInputLayoutPassword = findViewById<View>(R.id.textInputLayoutPassword) as TextInputLayout

        textInputEditTextEmail = findViewById<View>(R.id.textInputEditTextEmail) as TextInputEditText
        textInputEditTextPassword = findViewById<View>(R.id.textInputEditTextPassword) as TextInputEditText

        appCompatButtonLogin = findViewById<View>(R.id.appCompatButtonLogin) as AppCompatButton

        textViewLinkRegister = findViewById<View>(R.id.textViewLinkRegister) as AppCompatTextView

    }

    private fun initListeners() {

        appCompatButtonLogin!!.setOnClickListener(this)
        textViewLinkRegister!!.setOnClickListener(this)
    }

    private fun initObjects() {

        inputValidation = InputValidation(activity)

    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.appCompatButtonLogin -> verifyFromSQLite()
            R.id.textViewLinkRegister -> {
                val intentRegister = Intent(applicationContext, RegisterActivity::class.java)
                startActivity(intentRegister)
            }
        }
    }

    private fun verifyFromSQLite() {

        if (!inputValidation!!.isInputEditTextFilled(
                textInputEditTextEmail!!,
                textInputLayoutEmail!!,
                getString(R.string.error_message_email))) {
            return        } else if (!inputValidation!!.isInputEditTextFilled(
                textInputEditTextPassword!!,
                textInputLayoutPassword!!,
                getString(R.string.error_message_password))) {
            return        } else {
            val json = JSONObject()
            json.put("email", textInputEditTextEmail.text.toString())
            json.put("password", textInputEditTextPassword.text.toString())

            progressBar.visibility = View.VISIBLE            HttpTask({                progressBar.visibility = View.INVISIBLE                if (it == null) {
                    println("connection error")
                    return@HttpTask                }
                println(it)
                val json_res = JSONObject(it)
                if (json_res.getString("status").equals("true")) {
                    var userdata = User()
                    var jsonArray = JSONArray(json_res.getString("data"))
                    for (i in 0..(jsonArray.length() - 1)) {
                        val item = jsonArray.getJSONObject(i)
                        userdata.id = item.getString("id")
                        userdata.username = item.getString("username")
                        userdata.email = item.getString("email")
                    }
                    emptyInputEditText()
                    val intent = Intent(activity, HomeActivity::class.java)
                    intent.putExtra("id", userdata.id)
                    startActivity(intent)
                    Log.d("userdata Data:::::::", userdata.toString())
                } else {
                    Log.d("psot Data:::::::", json_res.getString("message"))
                    Snackbar.make(nestedScrollView!!, json_res.getString("message"), Snackbar.LENGTH_LONG).show()
                }

            }).execute("POST", "http://192.168.1.111/KotlinExample/LoginRegistration/login.php", json.toString())
        }
    }

    private fun emptyInputEditText() {
        textInputEditTextEmail!!.text = null        textInputEditTextPassword!!.text = null    }

}

activity_register.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout        xmlns:android="http://schemas.android.com/apk/res/android"        xmlns:tools="http://schemas.android.com/tools"        xmlns:app="http://schemas.android.com/apk/res-auto"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:background="@color/colorBackground"        android:paddingBottom="20dp"        android:paddingLeft="20dp"        android:paddingRight="20dp"        android:paddingTop="20dp"        tools:context=".RegisterActivity">
    <android.support.v4.widget.NestedScrollView            android:id="@+id/nestedScrollView"            android:layout_width="match_parent"            android:layout_height="match_parent">

        <android.support.v7.widget.LinearLayoutCompat                android:layout_width="match_parent"                android:layout_height="match_parent"                android:orientation="vertical">

            <android.support.v7.widget.AppCompatTextView                    android:layout_width="wrap_content"                    android:layout_height="wrap_content"                    android:layout_gravity="center_horizontal"                    android:layout_marginTop="40dp"                    android:text="JR"                    android:textSize="100sp"/>

            <android.support.design.widget.TextInputLayout                    android:id="@+id/textInputLayoutName"                    android:layout_width="match_parent"                    android:layout_height="wrap_content"                    android:layout_marginTop="40dp">

                <android.support.design.widget.TextInputEditText                        android:id="@+id/textInputEditTextName"                        android:layout_width="match_parent"                        android:layout_height="wrap_content"                        android:hint="@string/hint_name"                        android:inputType="text"                        android:maxLines="1"                        android:textColor="@android:color/white" />
            </android.support.design.widget.TextInputLayout>

            <android.support.design.widget.TextInputLayout                    android:id="@+id/textInputLayoutEmail"                    android:layout_width="match_parent"                    android:layout_height="wrap_content"                    android:layout_marginTop="20dp">

                <android.support.design.widget.TextInputEditText                        android:id="@+id/textInputEditTextEmail"                        android:layout_width="match_parent"                        android:layout_height="wrap_content"                        android:hint="@string/hint_email"                        android:inputType="text"                        android:maxLines="1"                        android:textColor="@android:color/white" />
            </android.support.design.widget.TextInputLayout>

            <android.support.design.widget.TextInputLayout                    android:id="@+id/textInputLayoutPassword"                    android:layout_width="match_parent"                    android:layout_height="wrap_content"                    android:layout_marginTop="20dp">

                <android.support.design.widget.TextInputEditText                        android:id="@+id/textInputEditTextPassword"                        android:layout_width="match_parent"                        android:layout_height="wrap_content"                        android:hint="@string/hint_password"                        android:inputType="textPassword"                        android:maxLines="1"                        android:textColor="@android:color/white" />
            </android.support.design.widget.TextInputLayout>

            <android.support.design.widget.TextInputLayout                    android:id="@+id/textInputLayoutConfirmPassword"                    android:layout_width="match_parent"                    android:layout_height="wrap_content"                    android:layout_marginTop="20dp">

                <android.support.design.widget.TextInputEditText                        android:id="@+id/textInputEditTextConfirmPassword"                        android:layout_width="match_parent"                        android:layout_height="wrap_content"                        android:hint="@string/hint_confirm_password"                        android:inputType="textPassword"                        android:maxLines="1"                        android:textColor="@android:color/white" />
            </android.support.design.widget.TextInputLayout>

            <android.support.v7.widget.AppCompatButton                    android:id="@+id/appCompatButtonRegister"                    android:layout_width="match_parent"                    android:layout_height="wrap_content"                    android:layout_marginTop="40dp"                    android:background="@color/colorTextHint"                    android:text="@string/text_register" />

            <android.support.v7.widget.AppCompatTextView                    android:id="@+id/appCompatTextViewLoginLink"                    android:layout_width="fill_parent"                    android:layout_height="wrap_content"                    android:layout_marginTop="30dp"                    android:gravity="center"                    android:text="Already a member? Login"                    android:textSize="16dp" />
        </android.support.v7.widget.LinearLayoutCompat>

    </android.support.v4.widget.NestedScrollView>

    <ProgressBar            android:id="@+id/progressBar"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:textColor="@android:color/white"            android:textSize="100sp"            android:layout_centerInParent="true"/>

</RelativeLayout>

RegisterActivity.kt

package com.loginregistration

import android.os.AsyncTask
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.design.widget.TextInputEditText
import android.support.design.widget.TextInputLayout
import android.support.v4.widget.NestedScrollView
import android.support.v7.widget.AppCompatButton
import android.support.v7.widget.AppCompatTextView
import android.util.Log
import android.view.View
import android.widget.ProgressBar
import kotlinx.android.synthetic.main.activity_register.*
import org.json.JSONArray
import org.json.JSONObject

class RegisterActivity : AppCompatActivity(), View.OnClickListener {

    private val activity = this@RegisterActivity
    private lateinit var nestedScrollView: NestedScrollView

    private lateinit var textInputLayoutName: TextInputLayout
    private lateinit var textInputLayoutEmail: TextInputLayout
    private lateinit var textInputLayoutPassword: TextInputLayout
    private lateinit var textInputLayoutConfirmPassword: TextInputLayout

    private lateinit var textInputEditTextName: TextInputEditText
    private lateinit var textInputEditTextEmail: TextInputEditText
    private lateinit var textInputEditTextPassword: TextInputEditText
    private lateinit var textInputEditTextConfirmPassword: TextInputEditText

    private lateinit var appCompatButtonRegister: AppCompatButton
    private lateinit var appCompatTextViewLoginLink: AppCompatTextView

    private lateinit var inputValidation: InputValidation

    operator fun JSONArray.iterator(): Iterator<JSONObject> =
        (0 until length()).asSequence().map { get(it) as JSONObject }.iterator()

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

        val progressBar = findViewById<ProgressBar>(R.id.progressBar)
        progressBar.visibility = View.INVISIBLE
        supportActionBar!!.hide()
        initViews()
        initListeners()
        initObjects()

    }

    private fun initViews() {
        nestedScrollView = findViewById<View>(R.id.nestedScrollView) as NestedScrollView

        textInputLayoutName = findViewById<View>(R.id.textInputLayoutName) as TextInputLayout
        textInputLayoutEmail = findViewById<View>(R.id.textInputLayoutEmail) as TextInputLayout
        textInputLayoutPassword = findViewById<View>(R.id.textInputLayoutPassword) as TextInputLayout
        textInputLayoutConfirmPassword = findViewById<View>(R.id.textInputLayoutConfirmPassword) as TextInputLayout

        textInputEditTextName = findViewById<View>(R.id.textInputEditTextName) as TextInputEditText
        textInputEditTextEmail = findViewById<View>(R.id.textInputEditTextEmail) as TextInputEditText
        textInputEditTextPassword = findViewById<View>(R.id.textInputEditTextPassword) as TextInputEditText
        textInputEditTextConfirmPassword = findViewById<View>(R.id.textInputEditTextConfirmPassword) as TextInputEditText

        appCompatButtonRegister = findViewById<View>(R.id.appCompatButtonRegister) as AppCompatButton

        appCompatTextViewLoginLink = findViewById<View>(R.id.appCompatTextViewLoginLink) as AppCompatTextView

    }

    /**     * This method is to initialize listeners     */    private fun initListeners() {
        appCompatButtonRegister!!.setOnClickListener(this)
        appCompatTextViewLoginLink!!.setOnClickListener(this)

    }

    private fun initObjects() {
        inputValidation = InputValidation(activity)
    }

    override fun onClick(v: View) {
        when (v.id) {

            R.id.appCompatButtonRegister -> postData()

            R.id.appCompatTextViewLoginLink -> finish()
        }
    }

    private fun postData() {
        if (!inputValidation!!.isInputEditTextFilled(
                textInputEditTextName,
                textInputLayoutName,
                getString(R.string.error_message_name))) {
            return        } else if (!inputValidation!!.isInputEditTextEmail(
                textInputEditTextEmail,
                textInputLayoutEmail,
                getString(R.string.error_message_email))) {
            return        } else if (!inputValidation!!.isInputEditTextFilled(
                textInputEditTextPassword,
                textInputLayoutPassword,
                getString(R.string.error_message_password))) {
            return        } else if (!inputValidation!!.isInputEditTextMatches(
                textInputEditTextPassword, textInputEditTextConfirmPassword,
                textInputLayoutConfirmPassword, getString(R.string.error_password_match))) {
            return        } else{
            Snackbar.make(nestedScrollView!!, getString(R.string.success_message), Snackbar.LENGTH_LONG).show()

            val json = JSONObject()
            json.put("email", textInputEditTextEmail.text.toString())
            json.put("username", textInputEditTextName.text.toString())
            json.put("password", textInputEditTextPassword.text.toString())

            progressBar.visibility = View.VISIBLE            HttpTask({                progressBar.visibility = View.INVISIBLE                if (it == null) {
                    println("connection error")
                    return@HttpTask                }
                println(it)
                val json_res = JSONObject(it)
                if (json_res.getString("status").equals("true")) {
                    Snackbar.make(nestedScrollView!!, json_res.getString("message"), Snackbar.LENGTH_LONG).show()
                    emptyInputEditText()
                    finish()
                } else {
                    Log.d("psot Data:::::::", json_res.getString("message"))
                    Snackbar.make(nestedScrollView!!, json_res.getString("message"), Snackbar.LENGTH_LONG).show()
                }
            }).execute("POST", "http://192.168.1.111/KotlinExample/LoginRegistration/register.php", json.toString())
        }

    }

    private fun emptyInputEditText() {
        textInputEditTextName!!.text = null        textInputEditTextEmail!!.text = null        textInputEditTextPassword!!.text = null        textInputEditTextConfirmPassword!!.text = null    }

    companion object {
        val TAG = "RegisterActivity.."    }
}

activity_home.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout        xmlns:android="http://schemas.android.com/apk/res/android"        xmlns:tools="http://schemas.android.com/tools"        xmlns:app="http://schemas.android.com/apk/res-auto"        android:layout_width="match_parent"        android:layout_height="match_parent"        tools:context=".HomeActivity">

    <android.support.v7.widget.LinearLayoutCompat            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:orientation="vertical">

        <android.support.v7.widget.LinearLayoutCompat                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:orientation="horizontal"                android:weightSum="2">

            <android.support.v7.widget.AppCompatTextView                    android:layout_width="0dp"                    android:layout_height="wrap_content"                    android:layout_weight="0.7"                    android:text="User Name : "                    android:textColor="@color/colorBackground"                    android:textSize="24sp"/>

            <android.support.v7.widget.AppCompatTextView                    android:layout_width="0dp"                    android:layout_height="wrap_content"                    android:layout_weight="1.3"                    android:textColor="@color/colorBackground"                    android:textSize="24sp"                    android:id="@+id/txt_userName"/>

        </android.support.v7.widget.LinearLayoutCompat>

        <android.support.v7.widget.LinearLayoutCompat                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:orientation="horizontal"                android:weightSum="2">

            <android.support.v7.widget.AppCompatTextView                    android:layout_width="0dp"                    android:layout_height="wrap_content"                    android:layout_weight="0.7"                    android:text="Email : "                    android:textColor="@color/colorBackground"                    android:textSize="24sp"/>

            <android.support.v7.widget.AppCompatTextView                    android:layout_width="0dp"                    android:layout_height="wrap_content"                    android:layout_weight="1.3"                    android:textColor="@color/colorBackground"                    android:textSize="24sp"                    android:id="@+id/txt_email"/>

        </android.support.v7.widget.LinearLayoutCompat>

    </android.support.v7.widget.LinearLayoutCompat>

    <ProgressBar            android:id="@+id/progressBar"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:textSize="100sp"            android:layout_centerInParent="true"            android:background="@color/colorBackground"/>

</RelativeLayout>

HomeActivity.kt

package com.loginregistration

import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v7.widget.AppCompatButton
import android.support.v7.widget.AppCompatTextView
import android.util.Log
import android.view.View
import android.widget.ProgressBar
import kotlinx.android.synthetic.main.activity_register.*
import org.json.JSONArray
import org.json.JSONObject

class HomeActivity : AppCompatActivity() {

    private lateinit var txt_userName: AppCompatTextView
    private lateinit var txt_email: AppCompatTextView

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

        val id = intent.getStringExtra("id")

        initViews()
        progressBar.visibility = View.VISIBLE        HttpTask({            progressBar.visibility = View.INVISIBLE            if (it == null) {
                println("connection error")
                return@HttpTask            }
            println(it)
            val json_res = JSONObject(it)
            if (json_res.getString("status").equals("true")) {
                var userdata = User()
                var jsonArray = JSONArray(json_res.getString("data"))
                for (i in 0..(jsonArray.length() - 1)) {
                    val item = jsonArray.getJSONObject(i)
                    userdata.id = item.getString("id")
                    userdata.username = item.getString("username")
                    userdata.email = item.getString("email")
                }
                Log.d("userdata Data:::::::", userdata.toString())
                txt_userName.setText(userdata.username)
                txt_email.setText(userdata.email)
            } else {
                Log.d("psot Data:::::::", json_res.getString("message"))
                Snackbar.make(nestedScrollView!!, json_res.getString("message"), Snackbar.LENGTH_LONG).show()
            }
        }).execute("GET", "http://192.168.1.111/KotlinExample/LoginRegistration/get_user_detail.php?id="+id)

    }

    private fun initViews() {

        val progressBar = findViewById<ProgressBar>(R.id.progressBar)
        progressBar.visibility = View.INVISIBLE
        txt_userName = findViewById<View>(R.id.txt_userName) as AppCompatTextView
        txt_email = findViewById<View>(R.id.txt_email) as AppCompatTextView
    }
}

5 comments:

  1. Thankyou very much sir.
    It really help me 👍🙏💐🙏

    ReplyDelete
  2. where is InputValidation class?

    ReplyDelete
  3. can you help me with the InputValidation? it's always error

    ReplyDelete
  4. Do we import InputValidation? I can't find it anywhere.

    ReplyDelete