Home Blog Page 79

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

 

How to Show Snackbar in Flutter

0
how to show snackbar in flutter

Hi Guys, Welcome to Proto Codes Point, In this flutter tutorial we check how to show snackbar in flutter app development.

What is Snackbar?

A Flutter Snackbar is Quick Information to the user of your application. Using material design snackbar you can give a quick message, error or warning message to the app user,

One of the best and the most useful way of showing message or notification is by using Flutter Material Snackbar.

Video Tutorial 

ScaffordMessenger – scaffold.of(context) error solution

How to Show Snackbar?

Step 1: Create a new Project

Of course, you need to create a new Flutter project in Android Studio or VSCode whichever is your favourite IDE.

Step2: Initialise a global key scaffold

Create a stateful class and declare a Global key scaffold state

final GlobalKey<ScaffoldState> _globalKey = GlobalKey<ScaffoldState>();

Step 3: Create a method of Snackbar bar

void _showSnackbar() {
   final snack = SnackBar(
     content: Text("This is Snackbar Example"),
     duration: Duration(seconds: 15),
     backgroundColor: Colors.green,
   );

   _globalKey.currentState.showSnackBar(snack);
  }

Step 4: Call the method to show snackbar

Then, ok to call the method _showSnackbar we will make use of the RaisedButton widget in a flutter, when it is been pressed the method is been called and this method will showSnackBar using scaffordState globalkey.

RaisedButton(
              onPressed: () {
                _showSnackbar();  // calling the method on pressed
              },
              child: Text("Click me"),
            
),

1st. Way using _globalKey.currentState – Show Snackbar in flutter App

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(

        primarySwatch: Colors.blue,

        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: Snackbar(),
    );
  }
}

class Snackbar extends StatefulWidget {
  @override
  _SnackbarState createState() => _SnackbarState();
}

class _SnackbarState extends State<Snackbar> {

  final GlobalKey<ScaffoldState> _globalKey = GlobalKey<ScaffoldState>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _globalKey,
      appBar: AppBar(title: Text("Flutter Snackbar Example"),),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text("press to show Snackbar"),
            RaisedButton(
              onPressed: () {
                _showSnackbar();
              },
              child: Text("Click me"),
            )
          ],
        ),
      ),
    );
  }

  void _showSnackbar() {
   final snack = SnackBar(
     content: Text("This is Snackbar Example"),
     duration: Duration(seconds: 15),
     backgroundColor: Colors.green,
   );

   _globalKey.currentState.showSnackBar(snack);
  }
}







2nd. Way using ScaffoldMessenger.of(context).showSnackBar

Show Snackbar in flutter using ScaffoldMessenger.of(context).shotSnackbar(snackbar);

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: SnackBarExample(),
    );
  }
}

class SnackBarExample extends StatefulWidget {
  @override
  _SnackBarExampleState createState() => _SnackBarExampleState();
}

class _SnackBarExampleState extends State<SnackBarExample> {

  //creating an instance of Snackbar to use it in scaffoldMessenger
  final snackBar = SnackBar(content: Text('New Way to show snackbar'),duration: Duration(seconds:1 ),action: SnackBarAction(
    onPressed: (){

    }, label: 'Button',
  ),);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child:Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            EButton(),
            ElevatedButton(onPressed: (){
            // using ScaffoldMessenger
              ScaffoldMessenger.of(context).showSnackBar(snackBar);
            }, child: Text('New Snackbar')),
          ],
        ),
      ),
    );
  }
}

Conclusion

Yes, Flutter provides its own Snackbar, but the only drawable of default is it create lots of boilerplate code and is not as customizable, so making use of the Flutter Flushbar library will remove this drawable and you can easily style as per your creativity that too without any scaffold.

This library is useful when you want to show more than a simple message.