Home Blog Page 93

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.

Picasso android library tutorial – Picasso image loader

2
picasso android image loader library
picasso android image loader library

Picasso android library is – A powerful image loading, image downloading, and image caching library for Android.

This Picasso library allows for hassle-free image loading in your application—often in one line of code!

Picasso dependency is an open-source Android library that is developed and maintained by Square. This library hides all the complexity as it will deal with back-on threading, loading images from the internet, and even caching. Picasso makes memory-efficient to resize and transform images. Picasso Library makes it quite easier for displaying images from remote locations.

Final Output of this Picasso android tutorial.

picasso android image loader
picasso android image loader

1. Feature of this Universal image loader library

  • Handling ImageView recycling and download cancelation in an adapter.
  • Complex image transformations with minimal memory use.
  • Automatic memory and disk caching.

2. Callbacks and Targets In Picasso In Android

Picasso library loads an image in two ways that are synchronously and Asynchronously.

.fetch() –this is an asynchronously load the image into a background thread. This method only saves the image into the disk or memory cache. It’s neither going to load the image into image view nor it is going to return any Bitmap. If you want to reduce the reduce image loading times and if you know that the image is needed by you shortly after then it could be used to fill the image cache in the background.

.get() – It returns a Bitmap object and loads an image synchronously. But it will freeze the UI if you will call it from the UI thread.

into(ImageView targetImageView) – It is provided by Picasso where you can Specify your target Imageview in which the image is supposed to get displayed.

In this tutorial, you will learn How to use Picasso android library to load images from the locally drawable drive and even how to load images from a URL.

How to add Picasso library in android studio Picasso dependency?

Navigate to your project file at the left side of your android studio. You will see “Gradle Scripts” open the drop down list, you will see a build.gradle (Module:app) open it.

adding picasso dependency library
adding picasso dependency library

Before using Picasso we have to add its dependency in build.gradle file in module level : app.

Picasso dependency

implementation 'com.squareup.picasso:picasso:2.71828'

NOTE: To load image from URL android  you need a internet permission that you need to assign in android manifest.xml file. As shown in below image.

adding internet permission in android studio
adding internet permission in android studio

add internet access permission in AndroidMainfest.xml file.

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

Picasso to load image

To Simply load an image in and imageView

Picasso.get()
.load("https://protocoderspoint.com/wp-content/uploads/2019/10/protocoderspoint-rectangle-round-.png")
.into(imageView);

show placeholder Picasso android library

Picasso.get() .
load("URL PATH") .
placeholder(R.drawable.user_placeholder) .
error(R.drawable.user_placeholder_error) .
into(imageView);

Picasso supports both download and error placeholders as optional features.

We can specify an image as a place holder until the image is being loaded, placeholder are commenly used with we face any technical issue like network failed to load the picasso image, in such a case we make use of placeholder in picasso so that we can show a default image in place of real image.We can also give an image as an error handler if any error occurs while loading the image.

show error image using Picasso library

Picasso.get() 
.load("URL PATH") 
.error(R.drawable.user_placeholder_error)
.into(imageView);

Image Transformation picasso android studio

Picasso.get()
  .load(url)
  .resize(50, 50)
  .centerCrop()
  .into(imageView)

As you know picasso is a universal image loader,So we can change image dimensions to fit layouts and reduce memory size utilized by image.

Image Rotation In Picasso

Picasso.with(context)

       .load("image source here")

       .rotate(90f)

       .into(someImageView);

This will rotate the image by 90 degrees.

Picasso Android Image loader library github.

Now let us begin by creating a project in android studio to implement Picasso universal image loader library.

Picasso Android Example

In the Example, i m loading an image from local and from URL when button is clicked OK.

Create a project with and of your wish package name  i m using “protocoderspoint.com.picassoandroidimageloader” and add following code in respective files

activity_main.xml

For User interface design.

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

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_gravity="center"
    android:gravity="center"
    android:layout_margin="10dp">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Proto Coders Point"
        android:textColor="#0042FF"
        android:textSize="20sp"
        android:layout_marginBottom="15dp"
        android:textStyle="italic|bold"/>

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@mipmap/ic_launcher" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="locally load image"/>

    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@mipmap/ic_launcher" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="load image from URL">

    </TextView>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textStyle="bold"
        android:textSize="20sp"
        android:textColor="#093FC4"
        android:text="Click load button to load images ">

    </TextView>

    <Button
        android:id="@+id/load_images"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Load images " />

</LinearLayout>
</LinearLayout>

Main_Activity.java

For back end programming in java

package protocoderspoint.com.picassoandroidimageloader;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.squareup.picasso.Picasso;

public class MainActivity extends AppCompatActivity {

    ImageView local_image,url_image;
    Button load_images;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        local_image=(ImageView)findViewById(R.id.imageView2);
        url_image=(ImageView)findViewById(R.id.imageView3);

        load_images=(Button)findViewById(R.id.load_images);

        load_images.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Picasso.get().load(R.drawable.protocoder).into(local_image);
                Picasso.get().load("https://cdn.pixabay.com/photo/2012/04/24/11/54/picasso-39592_960_720.png").into(url_image);
            }
        });


    }
}

