Home Blog Page 79

How to change whole app language in android programmatically

0

Hi Guys, Welcome to Proto Coders Point, In this Android Tutorial we will create an app that can support multiple languages, In other words, the user can select his desired language to change the whole app language in android.

This is a Simple Example of how to make an android multi language app with an example – locale in android.

how to change app language android
DEMO

Video Tutorial on change whole app language android programmatically

Step 1 − Create a new Android Project in Android Studio

Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. ( Name it as Change App language)

Step 2 – Create a new strings.xml with locale

In the values directory, you need to create a separate string.xml(hi) or any other language

Here is how to create a locale in android string with a language

right-click on values directory => New => Values Resource File

The below dialog will pop up in the android studio

Here you need to select your locale languages that your app will support.

how to create locale string in android
how to create locale string in android

After creating saperate strings.xml files for particular languages your string directory will look something like this.

strings xml to change app languages

Now in those strings.xml file add the translated strings

string.xml (hi) for hindi language in your android app.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">ऐप भाषा बदलें</string>
    <string name="language">नमस्ते दुनिया</string>
</resources>

string.xml (kn) for Kannada language in your app.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">ಅಪ್ಲಿಕೇಶನ್ ಭಾಷೆ</string>
    <string name="language">ಹಲೋ ವರ್ಲ್ಡ್</string>
</resources>

likewise you can add different language that you want to add into your android applicaton.

Step 3 – Create a LocaleHelper Class

Now create new java file and name it as Localehelper and add the below code

This class will help you in getting and storing language that a user has previously selected before he close the application, we will use SharedPreferences to store the locale selected by user in app.

package com.example.applanguagechange.Language;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.preference.PreferenceManager;

import java.util.Locale;

/**
 * Created by abdalla on 10/2/17.
 */

public class LocaleHelper {

    private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";

    public static Context onAttach(Context context) {
        String lang = getPersistedData(context, Locale.getDefault().getLanguage());
        return setLocale(context, lang);
    }

    public static Context onAttach(Context context, String defaultLanguage) {
        String lang = getPersistedData(context, defaultLanguage);
        return setLocale(context, lang);
    }

    public static String getLanguage(Context context) {
        return getPersistedData(context, Locale.getDefault().getLanguage());
    }

    public static Context setLocale(Context context, String language) {
        persist(context, language);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return updateResources(context, language);
        }

        return updateResourcesLegacy(context, language);
    }

    private static String getPersistedData(Context context, String defaultLanguage) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getString(SELECTED_LANGUAGE, defaultLanguage);
    }

    private static void persist(Context context, String language) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = preferences.edit();

        editor.putString(SELECTED_LANGUAGE, language);
        editor.apply();
    }

    @TargetApi(Build.VERSION_CODES.N)
    private static Context updateResources(Context context, String language) {
        Locale locale = new Locale(language);
        Locale.setDefault(locale);

        Configuration configuration = context.getResources().getConfiguration();
        configuration.setLocale(locale);
        configuration.setLayoutDirection(locale);

        return context.createConfigurationContext(configuration);
    }

    @SuppressWarnings("deprecation")
    private static Context updateResourcesLegacy(Context context, String language) {
        Locale locale = new Locale(language);
        Locale.setDefault(locale);

        Resources resources = context.getResources();

        Configuration configuration = resources.getConfiguration();
        configuration.locale = locale;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            configuration.setLayoutDirection(locale);
        }

        resources.updateConfiguration(configuration, resources.getDisplayMetrics());

        return context;
    }
}

Step 4 –  UI Design

activity_main.xml 

Add the following code to res/layout/activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".MainActivity"
    android:layout_gravity="center"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
        android:id="@+id/helloworld"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <RelativeLayout
        android:id="@+id/showlangdialog"
        android:layout_width="200dp"
        android:layout_height="40dp"
        android:layout_marginTop="10dp"
        android:layout_marginEnd="3dp"
        android:layout_marginRight="3dp"
        android:background="@drawable/background_color"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/dialog_language"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentBottom="true"
            android:layout_gravity="center"
            android:gravity="center"
            android:background="@android:color/transparent"
            android:dropDownVerticalOffset="35dp"
            android:popupBackground="@color/colorPrimary"
            android:textColor="@color/white"
            android:text="English"
             />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_gravity="center"
            android:layout_marginRight="10dp"
            android:src="@drawable/drop" />

    </RelativeLayout>

