Home Blog Page 58

Send SMS using text local an SMS GATEWAY – Android Studio Application

2
SMS GATEWAY Text local
Android Studio Application - Send SMS using text local an SMS GATEWAY

Hi, Guys Welcome to Proto Coders Point.

This Article will learn how to develop an android application that can send SMS or bulk SMS to mobiles number.

In this  Aritcle, we are going to make use  https://textlocal.in/ to send SMS from our android app.

What is Textlocal?

India’s No. 1 Bulk SMS Platform Increase sales and customer satisfaction with smarter SMS campaigns, instant OTPs, notifications, two-way interactions & other award-winning bulk SMS services. this SMS sender android application can we used to send promotional SMS, bill SMS, and much more SMS services in India.

What is SMS GATEWAY Services ?

An SMS Gateway enables a computer to send and receive SMS text messages to and from a SMS capable device over the global telecomunications network (normally to a mobile phone).

The SMS Gateway translates the message sent, and makes it compatible for delivery over the network to be able to reach the recipient.

Android App development to send SMS using text local an SMS GATEWAY || with source code

Android studio send sms to mobile number implementation video.

Developing an android application to send message to mobile number

So let’s begin implementation of android application development with TEXTLOCAL SMS GATEWAY SERVICES API.

Step by Step integration of android codes.

Textlocal Account 

  1. Creating a account in TextLocal.in
  2. Creating and getting a SMS API key in textlocal.

Android implementation Codes

  1. Creating a New Android Studio Project.
  2. Design a layout in main_activity.xml.
  3. writing java code in Main_Activity.java class.

Creating a account in TextLocal.in

To be able to send sms through textlocal.in SMS Gateway services you need to create an account under textlocal.in 

Creating an account in textlocal
Creating an account in textlocal
dashboard of textlocal sms gateway
dashboard of textlocal a sms gateway

Creating and getting a SMS API key in textlocal.

When you are in textlocal dashboard navigate Towards – > Settings -> API KEY.

Create a new SMS API key

creating a new SMS API KEY
creating a new SMS API KEY

You need to keep a note of the SMS API KEY you have generated just now, so that you can easily copy cost the sms api key in android studio project.

All set in textlocal website, we have now successfully created a account under textlocal and generated a API key.

Android Studio Implementation of SMS GATEWAY SERVICES

Complete project Source code is been listed down below, so that you can download the SMS sending project.

Now Let is  begin implementation the source code in android studio.

Creating a SMS sending project in android studio.

File -> New -> New Project ->select a empty activity

Design a layout in main_activity.xml.

Main_Activity.xml

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

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="SEND SMS"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.042" />

    <Button
        android:id="@+id/submit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="44dp"
        android:layout_marginBottom="420dp"
        android:text="Submit"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText2"
        app:layout_constraintVertical_bias="0.038" />

    <EditText
        android:id="@+id/number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:hint="Number"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <EditText
        android:id="@+id/msg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="136dp"
        android:ems="10"
        android:gravity="start|top"
        android:hint="Message"
        android:inputType="textMultiLine"
        app:layout_constraintBottom_toTopOf="@+id/submit"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Above xml code has 2 EditText and a Button

EditText1 is with ID number and EditText2 is with ID msg, that holds respectively mobile number and sms message to be sent.

Button is with ID Submit that fetch text from editext and send data to SMS gateway through SMS API key,

Writing java code in Main_Activity.java class

Main_Activity.java

package protocoderspoint.com.smsapi;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    Button submit;
    EditText number,msg;

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

        submit=(Button)findViewById(R.id.submit);
        number=(EditText)findViewById(R.id.number);
        msg=(EditText)findViewById(R.id.msg);


        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phono = number.getText().toString();
                String msgtext = msg.getText().toString();

                try {
                    // Construct data
                    String apiKey = "apikey=" + "Replace with your API KEY";
                    String message = "&message=" + msgtext;
                    String sender = "&sender=" + "TXTLCL";
                    String numbers = "&numbers=" + phono;

                    // Send data
                    HttpURLConnection conn = (HttpURLConnection) new URL("https://api.textlocal.in/send/?").openConnection();
                    String data = apiKey + numbers + message + sender;
                    conn.setDoOutput(true);
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Content-Length", Integer.toString(data.length()));
                    conn.getOutputStream().write(data.getBytes("UTF-8"));
                    final BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    final StringBuffer stringBuffer = new StringBuffer();
                    String line;
                    while ((line = rd.readLine()) != null) {
                        stringBuffer.append(line);

                        Toast.makeText(MainActivity.this,line,Toast.LENGTH_LONG).show();
                    }
                    rd.close();


                } catch (Exception e) {
                    System.out.println("Error SMS "+e);

                }
            }
        });

        StrictMode.ThreadPolicy st = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(st);
    }
}

