Monday, 20 February 2017

How can I use jQuery in Angular 2... How can I use iPhone like password input...



Hello Buddies.


First of all, in my quest to get acquainted with the all new glittery NG2, I think I was the quickest in making myself believe that NG2 won't allow jQuery to run in its playground.

But as I continued some RnD, I was amazed to see, it allows, though in the style it likes.

Now that won't stop us to open the throttle of jQuery here, as this one always remains the lovable UI library of many.


Writing this from a novice's perspective towards Angular 2 and jQuery, this might indulge you in getting started confidently.



The case study selected here comprises of the following requirements -

1. Get the password from the user.
2. Only show the entered character, while masking the earlier characters.
3. Something like iPhone password text box...


So here it goes...


Taking further the older post, additionally we install jQuery here -

npm install jquery --save

npm install @types/jquery --save-dev


In the component - pagePwd.component.ts, have the following code lines -



import {Component, ViewChild, ElementRef, AfterViewInit} from '@angular/core';

// this allows the $ to be available as in case of normal jQuery usagevar $ = require('jquery');

@Component({
  selector: 'app-pagePwd',
  providers: [],
  templateUrl: './pagePwd.component.html'})


export class CheckPwdComponent {

// this one is for replacing document ready part, that is done in script tags otherwise
ngAfterViewInit() {
    var placeholder = "";
    var originalPwd = "";
    var flag=0;

    // part 1
    $("#shownPwd").on('keydown',function(e){
      console.log(">>>>>>>>>>>>>" + e.keyCode);
      if (e.keyCode != 8 && e.keyCode != 16 && !(e.keyCode>=37 && e.keyCode<=40) && e.keyCode != 46) {
        flag++;
        if(flag>1){
          e.preventDefault();
        }
      }
    });

    // part 2 
    $('#shownPwd').bind("cut copy paste",function(e) {
      e.preventDefault();
    });

    // part 3
    $("#shownPwd").keyup(function(event){

      flag = 0;

      console.log($(this).val());
      var endChar = $(this).val().substr($(this).val().length - 1);
      if (endChar != "•") {
        originalPwd += $(this).val().substr($(this).val().length - 1);
      }
      console.log('original pwd = '+originalPwd);
      placeholder = $(this).val().replace(/./g,"•");
      $(this).val(placeholder);
      console.log($(this).val());

      if (event.keyCode == 8){
        originalPwd = originalPwd.substring(0, originalPwd.length - 1);
        console.log('after deletion, org pwd = '+originalPwd);
      }
    })

  }

}


Now have a template component as stated above - pagePwd.component.html, and include this one -

<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<meta charset="UTF-8"> <title>Check PWD</title>
    <input type="text" id="shownPwd" placeholder="password">
</body>
</html>


Explanation -

Part 1:
Takes care of the long key press, and editing scenarios like arrow keys, backspace and delete keys.

Part 2:
Preventing cut copy paste.

Part 3:
Actual logic, i.e. take the latest entered character and maintain password, while replacing the earlier characters.
Do try this to experience, and please share your suggestions and thoughts for improving the same.

The main question '?'
Why ngAfterViewInit

That's because in this world of NG2, script tags are barely recognized. 
So the mighty developers have provided this as a work around for document ready.


Console output -



Happy Coding buddies... take care... we will meet again with some more interesting topics soon...

Sunday, 12 February 2017

Talk Time - Android Speech to Text (English)







Hello Buddies.

Why not try something related to Android this time?

Like we always quote, a small piece of intro code can boost up your confidence and make you familiar with technology you want to take head on.

A basic program using “Android Studio”, “Speech API” and your “Android Handset” can provide you with a cool app, you can boast around with, and capture voice to try convert it into text.

The steps are very limited and simple –

1.      Create a new project in Android Studio.

2.       Use your weapon – JAVA to write down a class MainActivity.java

package com.example.myfirstapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import java.util.ArrayList;
import java.util.Locale;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
   
private final int SPEECH_RECOGNITION_CODE = 1;
   
private TextView txtOutput;
   
private ImageButton btnMicrophone;
   
private ImageButton btnMicrophone2;

   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_main);
       
txtOutput = (TextView) findViewById(R.id.txt_output);
       
btnMicrophone = (ImageButton) findViewById(R.id.btn_mic);
        
btnMicrophone.setOnClickListener(new View.OnClickListener() {
           
@Override
           
public void onClick(View v) {
                startSpeechToText();
            }
        });
    }
    private void startSpeechToText() {
        Intent intent =
new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.
EXTRA_LANGUAGE, Locale.getDefault());
        intent.putExtra(RecognizerIntent.
EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.
EXTRA_PROMPT, "Speak something...");
       
try {
            startActivityForResult(intent,
SPEECH_RECOGNITION_CODE);
        }