</LinearLayout>

@drawable/spinner_background.xml

create a new drawable resource file under drawable folder and add the below code.

This code is just to give background to above relativelayout

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/colorPrimary"
        />
    <corners android:radius="40dp" />
    <stroke
        android:width="1dp"
        android:color="#05AC21" />
</shape>

Create a vector drop image in drawable folder

Right Click(drawable) > New > Vector Image ( select a arrow down vector image )

Step 5 –  Java Code to switch between string.xml to use

Main_Activity.java

package com.example.applanguagechange;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    TextView helloworld,dialog_language;
    int lang_selected;
    RelativeLayout show_lan_dialog;


    Context context;
    Resources resources;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dialog_language = (TextView)findViewById(R.id.dialog_language);
        helloworld =(TextView)findViewById(R.id.helloworld);
        show_lan_dialog = (RelativeLayout)findViewById(R.id.showlangdialog);

        if(LocaleHelper.getLanguage(MainActivity.this).equalsIgnoreCase("en"))
        {
            context = LocaleHelper.setLocale(MainActivity.this,"en");
            resources =context.getResources();
            dialog_language.setText("ENGLISH");
            helloworld.setText(resources.getString(R.string.hello_world));
            setTitle(resources.getString(R.string.app_name));
            lang_selected = 0;

        }else if(LocaleHelper.getLanguage(MainActivity.this).equalsIgnoreCase("hi")){
            context = LocaleHelper.setLocale(MainActivity.this,"hi");
            resources =context.getResources();
            dialog_language.setText("हिन्दी");
            helloworld.setText(resources.getString(R.string.hello_world));
            setTitle(resources.getString(R.string.app_name));
            lang_selected =1;
        }
        else if(LocaleHelper.getLanguage(MainActivity.this).equalsIgnoreCase("kn")){
            context = LocaleHelper.setLocale(MainActivity.this,"kn");
            resources =context.getResources();
            dialog_language.setText("ಕನ್ನಡ");
            helloworld.setText(resources.getString(R.string.hello_world));
            setTitle(resources.getString(R.string.app_name));
            lang_selected =2;
        }

        show_lan_dialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String[] Language = {"ENGLISH","हिन्दी","ಕನ್ನಡ"};
                final int checkItem;
                Log.d("Clicked","Clicked");


                final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this);
                dialogBuilder.setTitle("Select a Language")
                              .setSingleChoiceItems(Language, lang_selected, new DialogInterface.OnClickListener() {
                                  @Override
                                  public void onClick(DialogInterface dialogInterface, int i) {
                                      dialog_language.setText(Language[i]);

                                      if(Language[i].equals("ENGLISH")){
                                           context = LocaleHelper.setLocale(MainActivity.this,"en");
                                           resources =context.getResources();
                                           lang_selected = 0;

                                           helloworld.setText(resources.getString(R.string.hello_world));
                                           setTitle(resources.getString(R.string.app_name));

                                      }
                                      if(Language[i].equals("हिन्दी"))
                                      {
                                          context = LocaleHelper.setLocale(MainActivity.this,"hi");
                                          resources =context.getResources();
                                          lang_selected = 1;
                                          helloworld.setText(resources.getString(R.string.hello_world));
                                          setTitle(resources.getString(R.string.app_name));
                                      }
                                      if(Language[i].equals("ಕನ್ನಡ"))
                                      {
                                          context = LocaleHelper.setLocale(MainActivity.this,"kn");
                                          resources =context.getResources();
                                          lang_selected = 2;
                                          helloworld.setText(resources.getString(R.string.hello_world));
                                          setTitle(resources.getString(R.string.app_name));
                                      }
                                  }
                              })
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                             @Override
                             public void onClick(DialogInterface dialogInterface, int i) {
                                   dialogInterface.dismiss();
                                }
                });
                dialogBuilder.create().show();
            }
        });

    }
}

Here in above code we have  a RelativeLayout with OnClickEvent, Then user will click the RelativeLayout a AlertDialog will popup asking for language selection, by using which user can change language of his application.

For Example: When user select language as Hindi, The strings.xml (hi) will get loaded and all the text in the application will turn it language string that come from strings.xml (hi), likewise if user select kannada as his app language then strings gets loaded from strings.xml(kn).

and if he select language as English all language will come back to default string.xml

Conclusion

In this tutorial we learnt how to change whole app language in android programmatically using strings.xml locale.