In the above java class code we have four parameter that should be passed to textlocal gateway service.

  1. SMS API KEY.
  2. MESSAGE ( Fetched from EditText box ).
  3. SENDER ( It should be ‘TXTLCL’).
  4. Numbers ( Fetched from EditText box ).

Numbers can be seperated with commas (,) Eg: 875877XXX,548848xxx,66652xxx4454. So that we can send bulk sms at a time.

Conclusion :

In this Article, we have developled an android application that is capable to send bulk sms with some message like promotional sms, bill sms or any kind of message to your customer using SMS gateway service by Textlocal.

 

Firebase Cloud Messaging ( FCM ) to Send Push Notification Android 2021

2

Welcome to Proto Coders Point. This tutorial will we learn how to send firebase push notifications using Firebase Cloud Messaging free Service (FCM) the easiest way for android 2021.

Final FCM  push notification project demo

firebase push notification project demo done
firebase push notification project demo done

Sending Push Notifications to Android with Firebase

The 2016 Google I/O announced major improvements to their amazing product – Firebase – a cloud platform with a lot of amazing features for mobile app developers.

One of them is Firebase Cloud Messaging (FCM) — a cross-platform messaging solution that lets users reliably deliver messages at no cost.

Yes, FCM is a free service from Google.

Comparing to the earlier Google Cloud Messaging (GCM), FCM is much more developer-friendly because you don’t even need to see any of the server code involved.

This is a tutorial about sending push notifications to Android through Firebase, based on the new release of Firebase this year (2019).

This tutorial shows how to set up the skeleton for sending and receiving push notifications via FCM with instructions on the server code.

Video tutorial on the implementation of FCM push notification firebase

Watch this video

Step by Step implementation of firebase push notification in android studio

Let’s Begin implementation FCM firebase push notification in android studio.

Create a new android studio project and name it as FCM push notification 

Step 1 : 

File > New Project > Empty Activity > FCM Push notification (Give Application name)> Package name > Finish

 

Step 2 :

Tools > Firebase 
android studio firebase tool
android studio firebase tool

Your will get a firebase assistant on the right side of android studio window

Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably deliver messages at no cost.

Under Cloud messaging you will see text called  Setup cloud messaging  click on it  you need see setup instruction given by Firebase android studio assistant.

setup firebase cloud messaging
Setup Firebase cloud messaging

FCM Connect app to firebase server

Click on Connect to Firebase Button you see under firebase assistant

connect to firebase
connect to firebase

After Your app is been Successfully connected to the firebase service you will see a connected text in green color, which means your android application is connected to the firebase server.

firebase connected successfully
firebase connected successfully

Now you need to add FCM dependencies into your project Gradle file ( app level )

Don’t worry all those work will be done for you by firebase assistant you just need to click on add FCM to your app. this will open a window, just click accept changes and all set leave it you firebase android assistant it will do the rest of your work.

firebase FCM Dependencies
firebase FCM Dependencies

 

Firebase have added a messaging dependencies in you gradle file
Firebase have added a messaging dependencies in you gradle file

After Adding the FCM dependencies library the third step is to create a java class that handles Firebase messaging services.

If you wish to do any message handling beyond receiving notifications on apps in the background, create a new Service ( File > New > Service > Service ) that extends FirebaseMessagingService. This service is necessary to receive notifications in foregrounded apps, to receive data payload, to send upstream messages, and so on.

Create a new android services