AndroidManifest.xml

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

    <!--internet permission to load image from URL-->
    <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">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

also read welcome-screen-github-library

Flutter Profile Page UI Design Using Flutter Card & ListTile Widget

4
Flutter Profile Page UI Design

Welcome To Proto Coders Point, In this tutorial, we will learn how to create a profile page UI Design app using Dart and Flutter. A quick sample app on how to create a simple profile screen page in flutter.

Similar profile page UI design 2 

Flutter Profile Page UI Design Using Flutter Card & ListTile Widget

The Final UI of Flutter profile page will look something like below screenshot.

Flutter Profile Page UI Design Using Flutter Card & ListTile Widget
Flutter Profile Page UI Design Using Flutter Card & ListTile Widget

Video Tutorial play here

Open android Studio and create a new flutter project.

File > New  > New Flutter Project

Give a name you your flutter project and set a path to store you flutter project.

Now you will a see a default counter code generated, that simply counts the number of times the button is pressed and display counting on the screeen.

You can just remove default code of flutter and shown in below Image.

flutter profile UI Design
flutter profile UI Design

So let’s begin with the actual code for Flutter profile page example UI Design.

before we start implement, we need the resources such as images and fonts to be set/copy in our project directory, For that we need to create 2 directory.

Directory

  1. images : to store all our project image resources.
  2. fonts : to store all our fonts style ttf extension files.

Here is how to create directory in android-studio ( flutter )

Right Click on project > New > Directory

creating a directory in flutter project
creating a directory in flutter project

like wise create a 2nd directory name “fonts”

download an icon and fonts from google

Icons made by Smashicons from www.flaticon.com

Copy both the image and fonts file in those directorys.

As shown in the highlighted area

NOTE: you also need to initialize the resources in  pubspec.yaml file

setting images in flutter pubspec.yaml android studio
setting images in flutter pubspec.yaml android studio

assets:
    - images/user.png
  fonts:
    - family: SourceSansPRO-Regular
      fonts:
        - asset: fonts/SourceSansPRO-Regular.ttf

Please check the indentation ( Many programmer face problems while setting  resources package )

Source Code of Flutter Profile UI Design

main.dart

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text(
            "Profile Page UI Design using Flutter ",
            style: TextStyle(fontSize: 18.0),
          ),
        ),
        backgroundColor: Colors.blue[300],
        body: SafeArea(
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                CircleAvatar(
                  radius: 80,
                  backgroundImage: AssetImage('images/protocoder.png'),
                ),
                Text(
                  'Proto Coders Point',
                  style: TextStyle(
                    fontFamily: 'SourceSansPro',
                    fontSize: 25,
                  ),
                ),
                Text(
                  'Welcome',
                  style: TextStyle(
                    fontSize: 20,
                    fontFamily: 'SourceSansPro',
                    color: Colors.red[400],
                    letterSpacing: 2.5,
                  ),
                ),
                SizedBox(
                  height: 20.0,
                  width: 200,
                  child: Divider(
                    color: Colors.teal[100],
                  ),
                ),
                Text("Keep visiting protocoderspoint.com for more contents"),
                Card(
                    color: Colors.white,
                    margin:
                        EdgeInsets.symmetric(vertical: 10.0, horizontal: 25.0),
                    child: ListTile(
                      leading: Icon(
                        Icons.phone,
                        color: Colors.teal[900],
                      ),
                      title: Text(
                        '+91 85465XXX8XX',
                        style:
                            TextStyle(fontFamily: 'BalooBhai', fontSize: 20.0),
                      ),
                    )),
                Card(
                  color: Colors.white,
                  margin:
                      EdgeInsets.symmetric(vertical: 10.0, horizontal: 25.0),
                  child: ListTile(
                    leading: Icon(
                      Icons.cake,
                      color: Colors.teal[900],
                    ),
                    title: Text(
                      '08-05-1995',
                      style: TextStyle(fontSize: 20.0, fontFamily: 'Neucha'),
                    ),
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Explaination of flutter widget used in the above code.

Flutter Card Class

A material design card. A card has slightly rounded corners and a shadow.

A card is a sheet of Material used to represent some related information, for example an album, a geographical location, a meal, contact details, etc.

In the above lines of code Flutter Card i have used child that contains ListTile widget class  with leading icons and title.

Read more above flutter card on official site.

ListTile class

A single fixed-height row that typically contains some text as well as a leading or trailing icon.

It is the responsibility of the caller to ensure that title does not wrap, and to ensure that subtitle doesn’t wrap.

In the above lines of code Flutter ListTile  class that has leading with icons and title with text.

SizedBox Widget Class

A box with a specified size.

If given a child, this widget forces its child to have a specific width and/or height .

In the above code you can observe their is a tiny empty space in between call icon and phone number text

Divider Widget Class

thin horizontal line, with padding on either side.

In the material design language, this represents a divider. Dividers can be used in lists, Drawers, and elsewhere to separate content.

If you are new in flutter development check this post to learn about how to install fluttter in android studio

How to install flutter in android studio with First Flutter App Hello World