Android Whatsapp Intent | Sending Message from your app to whatsapp

0
android whatsapp api send message

Hi Guys, Welcome to Proto Coders Point, In this android tutorial we will integrate sending message from your android application to whatsapp using whatsapp send message api service.

Video Tutorial on Youtube on android whatsapp intent

Send Message android whatsapp intent

Step 1 : Create a new Android Project

Off-Course you need a android Project to be created in android studio or open any existing project

File > New > New Project  give a name to the project as “whatsapp intent send Message”   hit the finish button

Step 2 : Adding Country Code Picker library

Open build.gradle (app level) and in dependencies section add the below implementation code.

implementation 'com.hbb20:ccp:2.4.0'

then, After adding the dependencies hit the Sync Now button

country code picker android library

Official Site to learn more about Country Code Picker

Step 3 : Custom EditText Background Design

To create a custome EditText Background Design you need to create a new Drawable Resource File to do so Right Click on drawable folder under app > res > drawable

Then, Name the Drawbale Resource file as “rounded_edittext.xml” and paste the below code in it.

<?xml version="1.0" encoding="utf-8"?>
<!-- res/drawable/rounded_edittext.xml -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="10dp"
    android:shape="rectangle" >

    <solid android:color="#FFFFFF" />

    <corners
        android:bottomLeftRadius="10dp"
        android:bottomRightRadius="10dp"
        android:topLeftRadius="10dp"
        android:topRightRadius="10dp" />

</shape>

Step 4 : UI Design

For this project we have 2 editText, a Country Code Picker  and a Button to send the message through whatsapp intent.

whatsapp ui design

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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=".MainActivity"
    android:orientation="vertical"
    android:background="@drawable/whatsapp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="WhatsApp Intent Send message Example"
        android:textColor="@android:color/white"
        android:gravity="center"
        android:textStyle="bold"
        android:layout_marginTop="10dp"
        android:textSize="20sp"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="10dp"
        >

        <com.hbb20.CountryCodePicker

            app:ccp_arrowColor="#FFF"
            app:ccp_contentColor="#FFF"
            android:id="@+id/ccp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <EditText
            android:id="@+id/phonenumber"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:hint="Enter Phone Number"
            android:paddingLeft="10dp"
            android:inputType="phone"
            android:background="@drawable/rounded_edittext"
            android:layout_marginLeft="5dp" />


    </LinearLayout>

        <EditText
            android:id="@+id/messages"
            android:layout_width="match_parent"
            android:layout_height="300dp"
            android:layout_marginTop="10dp"
            android:background="@drawable/rounded_edittext"
            android:gravity="start"
            android:hint="Enter Your Message"
            android:inputType="textMultiLine"
            android:paddingLeft="15dp"
            android:paddingTop="10dp" />

        <Button
        android:id="@+id/sendbutton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#4CAF50"
        android:drawableRight="@drawable/messageicon"
        android:paddingRight="20sp"
        android:textColor="#FFF"
        android:textSize="15sp"
        android:layout_margin="15dp"
        android:text="Send Message Through WhatsApp"
        />

    </LinearLayout>
</ScrollView>

Step 5 : JAVA code

MainActivity.java

package com.example.whatsappintentsendmsg;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.hbb20.CountryCodePicker;

public class MainActivity extends AppCompatActivity {

    EditText phoneno,message;
    CountryCodePicker ccpp;
    Button sendButton;
    String messageStr,phoneStr ="";

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

        phoneno = ( EditText) findViewById(R.id.phonenumber);
        message =(EditText)findViewById(R.id.messages);
        ccpp=(CountryCodePicker)findViewById(R.id.ccp);
        sendButton=(Button)findViewById(R.id.sendbutton);

        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                messageStr = message.getText().toString().trim();
                phoneStr = phoneno.getText().toString().trim();

