Home Blog Page 81

Create API using Deno js & Display data in Flutter Listview builder

0
flutter deno js example

Hi Guys, Welcome to Proto Coders Point, In this tutorial, we will create our own API server using DENO JS scripting language and we will also create a flutter app that will fetch image data from our Deno API server script and display the Images in flutter deno application by making use of Flutter Builder and ListView Builder.

flutter deno api example

Brief Introduction on what is DENO ?

Deno is new Implementation of Node.js, We can call it as alternative of Node.js, The Creator of Deno and Node.js is the same “Ryan Dahl“, He it the original Creator of Node.js.

A Deno is a runtime JavaScript and TypeScript that is built on Version 8 of JavaScript engine and Deno is writter in Rust Programming language.

Creating API server using Deno Script | Deno js tutorial

Video Tutorial to create deno API

Step 1: Editor VSCode or Atom

I prefer to make use of vscode editor or Atom editor to write back-end scripts.

In my case i am using vscode editor.

Step 2: Create New project / New Folder

File > Open Folder (new folder) > “deno http server”

creating new folder in vscode

Then, Select Folder.

Step 3: Creating .ts files under deno http server folder

In vscode go to Files > New File  here create 2 files and name it as index.ts and ImageData.ts

Step 4: index.ts deno script code and ImageData.ts

Then, In index.ts file copy paste the below lines of deno code

index.ts

// we need denotrain module to create routes and application
import { Application, Router } from "https://deno.land/x/denotrain@v0.5.0/mod.ts";
import { imagedata } from "./imagesdata.ts";

const app = new Application({hostname:"192.168.0.7"}); // replace with you localhost IP Address

const routes = new Router();
// lets create router to the api server

app.use("/api",routes);

routes.get("/imagedata",(ctx)=>{
 return {
     // lets pass imagesdata interface here
     "imagedata":imagedata
 }
});

app.get("/",(ctx)=>{
 return "Hello World";
});  //this is the root of the server

await app.run(); // then finally run the app  press ctrl + ` to open terminal

ImageData.ts

interface Images{
    url:String;
}

export const imagedata : Array<Images> = [
    {
        "url":"https://images.wallpapersden.com/image/download/aladdin-2019-movie-banner-8k_65035_2560x1440.jpg",
    },
    {
        "url":"https://thumbor.forbes.com/thumbor/960x0/https%3A%2F%2Fblogs-images.forbes.com%2Fscottmendelson%2Ffiles%2F2017%2F07%2FJustice-League-SDCC-Banner.jpg",
    },
    {
        "url":"https://c4.wallpaperflare.com/wallpaper/869/847/751/movies-hollywood-movies-wallpaper-preview.jpg",
    },
    {
        "url":"https://www.pixel4k.com/wp-content/uploads/2018/09/x-men-days-of-future-past-banner_1536361949.jpg",
    },
    {
        "url":"https://images.wallpapersden.com/image/download/aquaman-2018-movie-banner-textless_63348_4000x1828.jpg",
    },
]

then, make sure you have saved both the files.

Step 5: Run the Deno Script to start the server

open terminal in your editor,

How to open terminal in editor?