File > New > service > service ( name it as " Push_Notification_Android"

and now add the following source code to it

Push_Notification_Android.java (service)

package protocoderspoint.com.fcmpushnotification;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import static android.content.ContentValues.TAG;

public class Push_Notification_Android extends FirebaseMessagingService {
    public Push_Notification_Android() {
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        Log.d(TAG, "From: " + remoteMessage.getFrom());

        Log.d(TAG, "Message data payload: " + remoteMessage.getData());

    }

    @Override
    public void onNewToken(String s) {
        super.onNewToken(s);
    }
}

The most important concept here is that onMessageReceive is ONLY called when the app is in the foreground, if the app if is background, Google Services will take care of displaying the message

And Finally to get a firebase push notification you need to add INTERNET permission in your AndroidManifest.xml file

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

AndroidManifest.xml file 

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

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



    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <service
            android:name=".Push_Notification_Android"
            android:enabled="true"
            android:exported="true"></service>

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

</manifest>

 

There you go, android application ready to get a Push notification from firebase server sent by you manually.

( Bonus )

How to add Default Notification icon with color for firebase push notification? 

Add the following lines of meta data taga,  inside AndroidManifest.xml in between <application> here </application>

<meta-data
    android:name="com.google.firebase.messaging.default_notification_icon"
    android:resource="@drawable/ic_launcher" />
      
<meta-data 
    android:name="com.google.firebase.messaging.default_notification_color"
    android:resource="@color/google_blue" />

How to send firebase push notifications to the android app using FCM?

Open Firebase console, Link.

firebase console project
firebase console project

Select your firebase project and open it, In my case, my firebase project name is “FCM push notification” as you can see in the above Image screenshot.

Now the Left side of the firebase console project you will see many services provided by Google Firebase Console.

Then go into Grow option drop-down list you will see Cloud messaging. open it you may see a window something like the below image.

firebase console project firebase push notification
firebase console project

Click on send your first message

Now firebase push notification is ready to be sent

  • Enter Notification Title
  • Enter Notification Text
  • Select target package name
  • Review and send
firebase push notification
send firebase push notification

Notification will be displayed on your Android Phone, and if you tap on that notification it will open the app

Related articles

flutter firebase integration – connect flutter app to firebase console

flutter push notification

send push notification to android using php firebase

flutter getx authentication – firebase auth

Basic Programs / Algorithm Every Programmer Should Remember

0
Basic Programs logic Every Programmer Should Remember-min
Basic Programs logic Every Programmer Should Remember-min

Introduction 

Basic Programs Generally speaking, in order to call your software developer or software engineer, you need to start learning what the basic software development needs and what the coding is.

Which means you need to start programming for sure first!

You can now go and learn about data structures and algorithms after you are able to understand and solve basic programming problems such as addition, subraction etc. using computer programming.

Many Fresher Programmer usually ask me : – 

Should I need to learn Basic Program/ Algorithms for Programming?

Let’s get some things straight. ‘Yes’  you should need to learn Basic Algorithms, Programming is all about applying logic and reason to solving programming problems.

An algorithm represents your solution to a programming problem or Application Development.

Basic Program/Algorithms Every Programmer Must Should Know to improve programming logics.

basic programs every programmer show know
basic programs every programmer show know

The algorithm is not the code of the computer. Algorithm is just the instructions that give you a clear idea to write computer code.

Examples Of An Basic Program / Algorithms In  C Programming.

  1. Program to add two numbers.
  2. A Program to find largest of three number.
  3. Program Logic to find all roots of a quadratic equation
  4. A program to find factorial of a number
  5. Program for Fibonacci numbers.

1. Program to add two numbers

Write a Algorithm to add 2 numbers entered by the Users.

Basic Algorithm to add 2 given number 

Step 1: Start
Step 2: Declare variables num1, num2 and sum. 
Step 3: Read values num1 and num2. 
Step 4: Add num1 and num2 and assign the result to sum.
        sum←num1+num2 
Step 5: Display sum 
Step 6: Stop

c Basic Program to add 2 numbers

#include<stdio.h>
 
int main()
{
   int a, b, c;
   
   printf("Enter two numbers to add\n");
   scanf("%d%d", &a, &b);
   
   c = a + b;
   
   printf("Sum of the numbers = %d\n", c);
   
   return 0;
}

Output

Enter two numbers to add

4

5

Sum of the numbers = 9

 

2. Program to find largest of three number.

Algorithm to find largest of three number

Step 1: Start
Step 2: Declare variables a,b and c.
Step 3: Read variables a,b and c.
Step 4: If a>b
           If a>c
              Display a is the largest number.
           Else
              Display c is the largest number.
        Else
           If b>c
              Display b is the largest number.
           Else
              Display c is the greatest number.  
Step 5: Stop
Program Explanation

1. Read  3 numbers and store it in the variables a, b and c respectively.
2. Check out step 4 We check if the a is greater than b.
3. If it is greater, then check a if it is greater than c.
4. If it is, then print the output as “a is the greatest among three”.
5. Otherwise print the ouput as “c is the greatest among three”.
6. If the a is not greater than b, then check if b is greater than c.
7. If it is, then print the output as “b is the greatest among three”.
8. Otherwise print the output as “c is the greatest among three”.

C program to find the biggest of three numbers

/*
 * C program to find the biggest of three numbers
 */
#include <stdio.h>
 
void main()
{
    int a, b, c;
 
    printf("Enter the values of a, b and c\n");
    scanf("%d %d %d", &a, &b, &c);
  
    if (a > b)
    {
        if (a > c)
        {
            printf(" a is the greatest among three \n");
        }
        else
        {
            printf("c is the greatest among three \n");
        }
    }
    else if (b > c)
        printf("b is the greatest among three \n");
    else
        printf("c is the greatest among three \n");
}

Output

Output:1
Enter the values of a, b and c
6 8 10
c is the greatest among three
 
Output:2
Enter the values of a, b and c
10 100 99
b is the greatest among three

 

3. Program Logic to find all roots of a quadratic equation

Write a C program to find all roots of a quadratic equation using if else. How to find all roots of a quadratic equation using if else in C programming. Logic to find roots of quadratic equation in C programming.

Algorithm to find root of quadratic equation

Step 1: Start
Step 2: Declare variables a, b, c, D, x1, x2, rp and ip;
Step 3: Calculate discriminant
         D←b2-4ac
Step 4: If D≥0
              r1←(-b+√D)/2a
              r2←(-b-√D)/2a 
              Display r1 and r2 as roots.
        Else     
              Calculate real part and imaginary part
              rp←b/2a
              ip←√(-D)/2a
              Display rp+j(ip) and rp-j(ip) as roots
Step 5: Stop

 

C Program to find root of quadratic equation.

/**
 * C program to find all roots of a quadratic equation
 */

#include <stdio.h>
#include <math.h> /* Used for sqrt() */

int main()
{
    float a, b, c;
    float root1, root2, imaginary;
    float discriminant;
    
    printf("Enter values of a, b, c of quadratic equation (aX^2 + bX + c): ");
    scanf("%f%f%f", &a, &b, &c);
    
    /* Find discriminant of the equation */
    discriminant = (b * b) - (4 * a * c);
    
   
    /* Find the nature of discriminant */
    if(discriminant > 0)
    {
        root1 = (-b + sqrt(discriminant)) / (2*a);
        root2 = (-b - sqrt(discriminant)) / (2*a);

        printf("Two distinct and real roots exists: %.2f and %.2f", root1, root2);
    }
    else if(discriminant == 0)
    {
        root1 = root2 = -b / (2 * a);

        printf("Two equal and real roots exists: %.2f and %.2f", root1, root2);
    }
    else if(discriminant < 0)
    {
        root1 = root2 = -b / (2 * a);
        imaginary = sqrt(-discriminant) / (2 * a);

        printf("Two distinct complex roots exists: %.2f + i%.2f and %.2f - i%.2f", 
                root1, imaginary, root2, imaginary);
    }

    return 0;
}

output

Enter values of a, b, c of quadratic equation (aX^2 + bX + c):
 8 -4 -2

Two distinct and real roots exists:

 0.81 and -0.31

4. Program to find factorial of a number

Factorial program in C programming language:  Factorial is represented using ‘!’, so five factorial will be written as (5!), n factorial as (n!). Also,

n! = n*(n-1)*(n-2)*(n-3)…3.2.1

i.e 5*4*3*2*1

zero factorial is defined as one i.e., 0! = 1.

Algorithm to solve factotial of a given number

Step 1: Start
Step 2: Declare variables n,factorial and i.
Step 3: Initialize variables
          factorial←1
          i←1
Step 4: Read value of n
Step 5: Repeat the steps until i=n
     5.1: factorial←factorial*i
     5.2: i←i+1
Step 6: Display factorial
Step 7: Stop

Program to solve factotial of a given number

#include <stdio.h>
 
int main()
{
  int i, n, fact = 1;
 
  printf("Enter a number to calculate its factorial\n");
  scanf("%d", &n);
 
  for (i = 1; i <= n; i++)
  {
    fact = fact * i;
  }
 
  printf("Factorial of %d = %d\n", n, fact);
 
  return 0;
}

Output

Enter a number to calculate its factorial
6
Factorial of 6 = 720

5 . Program for Fibonacci Series in C

In case of fibonacci series, For example 0, 1, 1, 2, 3, 5, 8, 13, 21 etc.

The first two numbers of fibonacci series are 0 and 1

next number is the sum of previous two numbers.

.Here 0+1 = 1 which is the third number, as we continue 1+1 = 2 which is forth number, and 1+2=3 and so on

Algorithm to display fibonacci series

Step 1: Start
Step 2: Declare variables n1,n2,n3,number and i.
Step 3: Initialize variables
         n1=0
         n2=1
          i←1
Step 4: Read value of number
Step 5: Repeat the steps until i<number
        5.1: n3=n1+n2
        5.2: Disply n3
        5.3: n1=n2
        5.4: n2=n3
Step 6: Stop

Basic C  Program  to display fibonacci series

#include<stdio.h>    
int main()    
{    
 int n1=0,n2=1,n3,i,number;    
 printf("Enter the number of elements:");    
 scanf("%d",&number);    
 printf("\n%d %d",n1,n2);//printing 0 and 1    
 for(i=2;i<number;++i)//loop starts from 2 because 0 and 1 are already printed    
 {    
  n3=n1+n2;    
  printf(" %d",n3);    
  n1=n2;    
  n2=n3;    
 }  
  return 0;  
 }

Output

Enter the number of elements:15
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

 

Referals website

https://www.javatpoint.com/c-programming-language-tutorial

https://www.programiz.com/article/algorithm-programming

https://www.programmingsimplified.com/c-program-find-factorial

 

 

 

Dart Programming Language – Variables in Dart

5
Dart Programming Language - Variables in Dart
Dart Programming Language - Variables in Dart

In any programming, A variable is “a named space in the memory” that we use to store some values. In other words, it acts a box or a container filled with some values in it. Variable names are also called identifiers, all dart data types Variables in Dart are bit same as that of javascript language.

Here are some Rules we need to follow while creating an identifier/dart variables.

  •  A Variable should not be keywords
  • Variable can contain alphabet’s and numbers.
  • A Variable cannot contain any space or special character, except underscore( _ ) and Dollar symbol ( $ )
  • Variable name should not begin with a number.
  • Note: All the data types in dart are Objects. It means everything in Dart is objects and it inherits object properties. This means the default value of all these data types is null.

Syntax of Variable in dart 

Dart makes use of the var keyword to declare the same. The syntax for declaring a dart variable is as given below:-

var name;

When we declare a variable without giving it any value, we essentially have created a dynamic type of variables, which means that variable can store any kind of values whether it may be an int or a string.

Eg: dart variable declared as a string

var Name = 'proto coders point';

Here is the explanation.

  • var is the Data Type
  • Name is the Variable name
  • Proto Coders Point is the Value stored in the variable

In the above-given example, we are declaring a variable name with the value ” proto coders point “ which means that this variable can only store Strings. when we set any value in single or double inverted commas it will automatically initialize itself a string, in other cases number can directly set to a variable. as shown below:-

void main() {
  
 var number = 123;
  print(number);
 
}

output

123

Dart Programming Language Different data-types variable.

Here is an example where are will implement all kinds of data types variables in dart programming language.

void main() {
     var x = 'Maths pi'; // string variable
     var y = 3.14;       // int variable

     print(x); // Maths pi
     print(y); // 3.14
}

Output

Maths pi
3.14

Example 2: In Dart, we can store different kinds of data in the same variable and change it during run time. Here is an example of flutter math.pi

//this will work know more about this below
void main() {
    var x ;
    x = 'Math pi';
    print(x); // Maths pi

    x = 3.14;
    print(x); // 3.14
}

Output

Math pi

3.14

This is valid Example   because we are not initilizating any value to var x  so we can easily change its data type at runtime.

Example 3

In this Example 3 we will try to mix both example 1 &2.
Now I am going to initialize the variable at the time if declaration and trying to store different data type in the same variable. I Now This will sure give me some error because this is not valid in Dart, as it is valid in javascript.

// This is invalid Example this will work
void main() {

     var x = 'Math pi';
     print(x);  // Maths pi


     x = 3.14;  // Compilation failed error because
                // you are trying to assign double to String variable.
     print(x);
}

Here in above Example 3 we will get compilation Failed Error Because we are trying to assign double to String Variable which is not possible in Dart.

dynamic type keyword variable in dart

There is the dynamic keyword for variable declaration in Dart which is equivalent to JavaScript var keyword.

If we had used dynamic instead of var in Dart code we will not got any error because in dart  programming language dynamic is same as  Var in JavaScript.

dynamic name = 'My Name Is Proto'; // dynamic keyword 
dynamic id = 101; 

name= 123; // dynamic variable can also even store numbers

As in above lines of code we have declared a dynamic variable which is currently storing string values, but as code reach line num 3  it will change its datatype to integer.

if you need the flexibility of a dynamic language. The dynamic type itself is static, but can contain any date type at runtime. Of course, that removes many of the benefits of a type-safe language for that variable.

Example of Dynamic Variable in dart :

void main() {
  
  dynamic n ='Its a Dynamic Value : String';
  
  print(n);
  
  n = 5;
  
  print("its a Dynamic Value : Integer = $n ");
  
  
  
}

OutPut

Its a Dynamic Value : String
its a Dynamic Value : Integer = 5

Final and Const

The final and const keyword are used to declare constants. Here Dart Programming Language allow prevents modifying the values of a variable declared using the final or const keyword.

here final and const keyword variable will work into similar way.

Syntax of const keyword:

const variable_name = value; //if value is string it should have inverted commans

Syntax of final keyword:

final variable_name = value; // is value is string it should have inverted commas.

Here final or const  variable in dart must be initialized at the time of declaration.

Example of final  or const  constants in dart programming language.

void main() {
  
  final abc='xyz';
  print("final data :  "+abc);
  
  const xyz=123;
  print("const data : $xyz");
  
  
}

output

final variable : xyz

const variable : 123

let us check if final or const  data can  be changed or no

void main() {
  
  final abc='xyz';
  print("final variable :  "+abc);
  
  abc="abc"; // this will give me error becz it final which iss constant in nature
  
  const xyz=123;
  print("const variable : $xyz");
  
  
}

// above Code will give me compilation error because once a datatype is  declared as final or const with cannot we changed during runtime.

All in one Dart Programming Language Data type Variables Example

void main() {
  
  String name = 'Smith'; //string data type 
  
  print("Name : "+name);
  
  int num = 10; //integer datatype
  
  print(" Number : $num");

  
  dynamic x = "tom"; //is initialized as string  but later we can change it to double or integer
  
  print("dynamic string : "+x); // dynamic print string
  
  x=123; //dynamic datatype value string gets changed into integer
  
  print("dynamic integer : $x");
  
  final abc='xyz';
  print("final constants"+abc);
  
  const number=123;
  print("constants number : $number");
 
  
  
}

Here name is normal string datatype , num is normal integer datatype , x is a dynamic datatype which can even change its datatype at runtime, final  abc is a constants datatype string which cannot be changed at runtime.

To run the above Dart Programs online visit here https://dartpad.dartlang.org/

recyclerview with cardview android studio example – Androidx Tutorial

6
android RecyclerView with CardView example
android RecyclerView with CardView example

In this Tutorial, we will implement recyclerview with cardview in android studio.

As it is usually recommended now to make use of simple ListView to show a large set of data sets. If you have a huge set of data sets that you want to show to UI, then you should use RecyclerView, Because RecyclerView is much more customizable than ListView and in terms of performance it is also very far ahead.

Here is a demo of how the Final Recyclerview with cardview UI looks like.

recyclerview with cardview android example
recyclerview with cardview android example

Android RecyclerView and Android CardView got introduced in Android Lollipop with Material Design.

Before We start Implementing Recyclerview with CardView android we will know the basics.

Android RecyclerView

Android RecyclerView is one of the more advanced, powerful, and flexible versions of the ListView Android.

RecyclerView is very useful to set the Layout Managers dynamically at runtime, unlike the ListView That was able to show the list in only one format is the vertical list. RecyclerView allows us to set the following types of Layouts at runtime.

  • LinearLayoutManager:  This helps users to set views in both vertical wells as horizontal listviews.
  • StaggeredLayoutManager: it supports staggered lists
  • GridLayoutManager: This layout helps us in viewing List in Grid UI as in  GalleryView earlier. recyclerview gridlayout android example

recycler view Dependencies

dependencies {
    implementation 'com.android.support:recyclerview-v7:28.0.0'
}

RecycleView Dependencies for androidx

implementation 'androidx.recyclerview:recyclerview:1.0.0'

Android CardView

Apps often need to display data in similarly styled containers. These containers are often used in lists to hold each item’s information. The system provides the CardView API is an easy way for you to show information inside cards that have a consistent look across the platform. CardView is mostly used for good-looking UI with RecyclerView.

CardView is usually an XML UI Design to show data within the list using the recycler view. Android CardView UI component shows information inside cards. This component is generally used to show contact information.

CardView Dependencies

dependencies {
    implementation 'com.android.support:cardview-v7:28.0.0'
}

CardView Dependencies for androidX

implementation 'androidx.cardview:cardview:1.0.0'

How we use RecyclerView with Cardview android x Example Project

So let us begin with the implementation of Recyclerview with card view android Application example.

Create a new project in android studio with Empty Activity.

This RecyclerView with Cardview android project consists of a MainActivity that basically displays the RecyclerView in XML.

The CardView is added to the RecyclerView from the CustomAdapter class.

The DataModel class is used to retrieve the data for each CardView through getters.

The MyData class holds the arrays of text views and drawables along with their ids.

Android RecyclerView with cardview android example code

The activity_main.xml holds the RecyclerView inside a RelativeLayout as shown below.

activity_main.xml code:

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

    >

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical"
        />

</RelativeLayout>

Android CardView layout is defined below:

cards_layout.xml code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:tag="cards main container">

    <androidx.cardview.widget.CardView
        android:id="@+id/card_view"
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        card_view:cardBackgroundColor="@color/colorAccent"
        card_view:cardCornerRadius="10dp"
        card_view:cardElevation="5dp"
        card_view:cardUseCompatPadding="true">

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

            <ImageView
                android:id="@+id/imageView"
                android:tag="image_tag"
                android:layout_width="0dp"
                android:layout_height="100dp"
                android:layout_margin="5dp"
                android:layout_weight="1"
                android:src="@drawable/ic_launcher_background"/>

            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="12dp"
                android:layout_weight="2"
                android:orientation="vertical"
                >

                <TextView
                    android:id="@+id/textViewName"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginTop="10dp"
                    android:text="Android Name"
                    android:textColor="#FFFFFF"
                    android:textAppearance="?android:attr/textAppearanceLarge"/>

                <TextView
                    android:id="@+id/textViewVersion"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginTop="10dp"
                    android:text="Android Version"
                    android:textColor="#FFFFFF"
                    android:textAppearance="?android:attr/textAppearanceMedium"/>

            </LinearLayout>
        </LinearLayout>

    </androidx.cardview.widget.CardView>

</LinearLayout>

In above Android CardView cards_layout.xml code  it holds a ImageView that displayed drawable resources along with two TextViews in a Nested Linear Layout.

The menu_main.xml contains a single item to add back the cards removed.

how to create a new menu

File > New >Menu Resource File

and Add the below line of menu coders

<?xml version="1.0" encoding="utf-8"?>
<menu 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"
    tools:context=".MainActivity">
    <item android:id="@+id/add_item"
        android:title="Add"
        android:orderInCategory="100"
        app:showAsAction="always"/>
</menu>

MainActivity.java class is defined below.

MainActivity.java

package protocoderspoint.com.cardviewrecycleviewandroid;

import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private static RecyclerView.Adapter adapter;
    private RecyclerView.LayoutManager layoutManager;
    private static RecyclerView recyclerView;
    private static ArrayList<DataModel> data;
    static View.OnClickListener myOnClickListener;
    private static ArrayList<Integer> removedItems;

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

        myOnClickListener = new MyOnClickListener(this);

        recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
        recyclerView.setHasFixedSize(true);

        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        data = new ArrayList<DataModel>();
        for (int i = 0; i < MyData.nameArray.length; i++) {
            data.add(new DataModel(
                    MyData.nameArray[i],
                    MyData.versionArray[i],
                    MyData.id_[i],
                    MyData.drawableArray[i]
            ));
        }

        removedItems = new ArrayList<Integer>();

        adapter = new CustomAdapter(data);
        recyclerView.setAdapter(adapter);
    }


    private static class MyOnClickListener implements View.OnClickListener {

        private final Context context;

        private MyOnClickListener(Context context) {
            this.context = context;
        }

        @Override
        public void onClick(View v) {
            removeItem(v);
        }

        private void removeItem(View v) {
            int selectedItemPosition = recyclerView.getChildPosition(v);
            RecyclerView.ViewHolder viewHolder
                    = recyclerView.findViewHolderForPosition(selectedItemPosition);
            TextView textViewName
                    = (TextView) viewHolder.itemView.findViewById(R.id.textViewName);
            String selectedName = (String) textViewName.getText();
            int selectedItemId = -1;
            for (int i = 0; i < MyData.nameArray.length; i++) {
                if (selectedName.equals(MyData.nameArray[i])) {
                    selectedItemId = MyData.id_[i];
                }
            }
            removedItems.add(selectedItemId);
            data.remove(selectedItemPosition);
            adapter.notifyItemRemoved(selectedItemPosition);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        if (item.getItemId() == R.id.add_item) {
            //check if any items to add
            if (removedItems.size() != 0) {
                addRemovedItemToList();
            } else {
                Toast.makeText(this, "Nothing to add", Toast.LENGTH_SHORT).show();
            }
        }
        return true;
    }

    private void addRemovedItemToList() {
        int addItemAtListPosition = 3;
        data.add(addItemAtListPosition, new DataModel(
                MyData.nameArray[removedItems.get(0)],
                MyData.versionArray[removedItems.get(0)],
                MyData.id_[removedItems.get(0)],
                MyData.drawableArray[removedItems.get(0)]
        ));
        adapter.notifyItemInserted(addItemAtListPosition);
        removedItems.remove(0);
    }
}