                if(phoneStr.isEmpty())
                {
                    phoneno.setError("Please Enter Phone");
                } else if (messageStr.isEmpty())
                {
                    message.setError("Please Enter Message");
                }else{
                    ccpp.registerCarrierNumberEditText(phoneno);
                    phoneStr = ccpp.getFullNumber();

                    boolean isInstalled = WhatsappAvailable("com.whatsapp");

                    //if whatsapp is installed it will be true or else isInstalled will become false
                    if(isInstalled)
                    {
                        //Whatsapp send message using Instant
                        Intent whatsapp = new Intent(Intent.ACTION_VIEW,Uri.parse("https://api.whatsapp.com/send?phone="+phoneStr+"&text="+messageStr));

                        startActivity(whatsapp);
                        phoneno.setText("");
                        message.setText("");

                    }else
                    {
                        Toast.makeText(MainActivity.this,"Whatsapp is not Installed on your Device",Toast.LENGTH_SHORT).show();
                    }
                    
                }

            }
        });
    }

    //check is whatsapp is installed on the Device
    private  boolean WhatsappAvailable(String uri)
    {
        PackageManager packageManager = getPackageManager();
        boolean isInstalled;
        try{
            packageManager.getPackageInfo(uri,PackageManager.GET_ACTIVITIES);
            isInstalled = true;

        }catch (PackageManager.NameNotFoundException e){
           isInstalled = false;

        }
        return  isInstalled;
    }


}

 

 

Flutter : Auto Create Model from JSON file | json model Dart Package

0

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial, we will learn how to auto create model class from json file by making use of json model dart package library.

What is Json Model package?

Flutter json model package library is been used to create a model class from a json file. In other words this Library will help you to convert json data to model class for your flutter application.

Ok so let’s begin

Flutter : Auto Create Model from JSON file | json model Dart Package

Step 1 : Add Required Dependencies

Create a new Flutter project and add the following 4 dependencies.

To do so open pubspec.yaml file and add those.

dependencies

json_annotation : to create code for JSON serialization and deserialization.

dev_dependencies 

json_model: used to generate model

build_runner: concrete way of generating files using dart code.

json_serializable: helps provider builder for handling JSON request.

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^0.1.3
  json_annotation:  #to create code for JSON serialization and deserialization.

dev_dependencies:
  flutter_test:
    sdk: flutter

  json_model:  #used to generate json to model
  build_runner: ^1.0.0 #concrete way of generating files using Dart code
  json_serializable: ^2.0.0  #helps provides builder for handling JSON

JSON to Model class can be generated simple by using json_model but json model will also make use of json serializable for Mapping and all other Modeling Staff.

So just add the above 4 dependencies in your flutter project pubspec.yaml file.

Step 2 : Create folder and Create .json file

Then, after adding json model and other 3 dependencies, now you need to create a new folder by name “jsons” and inside that folder create a .json file and add some json data in it.

  1. Create a “jsons” directory in root of your flutter project.
  2. Create a json file under jsons directory.
  3. Add below json data in that json file.

json data for model

{
  "name": "Flash",
  "power": "Speed Run : His connection to the Speed Force gives him plenty of abilities.",
  "url": "https://m.media-amazon.com/images/M/MVXSDS_.jpg"
}

Check out my project structure in below image

json to model flutter
Created a folder by name “jsons” and inside it created a .json file which has some json data in it

Step 3 : Go to Terminal  and Run the Flutter Command

Once, you have created .json file and some json data in it, Now open your terminal and run the below Flutter Command

flutter packages pub run json_model

as shown below

flutter cmd to run json model

What this command will do is, It will auto detect json file from jsons  directory and create model from json data into your flutter project as shown below

"flutter

Conclusion

Ok so in this tutorial we checked out how to auto-generate data model class from JSON file by using JSON MODEL dart package library.

Recommended Post 

fetching data in flutter and displaying in listview

Install nodejs latest version on Ubuntu & Windows in 2 mins

1
Installing Nodejs On Ubuntu & Windows

Hi Guys, Welcome to Proto Coders Point, In this Programmer Blog post we will learn About What is Node.js and Why is Node js used for? and even we will check how to install NODE.JS on Ubuntu & Windows OS.

What is Node.js?

Node.js is basically an Open-Source Scripting Language, It is and JavaScript runtime Environment that executes JS codes outside a browser also.

The Node js will help the Back-End Developer use javascript to write server-side script to produce dynamic web page and fetch data from database before web page is sent to user’s browers.

In Short Node.js is and Open Source server environment which is completely free to used and Node.js is very speed and easily compatible on various OS platforms (Windows, Linus , Unix, Mac OS any many more)

Why NodeJS is Famous?

By using Simple JavaScript, we cannot get access to files system from browser but sometimes there is a situation, where we need to be able to read data from local file system sinse this is not possible by using Javascript.

In this sense we need something that we can use to interact directly with the computer file system, that’s what exactly what node.js allows us to do.

Node.js allows us to take javascript out of the browser by allowing us to interact directly with the computer data source.