catch (ActivityNotFoundException a) {
            Toast.makeText(getApplicationContext(),
"Sorry! Speech recognition is not supported in this device.", Toast.LENGTH_SHORT).show();
        }
    }
    @Override
   
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       
super.onActivityResult(requestCode, resultCode, data);
       
switch (requestCode) {
           
case SPEECH_RECOGNITION_CODE: {
               
if (resultCode == RESULT_OK && null != data) {
                    ArrayList<String> result = data
                            .getStringArrayListExtra(RecognizerIntent.
EXTRA_RESULTS);
                    String text = result.get(
0);
                   
txtOutput.setText(text);
                }
               
break;
            }
        }
    }

}


3.       Make some changes in AndroidManifest.xml as below –

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.example.myfirstapp"

    android:versionCode="1"

    android:versionName="1.0">

    <application

        android:allowBackup="true"

        android:label="@string/app_name"

        android:theme="@style/AppTheme" >

        <activity android:name="MainActivity" >

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

    </application>

</manifest>



4.       Under layout folder à Have activity_main.xml as  below –

<?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/black"

    android:orientation="vertical" >

    <TextView

        android:id="@+id/txt_output"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignParentTop="true"

        android:layout_centerHorizontal="true"

        android:layout_marginTop="50dp"

        android:textColor="@color/green"

        android:text="Talk Time !"

        android:textSize="50dp"

        android:textStyle="bold" />

    <LinearLayout

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignParentBottom="true"

        android:layout_centerHorizontal="true"

        android:layout_marginBottom="200dp"

        android:gravity="center"

        android:orientation="vertical" >

        <ImageButton

            android:id="@+id/btn_mic"

            android:layout_width="100dp"

            android:layout_height="100dp"

            android:background="@color/black"

            android:scaleType="centerCrop"

            android:src="@mipmap/ic_launcher"

            />

        <TextView

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:layout_marginTop="10dp"

            android:text="English Speech to text using Google API"

            android:textColor="@color/white"

            android:textSize="15dp"

            android:textStyle="italic" />

    </LinearLayout>

</RelativeLayout>


5.       You can also add colors as per your choice in values/colors.xml

<?xml version="1.0" encoding="utf-8"?>

<resources>

    <color name="colorPrimary">#3F51B5</color>

    <color name="colorPrimaryDark">#303F9F</color>

    <color name="colorAccent">#FF4081</color>

    <color name="white">#FFFFFF</color>

    <color name="black">#000000</color>

    <color name="red">#FF0000</color>

    <color name="blue">#0000FF</color>

    <color name="green">#00FF00</color>

    <color name="yellow">#F0F000</color>

</resources>
 
6.       Strings.xml –

<resources>

    <string name="app_name"> Speech To Text </string>

</resources>

Your IDE will show folder structure like this -



Once the compiler approves, you are ready to build your project as APK.
Export the APK into your Android device and BOOM, you are ready to install and flaunt you new Voice to Text converter.


The code mentioned above has been inspired from various hard-core online materials available, leaving the theoretical and explanatory parts to the readers. Happy Coding ...

Let's say Hello to the World... the Angular 2 way...


With the onset of journey towards Angular 2, some quick tit-bits are always helpful, to get you going and making your development life bit easier.

We shall target few upcoming posts to have working components in place and to use these plugins to chip off coding duration. They might not be the complete tutorials for you, but will be quite beneficial in providing some hands on experience.

Your suggestions for corrections and improvements are always welcome.

Let’s start with the basic one, following the old-school tradition, i.e. ‘Hello World’.

What we need to kick off -

1. Eclipse CLI – can be installed as plugin in your favorite eclipse flavor, and can be it can be used for around a fortnight as freely available.
2. Webpack – alternative to the above, since once trial expires we have to switch to the next best player out there. A pointer for this can be -
3. NPM – we should better keep ourselves acquainted with the npm magic words like – npm install, npm update, npm start, to run the NG2 apps.

We are here assuming that the basic documentations and key notes about NG2 are already well versed with us, and the minds are having clarity for the why’s and what’s.

We have the basic project structure similar to the below one -



Main action players are -

a. app module for registering – app.module.ts
import { NgModule } from '@angular/core';
@NgModule({
declarations: [
AppComponent
],
imports: [],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }


b. component ts – app.component.ts
import { Component, Input, Output } from '@angular/core';
import { Router, Routes } from '@angular/router';
@Component({
selector: 'app-root',
providers: [],
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor() { }
init() {
}
}

c. component html – app.component.html
hello world !



Action behind the scenes is -

1  Index.html has app-root defined.
2. app.component.ts has the above as the selector -
3. there corresponding tenplateurl or template is picked up i.e. html content

Hitting npm start command loads the NG2 app on the npm server and hit localhost:8080 for this example and BOOM -

.  

Featured post

JAVA based project, that can be used to hit DB using JDBC, from WSO2 ESB

Hi Buddies, Here is a small project that will enable you to hit MySQL DB using WSO2 ESB - https://github.com/namitsharma99/customM...