In the above lines of code the removeItems() method is invoked from the listener method to remove the CardView with every card is been clicked. ts respective id is stored in an array to retrieve later.

The CustomeAdapter.java class is defined below :

package protocoderspoint.com.cardviewrecycleviewandroid;


import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;


class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {

    private ArrayList<DataModel> dataSet;



    public static class MyViewHolder extends RecyclerView.ViewHolder {

        TextView textViewName;
        TextView textViewVersion;
        ImageView imageViewIcon;

        public MyViewHolder(View itemView) {
            super(itemView);
            this.textViewName = (TextView) itemView.findViewById(R.id.textViewName);
            this.textViewVersion = (TextView) itemView.findViewById(R.id.textViewVersion);
            this.imageViewIcon = (ImageView) itemView.findViewById(R.id.imageView);
        }
    }

    public CustomAdapter(ArrayList<DataModel> data) {
        this.dataSet = data;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent,
                                           int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.cards_layout, parent, false);

        view.setOnClickListener(MainActivity.myOnClickListener);

        MyViewHolder myViewHolder = new MyViewHolder(view);
        return myViewHolder;
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, final int listPosition) {

        TextView textViewName = holder.textViewName;
        TextView textViewVersion = holder.textViewVersion;
        ImageView imageView = holder.imageViewIcon;

        textViewName.setText(dataSet.get(listPosition).getName());
        textViewVersion.setText(dataSet.get(listPosition).getVersion());
        imageView.setImageResource(dataSet.get(listPosition).getImage());
    }

    @Override
    public int getItemCount() {
        return dataSet.size();
    }
}