Thus not we can access system files, Therefore by using Node.js we can also create a desktop application and Atom Editor is the best example that is built using Node.js.

Then, Now you can write javascript code not just for browser but also to make use of hardware component or file system.

Why node.js?

Well, node.js can be run on your own computer or somebody else computer rather say it you can run server script using Node.js on server computer.

How to Install nodejs latest version on ubuntu

Here we use curl to download nodejs 16 on Ubuntu.

Option 1: Using curl

Installation Steps

1. Install curl on ubuntu

sudo apt install curl

2. Download NodeJS 16 Repository

curl -sL https://deb.nodesource.com/setup_16.x | sudo bash –

curl -sL https://deb.nodesource.com/setup_16.x | sudo bash -

In above cmd just replace setup_16.x to latest Eg: setup_17.x (whichever is latest).

3. Finally install Latest NodeJS using below cmd.

sudo apt -y install nodejs

Finally we have successfully installed, Latest Nodejs On Ubuntu, just by following above 3 cmd both node & npm will get installed.

4. Check Node & npm version

node  -v
npm -

Option 2: use standard Binary Package to install nodeJS & Npm in ubuntu

1. use wget to download the nodeJS of your desired version, Note that in below command replace v16.17.1 with the version you want to download.

sudo wget https://nodejs.org/dist/v16.17.1/node-v16.17.1-linux-x64.tar.xz

2. to unpack or unzip the above tar.xz u need to xz-utils so install it.

sudo apt-get install xz-utils

3. Now extract the tar.xz using xz-utils as below, This cmd will install node.js binary in /usr/local/:

tar -C /usr/local --strip-components 1 -xJf node-v16.17.1-linux-x64.tar.xz

4. Finally Node and npm is been install in /usr/local/bin, To check run below commands

ls -l /usr/local/bin/node
ls -l /usr/local/bin/npm

or 

node -v
npm -v

How to Install Node.js on Windows

Installation Steps

  1. Download the Windows installer from the Nodes.js® web site
  2. Choose the LTS version that’s shown on the left. 
  3. Run the installer (the .msi file you downloaded in the previous step.)
  4. Follow the prompts in the installer (Accept the license agreement, click the NEXT button a bunch of times and accept the default installation settings).
node js installation
node js installation

5. Restart your computer. You won’t be able to run Node.js® until you restart your computer.

6. Confirm that Node has been installed successfully on your computer by opening a Hyper terminal and typing in the commands node --version

how to check nodejs version

You should see the version of node you just installed. So you can see my pc is been install with NodeJS version 12.17.0

Getting Started with NodeJS

Once Nodejs is been Installed successfully in your OS, Let’s use write a node script that will simply display ” HelloWorld” on the Browser.

Create a folder on your Desktop named “nodejs” under that folder Create a .js file named “helloworld.js”, and add the following code:

var http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/h1'});
    res.end("Hello World! Welcome to Proto Coders Point");
}).listen(8080);

console.log(" Server Running at : http://localhost:8080/");

Save the file.

Then Open Comment Prompt and run the below command

1. moving inside folder.

C:\Users\rajat>cd Desktop

C:\Users\rajat\Desktop>cd nodejs2

2. run the script using node cmd

C:\Users\rajat\Desktop\nodejs2>node helloworld.js

Then,  your computer works as a server of helloworld.js file

If anyone tries to access your computer on port 8080, they will get a “Hello World!” message in return!

Start your internet browser, and type in the address: http://localhost:8080

how to run nodejs file in cmd prompt

Result on the browser

Password Validation regex in Android

0
Password Text Field Validation in android
Password Text Field Validation in android

Hi Guys Welcome to Proto Coders Point, In this Android Tutorial we will learn how to implement password validation regex requirements in android app.

In other words Password Validation   To check a password character must be minimum 8 character length which include alphebet, numeric digits and any special character symbol.

Password Validation requirements

  1. Atleast 8 character in length.
  2. Minimum One Uppercase.
  3. Minimum One Number.
  4. and should contain 1 Special Symbol.

Password Validation regex in android

Video Tutorial

Follow the below Steps and Code to integrate this validation textfield in android.

Step 1 : Create a new android project

offcourse you need to create a new Android Project or Open any existing project in android studio.

File > New > New Project > Empty Activity

Give a name to android project as “Password Validation android”  or anything else as per your choice.

hit next > finish.