press ctrl + ` to open terminal

Then run the deno js script using below command

deno run --allow-net index.ts

After running the command, your deno script API data we be serving at your hostname as show in below screenshot.

how to run deno script

My Deno script Imagedata router url is http://192.168.0.7:3000/api/imagedata

Deno will server me json format of Image Urls that i will be using in my Flutter application to load those image URL.

deno server api

Now we are done with Creating our own API using Deno Script.

Creating Flutter Application to Display Image in ListView Builder | Flutter Deno Example

Flutter Deno Example Video Tutorial

Step 1: Create a new Flutter Project

I am making Android Studio as my IDE to build Flutter Application

create a new Flutter Project in android studio and name the project as “Flutter Deno Example” or anything as per your choice.

Step 2: Add flutter http dependencies

As we are we are making network call we need to use flutter http library to fetch data from our deno api server.

open pubspec.yaml file and add the flutter http library under dependencies section.

http: ^0.12.1  #kindly check official site for latest version

Step 3: Method to Fetch Image Data from Server

//function to fetch image data from deno script server
fetchImageData() async{
  final url = "http://192.168.0.7:3000/api/imagedata";  // replace with your IP url
  var res = await http.get(url);
  return jsonDecode(res.body)["imagedata"];
}

The above method is making use of http call to get data from deno script and return data in json decoded format.

Step 4 : Display image Data using Future builder and Listview widget

This is just a snipcode, Complete flutter code is given at the end.

FutureBuilder(
        future: fetchImageData(),
        builder: (context,snapshot){
          if(snapshot.connectionState == ConnectionState.done)
            {
              if(snapshot.hasData)
                {
                  return ListView.builder(itemBuilder: (context,index){
                    return ClipRRect(
                      borderRadius: BorderRadius.circular(8.0),
                      child: Image.network(snapshot.data[index]["url"],fit: BoxFit.cover,),
                    );
                  },itemCount: snapshot.data.length,);
                }
            }else if (snapshot.connectionState == ConnectionState.none)
              {
                return Text("Something went Wrong");
              }
          return CircularProgressIndicator();
        },
      ),

In above Flutter code we are making use of:

FutureBuilder : Making use of FutureBuilder because loading/fetching data from server may take some time. Here  snapshot will hold all the data received from server.

Until data from server is completely loaded we will display CircularProgressIndicator() and once data is received we will show the data using ListView.builder that has Image widget to load url.

Complete Flutter Source Code | Flutter Deno Example

Copy paste below lines of Flutter Deno Example Source in main.dart file.

main.dart

import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;


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: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 20.0),
      height: 200.0,
      child: FutureBuilder(
        future: fetchImageData(),
        builder: (context,snapshot){
          if(snapshot.connectionState == ConnectionState.done)
            {
              if(snapshot.hasData)
                {
                  return ListView.builder(itemBuilder: (context,index){
                    return ClipRRect(
                      borderRadius: BorderRadius.circular(8.0),
                      child: Image.network(snapshot.data[index]["url"],fit: BoxFit.cover,),
                    );
                  },itemCount: snapshot.data.length,);
                }
            }else if (snapshot.connectionState ==ConnectionState.none)
              {
                return Text("Something went Wrong");
              }
          return CircularProgressIndicator();
        },
      ),
    );
  }
}

//function to fetch image data from deno script server
fetchImageData() async{
  final url = "http://192.168.0.7:3000/api/imagedata";
  var res = await http.get(url);
  return jsonDecode(res.body)["imagedata"];
}


Done now your Flutter applications is ready to fetch data from your own deno API script.

Recommended Article

how to install deno js – Deno Hello World Example

How to install Deno in Windows | Basic of Deno Script HTTP server

0
install deno js deno script http server hello world
install deno js deno script http server hello world

Hi Guys, Welcome to Proto Coders Point, In this tutorial, we will install Deno JS in Windows OS & learn some basics of denojs scripting language.

What is Deno? Who is the creator of Deno?

Deno is the new Implementation of Node.js, We can call it an alternative of Node.js, The Creator of Deno and Node.js is the same Ryan Dahl“, He is the original Creator of Node.js. A Deno is a runtime JavaScript and TypeScript that is built on Version 8 of the JavaScript engine and Deno is written in Rust Programming language. Deno explicitly takes on the role of both runtime and package manager within a single executable, rather than requiring a separate package-management program. Ryan Dahl during his talk says “10 Things I Regret About Node.js” ( You can Watch His talk in below video )

and is intended to fix design problems in Node.js, Ok so straight Start Installing Deno on Windows OS.

How to Install Deno on Windows?

Note: This steps are only for windows user.

Video Tutorial Watch :

Step 1: Scoop/Chocolatey must be Installed

You required any of this Scoop or Chocolatey that will help you in Installing Deno on windows,

a) How to install Scoop on windows

Run Command Prompt as Admin:  just copy paste below lines of commands & hit enter.

@"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "[System.Net.ServicePointManager]::SecurityProtocol = 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://get.scoop.sh'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%\scoop\bin"
scoop install

This will install Scoop on your windows OS.

b) How to install Chocolaty on windows

Run Command Prompt as Admin:  just copy paste below lines of commands & hit enter.

@"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "[System.Net.ServicePointManager]::SecurityProtocol = 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"

This will install Chocolaty on your OS.

Step 2: Install Deno using Scoop or Chocolately.

After you have installed scoop or chocolately, now you can use then to install deno 

Then in Command Prompt just enter any of the below command.

scoop install deno
installing deno using scoop

OR

choco install deno

Step 4 : Test Deno

Then,Once you install deno, you to check if deno is installed successfully just in command prompt type : deno, This will run deno.

deno execution

In above Screenshoot, i have used deno to perform basic arithmetic operations.

Deno script to perform basic HTTP server

Use any Code Editor, In my Case, I am making use of VSCode to write my Deno Script. This Script is will basically print “Hello World” text on the Browser screen.

In VSCode editor Create a new Folder and name it as “Deno_http_server”.

vs code creating new folder for deno http server

Under this folder you need to create a new index.ts file

creating file in vscode for deno scripting

Copy the Below Deno Script HTTP server ” deno Hello World” in index.ts

import { serve } from "https://deno.land/std@0.50.0/http/server.ts";
const s = serve({ port: 8000 });
console.log("http://localhost:8000/");
for await (const req of s) {
  req.respond({ body: "Hello World\n" });
}

Ok then, to run this index.tx file.

Open Terminal in VsCode itself by pressing ctrl + Then run below command,

deno run --allow-net index.ts

screenshot example:

how to run deno script

Output

deno hello world output
deno hello world output

Related Article

Creating API using DENOJS & display listview in flutter app

Flutter Video Player Widget Tutorial

0
flutter video player widget plugin

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we will build a Flutter application by making use of Flutter Video Player Widget Plugin to display/play videos in our Flutter App with example.

Introduction to video player flutter widget

Flutter Video Player is a plugin developed by the flutter team for Android, iOS, and Web development so that developers can easily make use of this video pkg widget library in integrating playing videos in their apps.

Important Note: As mentioned in official site that, This plugin is still under development, some latest API version of this video player library may give some kind of bugs.

let’s Start with installation of this widget in our flutter project

Flutter Video Player Widget Tutorial

Video Tutorial

Step 1: Create a new Project

offCourse you need to create a new Flutter Project or Open any existing project, all depends to you.

In my case, I m making use of Android Studio to Develop Flutter application.

Files > New > New Flutter Project

Step 2: Installation of Video Player Plugin

Adding dependencies

Open pubspec.yaml file and add the below video_player flutter dependencies version

dependencies:
  video_player: ^2.1.1 // version might change so check the official site

Import the video_player.dart

Once you have added the video player plugin, now you will be able to use video pkg by importing the library file where required.

import 'package:video_player/video_player.dart';

In my case i have imported video_player.dart file in main.dart file

Step 3: Adding Internet permission in android and iOS

Android

Please make sure to add the following Internet permission in your Android project manifest file.

Naviget to : <project root>/android/app/src/main/AndroidManifest.xml:

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

The Flutter project template adds it, so it may already be there.

iOS

For iOS devices Navigate to <project root>/ios/Runner/Info.plist:

<key>NSAppTransportSecurity</key>
<dict>
  <key>NSAllowsArbitraryLoads</key>
  <true/>
</dict>

and just add the above keys.

Step 4 : Network configuration android version 9 ( Optional )

This Step is optional, do this only if you are facing any problem in loading the video.

Create a directory names ” xml ” under the following path:

<project root>/android/app/src/main/res

In this xml folder you need to create a new xml resource file  

xml(dir) > (Right click) New > xml Resource file > and name the file as networkconfig.xml

Then, add the following Network Config code:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">commondatastorage.googleapis.com</domain>  //here replace with you localhost server or your domain name
    </domain-config>
</network-security-config>

Here is example of the directory structure:

network config android

Step 5 : The Complete Code for Flutter Video Player

main.dart 

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {

  VideoPlayerController controller; // used to controller videos
  Future<void> futureController;  // network takes time to load video, so to control future video data

  @override
  void initState() {

    //url to load network
    controller = VideoPlayerController.network("http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4");
    futureController = controller.initialize();

    controller.setLooping(true);  // this will keep video looping active, means video will keep on playing
    controller.setVolume(25.0);  // default  volume to initially play the video 
    super.initState();

  }

  @override
  void dispose() {
    controller.dispose();  // when app is been closed destroyed the controller
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar:  AppBar(
        title: Text("Flutter Video Player Example"),
      ),
      body: Column(
        children: <Widget>[
          Center(
            child: FutureBuilder(
              future: futureController,
              builder: (context,snapshot){
                // if video to ready to play, else show a progress bar to the user
                if(snapshot.connectionState == ConnectionState.done)
                  {
                    return AspectRatio(
                      aspectRatio: controller.value.aspectRatio,
                      child: VideoPlayer(controller)
                    );
                  }else{
                    return Center(child: CircularProgressIndicator(),);
                }
                
              },
            ),
          ),
          //button to play/pause the video
          RaisedButton(
            color: Colors.transparent,
            child: Icon(
              controller.value.isPlaying? Icons.pause : Icons.play_arrow
            ),
            onPressed: (){
              setState(() {
                if(controller.value.isPlaying)
                  {
                    controller.pause();
                  }
                else
                  {
                    controller.play();
                  }
              });
            },
          )
        ],
      )
    );
  }
}

Text Recognition Using Firebase ML Kit – Text Recognition in Android.

0

Hi Guys, Welcome to Proto Coders Point, In this android tutorial we will build an application that can recognize text in image with Firebase ML Kit.

Introduction to Firebase Machine Learning(ML) Kit

Firebase ML Kit is an mobile SDK that helps you in building an android or iOS apps that can help developer to add Machine Learning feature into there mobile application, This ML Kit is very powerfull and very easy to use.

Whether you’re new to Machine Learning or you have experienced in ML, you can easily implement the ML functionality that you need that too in just few lines of firebase ML Codes.

So as the title says that we gonna build an simple application that can read text from a image and display it to use.

RESULT OF FINAL OUTPUT OF APPLICATION

firebase ml kit text recognition android example

Firebase ML Kit text Recognition

Let’s start this Firebase ML Kit Android Project to read text from image, Just follow the below Steps

Step 1: Create a new android project in android studio

ofcourse you need to create a new android project or you may just open any existing android project

File > New > New Project ( here select Empty Activity )

creating new project image

Hit Next Button

Then Give a Good name to your android project, In my case i have named it as “TextRecognitionMLFirebase” you may name it as per your choice

Then, Hit the Finish Button, your android project will get built in few minutes.

Step 2 : Connect your android app to firebase console

First you  need to be signedIn with Google Account in your android Studio.

Then, Go to Tools > Firebase  a Android Assistant will open a side window from where you can connect your app to firebase console. Here select Analytics

firebase analytic

connect to firebase

In place of Connected in above image you may see Connect to Firebase Button, Click on it and it will open a default Browser so that you can connect android application to firebase console, Then In browser you need to follow some steps

 1: Add project

Now, on your browser with Firebase website opened click on Add Project

This page will get Loaded

adding android project to firebase console
Project Name will automatically get here you just need to hit Continue button

2: Config Google Analysis

adding android project to firebase console configuration google analysis

Here you need to accept all the terms and conditions of firebase console & then Hit Create Project.

Therefore your android studio project is successfully connected  to Firebase Console

firebase project is connected to android project

Now, Come back to Android Studio IDE.

Step 3 : Add Firebase Dependencies

Add Firebase ml vision and firebase core dependencies into yor android studio project.

Open built.gradle(Module:app)  then in dependencies section just add below Implementation code

implementation 'com.google.firebase:firebase-core:15.0.2'

implementation 'com.google.firebase:firebase-ml-vision:15.0.0'

Step 4 : Adding Camera Feature

Open Androidmanifest.xml and add the following required camera Feature permission

<uses-feature android:name="android.hardware.camera" android:required="true"/>

Step 5 : XML UI Design

Now it’s time to work with some UI Design for Text Recognition in android

open activity_main.xml  and add the below lines of XML code

<?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:orientation="vertical">

 <ImageView
     android:id="@+id/imageview1"
     android:layout_gravity="center"
     android:layout_width="match_parent"
     android:layout_height="400dp"
     />

    <TextView
        android:id="@+id/text1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:textSize="20dp"
        android:text="Display the text from the image"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/captureImage"
        android:text="Capture Image"
        />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/detectText"
        android:text="Detect Text"/>
</LinearLayout>

Above xml code has :

ImageView to display image captured by camera.

TextView to display text read by Firebase ML Kit.

Button 1 to Open Camera to capture image from camera

Button 2 to read or detect text from captured image.

Step 6 : Java Coding for firebase ML Kit Text Recognition

Open MainActivity.java  and copy paste below code

package com.example.textrecognitionmlfirebase;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.ml.vision.FirebaseVision;
import com.google.firebase.ml.vision.common.FirebaseVisionImage;
import com.google.firebase.ml.vision.text.FirebaseVisionText;
import com.google.firebase.ml.vision.text.FirebaseVisionTextDetector;
import java.io.ByteArrayOutputStream;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    Button captureImage,DetectText;
    ImageView imageView1;
    TextView text1;
    static  final int REQUEST_IMAGE_CAPTURE = 1;
    Bitmap imageBitmap;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // initialization of Views
        captureImage = (Button)findViewById(R.id.captureImage);
        imageView1 = (ImageView)findViewById(R.id.imageview1);
        DetectText = (Button)findViewById(R.id.detectText);
        text1 = (TextView)findViewById(R.id.text1);

        //on button click open camera to capture image
        captureImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if(takePictureIntent.resolveActivity(getPackageManager())!=null){
                    startActivityForResult(takePictureIntent,REQUEST_IMAGE_CAPTURE);
                }
            }
        });

        //on click read the text from captured image
        DetectText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DetectTextFromImage();
            }
        });
    }

    private void DetectTextFromImage() {
        //read bitmap image
        FirebaseVisionImage firebaseVisionImage = FirebaseVisionImage.fromBitmap(imageBitmap);
        //text detector from selected image 
        FirebaseVisionTextDetector textDetector = FirebaseVision.getInstance().getVisionTextDetector();

        textDetector.detectInImage(firebaseVisionImage).addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() {
            @Override
            public void onSuccess(FirebaseVisionText firebaseVisionText) {

                List<FirebaseVisionText.Block> blockList = firebaseVisionText.getBlocks();
                if(blockList.size()==0){
                    Toast.makeText(MainActivity.this,"No Text Found no images",Toast.LENGTH_LONG).show();
                }
                else{
                    for(FirebaseVisionText.Block block : firebaseVisionText.getBlocks())
                    {
                        String text = block.getText();
                        //set text to textview 
                        // that is been read from imagebitmap
                        text1.setText(text);
                    }
                }
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(MainActivity.this,"Something Went Wrong",Toast.LENGTH_LONG).show();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Bundle extras  = data.getExtras();
        imageBitmap = (Bitmap) extras.get("data");

        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        // camera captured image set to ImageView
        imageView1.setImageBitmap(imageBitmap);
    }
}

And there you go your app is ready to recognize text in image with ML Kit on android application.

Scratch Card like google pay reward card in android studio

0
Scratch card like google pay reward card in android application

Hi Guys, Welcome to Proto Coders Point, In this Android Tutorial we will implement Scratch Card in android studio,  an android app same like Google Pay(Tez app) reward scratch card in our android application.

I found the Source code in GitHub developed by Shubham Mahalkar, Credit to him

Result of the Final built app

scratch card reward google pay android studio

Scratch Card like google pay reward card in android studio

Step 1 : Create a new android project in android studio

offcourse you need to create a new android project or open any of your existing android project where you want to add Scratch card reward.

Give a name to your android project as “Scratch Card Google Pay” or anything as per you choice.

Step 2 : create a attrs xml file in values folder

go to res->values-> and create new file name it as attrs.xml

then copy paste below lines of code

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

    <declare-styleable name="ScratchCard">
        <attr
            name="scratchDrawable"
            format="reference|color" />
        <attr
            name="scratchWidth"
            format="dimension" />
    </declare-styleable>

</resources>

Step 3 : Create a java class ScratchCard.java

This class is used to create Graphical objects in xml layout. Even this class will keep track of any event happens such as user scratch the card to check his reward points.

We will implement this class in xml file to display a square box which we will be able to check the google pay reward point after the card is been scratched.

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

class ScratchCard extends View {
    private Drawable mDrawable;
    private float mScratchWidth;
    private Bitmap mBitmap;
    private Canvas mCanvas;
    private Path mPath;
    private Paint mInnerPaint;
    private Paint mOuterPaint;
    private OnScratchListener mListener;

    public interface OnScratchListener {
        void onScratch(ScratchCard scratchCard, float visiblePercent);
    }

    public ScratchCard(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        resolveAttr(context, attrs);
    }

    public ScratchCard(Context context, AttributeSet attrs) {
        super(context, attrs);
        resolveAttr(context, attrs);
    }

    public ScratchCard(Context context) {
        super(context);
        resolveAttr(context, null);
    }

    private void resolveAttr(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ScratchCard);
        mDrawable = typedArray.getDrawable(R.styleable.ScratchCard_scratchDrawable);
        mScratchWidth = typedArray.getDimension(R.styleable.ScratchCard_scratchWidth, Utils.dipToPx(context, 70));
        typedArray.recycle();
    }

    public void setOnScratchListener(OnScratchListener listener) {
        mListener = listener;
    }

    @Override
    protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
        super.onSizeChanged(width, height, oldWidth, oldHeight);

        if (mBitmap != null)
            mBitmap.recycle();

        mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        mCanvas = new Canvas(mBitmap);

        if (mDrawable != null) {
            mDrawable.setBounds(0, 0, mBitmap.getWidth(), mBitmap.getHeight());
            mDrawable.draw(mCanvas);
        } else {
            mCanvas.drawColor(0xFFEC7063);
        }

        if (mPath == null) {
            mPath = new Path();
        }

        if (mInnerPaint == null) {
            mInnerPaint = new Paint();
            mInnerPaint.setAntiAlias(true);
            mInnerPaint.setDither(true);
            mInnerPaint.setStyle(Paint.Style.STROKE);
            mInnerPaint.setFilterBitmap(true);
            mInnerPaint.setStrokeJoin(Paint.Join.ROUND);
            mInnerPaint.setStrokeCap(Paint.Cap.ROUND);
            mInnerPaint.setStrokeWidth(mScratchWidth);
            mInnerPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
        }

        if (mOuterPaint == null) {
            mOuterPaint = new Paint();
        }
    }

    private float mLastTouchX;
    private float mLastTouchY;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float currentTouchX = event.getX();
        float currentTouchY = event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mPath.reset();
                mPath.moveTo(event.getX(), event.getY());
                break;
            case MotionEvent.ACTION_MOVE:
                float dx = Math.abs(currentTouchX - mLastTouchX);
                float dy = Math.abs(currentTouchY - mLastTouchY);
                if (dx >= 4 || dy >= 4) {
                    float x1 = mLastTouchX;
                    float y1 = mLastTouchY;
                    float x2 = (currentTouchX + mLastTouchX) / 2;
                    float y2 = (currentTouchY + mLastTouchY) / 2;
                    mPath.quadTo(x1, y1, x2, y2);
                }
                break;
            case MotionEvent.ACTION_UP:
                mPath.lineTo(currentTouchX, currentTouchY);
                if (mListener != null) {
                    int width = mBitmap.getWidth();
                    int height = mBitmap.getHeight();
                    int total = width * height;
                    int count = 0;
                    for (int i = 0; i < width; i += 3) {
                        for (int j = 0; j < height; j += 3) {
                            if (mBitmap.getPixel(i, j) == 0x00000000)
                                count++;
                        }
                    }
                    mListener.onScratch(this, ((float) count) / total * 9);
                }
                break;
        }

        mCanvas.drawPath(mPath, mInnerPaint);
        mLastTouchX = currentTouchX;
        mLastTouchY = currentTouchY;

        invalidate();
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawBitmap(mBitmap, 0, 0, mOuterPaint);
        super.onDraw(canvas);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mBitmap != null) {
            mBitmap.recycle();
            mBitmap = null;
        }
    }
}

STEP 4 : Create a new Utils.java file

Utils.java this class will help you randomly generate as number from 1 – 100 and we will be able to display in a form of rewards point some like google Play app.

Utils.java

import android.content.Context;

import java.util.Random;

public class Utils {
    static Random random = new Random();

    public static float dipToPx(Context context, float dipValue) {
        float density = context.getResources().getDisplayMetrics().density;
        return dipValue * density;
    }


    //Generate random number(Prize)
    private static String generateCodePart(int min, int max) {
        int minNumber = 1;
        int maxNumber = 100;
        return String.valueOf((random.nextInt((maxNumber - minNumber) + 1) + minNumber));
    }

    public static String generateNewCode() {
        String firstCodePart = generateCodePart(1000, 9999);
        return "You Won\nRs." + firstCodePart;
    }
}

Step 5: Now Open activity_main.xml file and add the below lines of code

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

    <View
        android:id="@+id/view"
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:layout_gravity="center"
        android:background="@color/colorPrimaryDark"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <LinearLayout
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:gravity="center"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

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

        <TextView
            android:id="@+id/codeTxt"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="15dp"
            android:gravity="center"
            android:textColor="@android:color/white"
            android:textSize="30sp" />

    </LinearLayout>

    <com.example.androidscratchcard.ScratchCard
        android:id="@+id/scratchCard"
        android:layout_width="300dp"
        android:layout_height="300dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnScratchAgain"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="scratch again to get reward"
        android:textColor="@android:color/black"
        android:textSize="18sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/view" />

</androidx.constraintlayout.widget.ConstraintLayout>

” you just need to replace with package name with your android project package name” as shown below

scratchcard android studio

Step 6 : The Final Step add code in MainActivity.java

Then Now open MainActivity.java and add the below lines of code

package com.example.androidscratchcard;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private ScratchCard mScratchCard;
    TextView codeTxt;
    String number;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mScratchCard = findViewById(R.id.scratchCard);
        codeTxt = findViewById(R.id.codeTxt);
        number = codeTxt.getText().toString();
        codeTxt.setText(number);
        codeTxt.setText(Utils.generateNewCode());

        findViewById(R.id.btnScratchAgain).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                startActivity(getIntent());
            }
        });
    }

    private void scratch(boolean isScratched) {
        if (isScratched) {
            mScratchCard.setVisibility(View.INVISIBLE);
        } else {
            mScratchCard.setVisibility(View.VISIBLE);
        }
    }

    private void handleListeners() {
        mScratchCard.setOnScratchListener(new ScratchCard.OnScratchListener() {
            @Override
            public void onScratch(ScratchCard scratchCard, float visiblePercent) {
                if (visiblePercent > 0.8) {
                    scratch(true);
                }
            }
        });
    }
}

You are all set to run your application, Kindly feel free to ask questions in comments  section.

 

Automatically SMS OTP reading using Broadcast Receiver in android studio

1
Automatically SMS OTP reader using Broadcast Receiver in android studio
Automatically SMS OTP reader using Broadcast Receiver in android studio

Hi Guys, Welcome to Proto Coders Point, In this Android Tutorial we will build an android application that will be able in reading incoming message automatically in android to verify otp.

FINAL OUTPUT OF READING OTP AUTOMATICALLY

Automatically SMS OTP reader using Broadcast Receiver in android studio

Video Tutorial on How to auto read otp in android using Breadcast Receiver.

At the end of this android tutorial your app will be able the read sms and fetch all the text in that sms and then it will copy the OTP from SMS and paste it in EditText box.

So let’s begin implementation of otp sms reader

Create a new Android Project

Ofcourse you need to create a new android project or open any existing android project

To do so go to File > New > New Project

Give a name as per you need in my case i have names my application as “Auto sms otp reader”

Create a custom background for EditText and a Vector Image

1. edittextbackground.xml

create a new xml file in drawable folder

res > drawable(right click) > New > Drawable resource file

copy paste below xml code

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

    <corners android:radius="5dp"/>
    <solid android:color="#dcdcdc"/>

</shape>

2. Create a Vector Image

res > drawable (right click) > New > Vector Asset

a dialog box will appear on your screen as shown below

How to create Vector image asset on android studio

Then, Here you can select any kind of image clip Art.

Create a new Java Class names OTPReceiver

OTPReceiver.java

package com.example.autosmsotpreader;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.provider.Telephony;
import android.telephony.SmsMessage;
import android.widget.EditText;

public class OTP_Receiver extends BroadcastReceiver {
    private  static EditText editText;

    public void setEditText(EditText editText)
    {
        OTP_Receiver.editText=editText;
    }

// OnReceive will keep trace when sms is been received in mobile
    @Override
    public void onReceive(Context context, Intent intent) {
        //message will be holding complete sms that is received
        SmsMessage[] messages = Telephony.Sms.Intents.getMessagesFromIntent(intent); 

        for(SmsMessage sms : messages)
        {
  
            String msg = sms.getMessageBody();
            // here we are spliting the sms using " : " symbol
            String otp = msg.split(": ")[1]; 

            editText.setText(otp);
        }

    }
}

eg: sms received is Your OTP is : 4587, Then in above code i have split the complete message string in to 2 parts using “:” this special symbol.

Open AndroidManifest.xml file & add the uses permission

adding uses permission

add this 4 user-permission inside <manifest>  here </manifest> tags

<!-- this are the permission need so that application can read sms -->
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>
    <uses-permission android:name="android.permission.READ_PHONE_NUMBERS"/>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
    <uses-permission android:name="android.permission.WRITE_SMS"/>

Now, Add the following receiver OTPReceiver.java in manifest under <application> tag

<receiver android:name=".OTP_Receiver">
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
            </intent-filter>
</receiver>

as shown in the below screenshot

adding permission in android manifest xml

MainActivity.java

Copy paste the below lines of code in MainActivity.java

package com.example.autosmsotpreader;


import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.EditText;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;


public class MainActivity extends AppCompatActivity {

    EditText otpnumber;
    
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //we need to ask user permission to auto read sms
        requestsmspermission();
        otpnumber = (EditText)findViewById(R.id.edittext);

        new OTP_Receiver().setEditText(otpnumber);
    }

  
    private void requestsmspermission() {
        String smspermission = Manifest.permission.RECEIVE_SMS;
        int grant = ContextCompat.checkSelfPermission(this,smspermission);

        //check if read SMS permission is granted or not
        if(grant!= PackageManager.PERMISSION_GRANTED)
        {
            String[] permission_list = new String[1];
            permission_list[0]=smspermission;

            ActivityCompat.requestPermissions(this,permission_list,1);
        }
    }


}

Recommended Android Articles

otp verification in android

textlocal api to send sms/otp verification

android check internet connection continuously