In the CustomAdopter.java code, we have implemented our own ViewHolder by extending RecyclerView.ViewHolder. The view  that inflate the cards_layout.xml.

An ArrayList stores all the data in the form of a DataModel class object in an ArrayList and adds them to the respective cards in a form of list.

Here i have made user of data model class that contains specific data for this application,

DataModel.java

package protocoderspoint.com.cardviewrecycleviewandroid;


public class DataModel {

    String name;
    String version;
    int id_;
    int image;

    public DataModel(String name, String version, int id_, int image) {
        this.name = name;
        this.version = version;
        this.id_ = id_;
        this.image=image;
    }

    public String getName() {
        return name;
    }

    public String getVersion() {
        return version;
    }

    public int getImage() {
        return image;
    }

    public int getId() {
        return id_;
    }
}

In the above DataModel.java we have defined a list if variables that stored and fetch data using getters mehods.

In above code i m getting data like name, id, image; that help us in showing data in cardview.

MyData.java

package protocoderspoint.com.cardviewrecycleviewandroid;

public class MyData {

     //list of android version names
    static String[] nameArray = {"Cupcake", "Donut", "Eclair", "Froyo", 
"Gingerbread", "Honeycomb", "Ice Cream Sandwich",
"JellyBean", "Kitkat", "Lollipop", "Marshmallow"};