Step 2 : Add Material Design Dependencies

Open build.gradle(app level) and add the below android design dependencies.

implementation 'com.android.support:design:29.0.0'

We are making use of android design library dependencies so that we can use material.textfield.TextInputLayout  and androidx.cardview.widget.CardView in our android UI design.

Step 3 : Creating a Registration page UI

Open activity_main.xml file and copy page the below xml UI code.

registration page UI design android
registration page UI design android

<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView 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=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="20dp"
        android:orientation="vertical"
        >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="35sp"
            android:textStyle="bold"
            android:text="Register"
            android:textColor="@android:color/black"
            android:gravity="center"
            android:layout_marginBottom="30dp"
            />

        <com.google.android.material.textfield.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="60dp"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense">

        <EditText
            android:id="@+id/etFullname"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:hint="Enter Full Name"
            android:inputType="text"
            android:textColor="@android:color/black"
            />

    </com.google.android.material.textfield.TextInputLayout>

        <com.google.android.material.textfield.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="60dp"
            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense">

            <EditText
                android:id="@+id/etEmail"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:hint="Enter Email"
                android:inputType="text"
                android:textColor="@android:color/black"
                />

        </com.google.android.material.textfield.TextInputLayout>



        <com.google.android.material.textfield.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="60dp"
            app:passwordToggleEnabled="true"
            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense">

            <EditText
                android:id="@+id/etPassword"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:hint="Enter Password"
                android:inputType="textPassword"
                android:textColor="@android:color/black"
                />

        </com.google.android.material.textfield.TextInputLayout>



        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Password must be "
            android:layout_marginTop="10dp"
            android:textColor="@android:color/black"
            android:textSize="18sp"
            />
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="30dp"
            android:layout_marginTop="10dp"
            android:gravity="center"
            android:orientation="horizontal">

            <androidx.cardview.widget.CardView
                android:id="@+id/card1"
                android:layout_width="20dp"
                android:layout_height="20dp"
                app:cardBackgroundColor="#dcdcdc"
                app:cardCornerRadius="25dp"
                android:layout_gravity="center">

                <ImageView
                    android:layout_gravity="center"
                    android:layout_width="15dp"
                    android:layout_height="15dp"
                    android:background="@drawable/check_24"
                    />


            </androidx.cardview.widget.CardView>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:textColor="@android:color/black"
                android:text="Atleast 8 character"
                android:gravity="center|start"
                android:layout_marginStart="10dp"
                android:layout_marginEnd="10dp"

                android:layout_marginLeft="10dp" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="30dp"
            android:layout_marginTop="10dp"
            android:gravity="center"
            android:orientation="horizontal">

            <androidx.cardview.widget.CardView
                android:id="@+id/card2"
                android:layout_width="20dp"
                android:layout_height="20dp"
                app:cardBackgroundColor="#dcdcdc"
                app:cardCornerRadius="25dp"
                android:layout_gravity="center">

                <ImageView
                    android:layout_gravity="center"
                    android:layout_width="15dp"
                    android:layout_height="15dp"
                    android:background="@drawable/check_24"
                    />


            </androidx.cardview.widget.CardView>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:textColor="@android:color/black"
                android:text="mininum one number"
                android:gravity="center|start"
                android:layout_marginStart="10dp"
                android:layout_marginEnd="10dp"

                android:layout_marginLeft="10dp" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="30dp"
            android:layout_marginTop="10dp"
            android:gravity="center"
            android:orientation="horizontal">

            <androidx.cardview.widget.CardView
                android:id="@+id/card3"
                android:layout_width="20dp"
                android:layout_height="20dp"
                app:cardBackgroundColor="#dcdcdc"
                app:cardCornerRadius="25dp"
                android:layout_gravity="center">

                <ImageView
                    android:layout_gravity="center"
                    android:layout_width="15dp"
                    android:layout_height="15dp"
                    android:background="@drawable/check_24"
                    />


            </androidx.cardview.widget.CardView>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:textColor="@android:color/black"
                android:text="minimum one uppercase"
                android:gravity="center|start"
                android:layout_marginStart="10dp"
                android:layout_marginEnd="10dp"

                android:layout_marginLeft="10dp" />

        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="30dp"
            android:layout_marginTop="10dp"
            android:gravity="center"
            android:orientation="horizontal">

            <androidx.cardview.widget.CardView
                android:id="@+id/card4"
                android:layout_width="20dp"
                android:layout_height="20dp"
                app:cardBackgroundColor="#dcdcdc"
                app:cardCornerRadius="25dp"
                android:layout_gravity="center">

                <ImageView
                    android:layout_gravity="center"
                    android:layout_width="15dp"
                    android:layout_height="15dp"
                    android:background="@drawable/check_24"
                    />


            </androidx.cardview.widget.CardView>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:textColor="@android:color/black"
                android:text="minimum one special symbol"
                android:gravity="center|start"
                android:layout_marginStart="10dp"
                android:layout_marginEnd="10dp"

                android:layout_marginLeft="10dp" />

        </LinearLayout>

        <androidx.cardview.widget.CardView
            android:id="@+id/cardsignup"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:layout_marginTop="20sp"
            app:cardBackgroundColor="#dcdcdc">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:textSize="20sp"
                android:textStyle="bold"
                android:text="Sign Up"
                android:textColor="@android:color/black"
                android:gravity="center"/>

        </androidx.cardview.widget.CardView>


    </LinearLayout>