    //list of android version
    static String[] versionArray = {"1.5", "1.6", "2.0-2.1", 
"2.2-2.2.3", "2.3-2.3.7", "3.0-3.2.6", "4.0-4.0.4", "4.1-4.3.1", 
"4.4-4.4.4", "5.0-5.1.1","6.0-6.0.1"};

    //list of android images
    static Integer[] drawableArray = {R.drawable.cupcake, R.drawable.donut, R.drawable.eclair,
            R.drawable.froyo, R.drawable.gingerbread, R.drawable.honeycomb,R.drawable.icecream,
            R.drawable.jellybean, R.drawable.kitkat,R.drawable.lollipop,R.drawable.marshmallow};

    static Integer[] id_ = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
}

That above MyData.java is been used just to store list of data in a form of arrays.

The above list of data will be displayed in a form of RecyclerView with CardView list items.

Refered Article @www.journaldev.com

Introduction To Java Programming – what is java

2
introduction to java programming.png
introduction to java programming.png

Introduction To JAVA

JAVA is a programming language that is used in many software developments like Android App Development and much more. It is class-based and object-oriented programming whose syntax is influenced by C++. The primary goals of JAVA are to be simple, object-oriented, robust, secure, and high level. JAVA application runs on JVM (JAVA Virtual Machine).

Tutorial On JAVA Topics

TopicDescription
VariablesLearn about variables and how they are created for storing information in memory. A variable is a container that holds the value while the java program is executed. In Java, there are 3 types of variables namely Local Variable, Static Variable, Instance Variable.
Data TypesLearn about Data Types (i.e. byte, int, char, etc) which is basically a type of information we want to store in the variable. Weather data is number, Character, or something else like boolean value.
StringThe string is nothing but a character array for example “protocoderspoint” is a string of 16 characters as shown.
KeywordsKeywords in JAVA are a predefined list of keywords which has a specific meaning and cannot be used in the Java programming language as an identifier, such as the name of a variable, method, class, function, or label.
OperatorsIn computer, a programming Operator is a symbol that tells the compiler to perform specific action which can be mathematical or logical like addition, subtraction, multiplication, etc.
Class And ObjectsThe concept of class comes into the role when we see certain types of objects or things around us and the common idea or a blueprint behind this type of object is called Class. Object is an instance of the class.
MethodA method is a self-defined block of code that performs a specific task.