</androidx.core.widget.NestedScrollView>

As you can see in above Ui Screenshot we have 3 EditText, 4 Cardview with a tick Icon and a Button.

Step 4 : Java Coding to Handle password Validation

In Below Java code we have 2 method one to check passwordValidation() and other to keep track of InputChanged() in TextField.

MainActivity.java

package com.example.passwordcharactervalidation;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;

public class MainActivity extends AppCompatActivity {

    EditText etfullname,etEmail,etPassword;

    CardView card1,card2,card3,card4,cardButtonSignUp;

    private  boolean is8char=false, hasUpper=false, hasnum=false, hasSpecialSymbol =false, isSignupClickable = false;

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

        etfullname=(EditText) findViewById(R.id.etFullname);
        etEmail = (EditText)findViewById(R.id.etEmail);
        etPassword = (EditText)findViewById(R.id.etPassword);

        card1 = (CardView)findViewById(R.id.card1);
        card2 = (CardView)findViewById(R.id.card2);
        card3 = (CardView)findViewById(R.id.card3);
        card4 = (CardView)findViewById(R.id.card4);
        cardButtonSignUp = (CardView)findViewById(R.id.cardsignup);


        cardButtonSignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        inputChanged();
    }

    @SuppressLint("ResourceType")
    private void passwordValidate(){
        String name = etfullname.getText().toString();
        String email = etEmail.getText().toString();
        String password = etPassword.getText().toString();


        if(name.isEmpty())
        {
            etfullname.setError("Please Enter Full name ");
        }

        if(email.isEmpty())
        {
            etEmail.setError("Please Enter Email ");
        }

        // 8 character
        if(password.length()>= 8)
        {
            is8char = true;
            card1.setCardBackgroundColor(Color.parseColor(getString(R.color.colorAccent)));
        }else{
            is8char = false;
            card1.setCardBackgroundColor(Color.parseColor(getString(R.color.colorGrey)));
        }

        //number
        if(password.matches("(.*[0-9].*)"))
        {
            hasnum = true;
            card2.setCardBackgroundColor(Color.parseColor(getString(R.color.colorAccent)));
        }else{
            hasUpper = false;
            card2.setCardBackgroundColor(Color.parseColor(getString(R.color.colorGrey)));
        }
        //upper case
        if(password.matches("(.*[A-Z].*)"))
        {
            hasUpper = true;
            card3.setCardBackgroundColor(Color.parseColor(getString(R.color.colorAccent)));
        }else{
            hasUpper = false;
            card3.setCardBackgroundColor(Color.parseColor(getString(R.color.colorGrey)));
        }

        //symbol
        if(password.matches("^(?=.*[_.()$&@]).*$")){
            hasSpecialSymbol = true;
            card4.setCardBackgroundColor(Color.parseColor(getString(R.color.colorAccent)));
        }else{
            hasSpecialSymbol = false;
            card4.setCardBackgroundColor(Color.parseColor(getString(R.color.colorGrey)));
        }
//
    }

    private  void inputChanged(){

        etPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @SuppressLint("ResourceType")
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                passwordValidate();
                if(is8char && hasnum && hasSpecialSymbol && hasUpper)
                {
                                      cardButtonSignUp.setCardBackgroundColor(Color.parseColor(getString(R.color.colorPrimary)));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
//
        });
//
    }
}

Final Output

android password field validation