Home Blog Page 62

How to create custom dialog box with floating image app logo in android

0
custom alert dialog in android
custom alert dialog in android

Hi Guys, Welcome to Proto Coders Point. In this Android tutorial, we will learn how to create a custom dialog box with a floating image app logo.

Sometimes a simple & default android dialop popup is not suitable with our app UI, In that case we need to create a custom alert dialog layout design to show as a popup to a user.

Example: Check the below image, this is what we will achieve at the end.
A android custom popup dialop example with a floating imageview sightly out of dialog as shown in below screenshot.

custom alert dialog in android design

Video Tutorial

Below are steps to achieve above android alert dialog.

Step 1: create a background for custom dialog layout

Create a XML file: dialog_bg.xml in drawable folder and copy paste the below code in it.

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

    android:insetLeft="5dp"
    android:insetTop="5dp"
    android:insetBottom="5dp"
    android:insetRight="5dp"
    >

    <shape android:shape="rectangle">
        <corners android:radius="20dp"/>
        <solid android:color="@color/white"/>
        <stroke android:width="5dp" android:color="#FFF"/>
    </shape>

</inset>

The above code is just to give a corner radius, solid color, and stroke to custom_dialog.xml background.


Step 2: Create a vector image(cancel image) and copy a logo image in drawable

Create vector assets image
Right click on drawable -> New -> Vector Assets & choose a cancel button.

We need a logo image file to show in dialog popup as a floating app logo, So just copy your app logo in drawable file.

logo.png

Step 3: Creating a custom_dialog.xml layout file under layout folder

Now a main custom alert dialog layout design custom_dialog.xml, Under layout folder create a XML file custom_dialog.xml and copy below layout code and paste in it.

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

    <LinearLayout
        android:background="@drawable/dialog_bg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:orientation="vertical"
        android:layout_marginRight="20dp"
        android:layout_marginTop="30dp">

        <ImageView
            android:id="@+id/cancel_button"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:background="@drawable/ic_cancel"
            android:layout_centerHorizontal="true"
            android:layout_marginRight="10dp"
            android:layout_marginTop="5dp"
            android:layout_gravity="right"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="20dp"
            android:layout_marginTop="20dp"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="WELCOME TO PROTO CODERS POINT"
                android:textColor="#000"
                android:textStyle="bold|italic"
                />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="Please do like and Subscribe Us"
                android:textColor="#000"
                android:textStyle="bold|italic"
                />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="OK"
                android:gravity="center"
                android:layout_gravity="center"
                android:layout_marginTop="10dp"/>


        </LinearLayout>

    </LinearLayout>

    <ImageView
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_centerHorizontal="true"
        android:background="@drawable/logo"
        />

</RelativeLayout>

This code defines different views inside a custom dialog layout, it has 2 imageview, one for App logo and another for cancel vector image and 2 TextView and a ‘OK’ button.


Step 4: activity_main.xml add a button

In activity_main.xml file will add a button, when a user clicks on that button will show android dialog.

<?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:gravity="center">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Dialog"
        android:id="@+id/showdialog"
        />

</LinearLayout>

Step 5: MainActivity.xml on click show alert dialog in android

On Button click create a custom dialog in android and show it to the user.

MainActivity.java

package example.on.dialog_popup;


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

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.Image;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;


public class MainActivity extends AppCompatActivity {

    Button showdialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //find the view
        showdialog = (Button)findViewById(R.id.showdialog);

       // when clicked 
        showdialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                 ImageView cancel;
                 //will create a view of our custom dialog layout
                 View alertCustomdialog = LayoutInflater.from(MainActivity.this).inflate(R.layout.custom_dialog,null);
                //initialize alert builder.
                AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
                
                //set our custom alert dialog to tha alertdialog builder
                alert.setView(alertCustomdialog);
                cancel = (ImageView)alertCustomdialog.findViewById(R.id.cancel_button);

                final AlertDialog dialog = alert.create();

                //this line removed app bar from dialog and make it transperent and you see the image is like floating outside dialog box.
                dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

                //finally show the dialog box in android all
                dialog.show();

                cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog.dismiss();
                    }
                });


            }
        });

    }
}


Recommended Android and Flutter Posts

Android Alert dialog Box with list of options in it.

Alert dialog box in flutter

Android emulator was killed – ERROR SOLUTION

0
Android emulator was killed
Android emulator was killed

Hi Guys, Welcome to Proto Coders Point.

So, I just tried starting AVD Android Emulator but what was actually happening is, when i start Emulator it was showing connecting to the emulator & suddenly it showed android emulator was killed.

Then, i tried some solution from stackoverflow and found a solution that worked for me. so just thought to share about this to you.

So here are some solution you need to try. The Solution 1 worked for me.

Solution 1: Check your drive free space( This worked for me)

I have a SSD drive, where my windows OS is installed & Android Studio is allso installed in SSD for fast loading with Emulator.

Android Studio Emulator consume atleast 8 GB of space in C: drive, Then if there is no space in C: drive & you try to start Android emulator then due to low storage, android emulater will kill itself.

Please check drive C:, it should have atleast 10 GB of free memory for emulator to run smoothly.


Solution 2: intel x86 Emulator Accelerator update

Check if you have installed ‘‘intel x86 Emulator Acceleration” SDK tools, if YES check if it updated else just install it and keep it up-to-date.

Android-Studio > Tools > SDK Manager > SDK Tools(Tab) > tick [intel x86 Emulator Accelerator(HAXM installer)] and update it.
android studio install intel x86 emulator accelerator

Solution 3: Install/Update Android Emulator SDK tools

There might be some issue if you are using lower version of SDK tools Android Emulator =, so kindly be updated with latest version of android Emulator.

Android-Studio > Tools > SDK Manager > SDK Tools(Tab) > tick [Android Emulator] and update it
android emulator sdk tools install

final and const keyword in dart – what’s difference

0
final and const keyword in dart
final and const in flutter dart

Hi Guys, Welcome to Proto Coders Point, In this dart tutorial we will learn what is the difference between final and const keyword in flutter dart.

Even dart programming language support assigning a constant value to a dart variable, Here constant value means once a value is assigned to the variable then it cannot be altered/changed.

There are 2 keywords used to declare constant variable in dart:

  1. const keyword.
  2. final keyword.

Const Keyword in dart

The const keyword in dart, are similar to final keyword but, The only different between const & final is, In const variable initialization can only be done during compile-time, means a variable value cannot be initialized at run-time.

Example: 
String name;

//get input to name from user
name = stdin.readLineSync();

//you will get error; doing this
const copyname = name; //error

In Simple words, by using const keyword you cannot take input from user and then assign to const variable in run-time. but by using const you can assign value directly at compile-time only.

Example:
const number = 85785;
// later this can't be changed; like this
number = 854; // cant do this


When to use const keyword

Suppose you have a value that will never alter or should not be changed during run-time. Eg: A String ‘ProtoCodersPoint’ will always be same for a app name, but if you are integrating a time in your app then const should not be used for currect time because it keep change every milli seconds.


final keyword in dart

In final keyword, the only different i we can assign a value to final variable at run-time(but only once), that means we can assign value to final keyword by taking manual input from user, but once value is been assigned then cannot be altered.

Example

final int? number;

number = int.parse(stdin.readLineSync());

Print(number);
//Now number is already assigned.
//then it can’t be altered again like this;

number = 100; // Error: Not Possible to change the value.


Example on final & const keyword

void main(){
     finalvariable(500);
     constvariable(5);
}

void finalvariable(int value){
  final finalvariable = value;
  print(finalvariable);

   //finalvariable = 5000; // this is not possible
}
void constvariable(int value){

  const directinit = 100;
  print(directinit);
 // const variableconst = value; // after compile time, initializing value to const variable is not possible

}

What is ArmStrong Number | ArmStrong Program in dart

0
what is armstrong number - dart program to check armstring number
what is armstrong number - dart program to check armstring number

Hi Guys, Welcome to Proto Coders Point. In this dart tutorial we will learn what is Armstrong number & then let’s write a dark program to check if a given number is a armstrong number or not.

This are the basic program been asked in most of the coding interviews so freshers who are applying for job must know armstring program.

What is Armstrong number

A Armstrong number, when each of its digits is raised to the power, number of digits in a number & the sum of it will be same as the number is called as armstrong number.

Eg: Let's take a number '370'.
  
370, so we have 3 digit number, therefore, each of its digits in 370 will have power of 3.

370 = 33 + 73 + 03
       = 27 + 343 + 0
       = 370
 It's a ArmStrong Number

Let’s Take one more Example(Not an Armstrong)

Let a Number be  '1234'

1234, so it is a 4 digit armstrong number to be checked ok. Therefore each digit in 1234 will have power as 4.

1234 = 14 + 24 + 34 + 44
= 1 + 8 + 81 + 256
1234 != 346

It's not a Armstrong number.

Armstrong are also called as plus perfect or Narcissistic number.

Few Example on armstrong number

1: 11 = 1

2: 21 = 2

3: 31 = 3

371: 33 + 73 +13 = 371

407 = 43 + 03 + 73 = 407

1634: 14 + 64 + 34 + 44 = 1 + 1296 + 81 + 256 = 1643

8208 = 84 + 24 + 04 +84 =8208

Armstrong number program in dart

The following program will check if the given number is armstrong number or not.

import 'dart:io';
import 'dart:math';
void main(){
  
  int? num;
  print('Enter A Number to check ARMSTRONG or NOT ARMSTRONG NUMBER');
  // user will enter a number to check
  num = int.parse(stdin.readLineSync()!);
 
  // user entered number is passed to function
  isArmString(num);

}

//a function to check arm strong
void isArmString(int number){
  //initial some variable
  int temp,digits =0, last = 0, sum = 0;

  //assign user entered number to temp variable
  temp = number;

// loop execute until temp is 0 and increment digits by 1 each loop
  while(temp>0){
    temp = temp~/10;
    digits++;
  }

  //reset temp to user entered number
  temp = number;

  //another loop for getting sum
  while(temp>0){
    last = temp % 10;
    sum = sum + pow(last, digits) as int;
    temp = temp~/10;   
  }

   // now if number and sum are equal its a arm strong number
  if(number == sum){
    print("IT'S A ARMSTRONG NUMBER");
  }else{
    print("IT'S NOT ARMSTRONG NUMBER");
  }
}

Result output

dart armstrong program output
dart armstrong program output

The below Dart Program will print all the ArmString number from 0 to specified input by user.

import 'dart:io';
import 'dart:math';
void main(){
  
  int? num;
  print('Enter A Number to check ARMSTRONG or NOT ARMSTRONG NUMBER');
  // user will enter a number to check
  num = int.parse(stdin.readLineSync()!);
 
  // user entered number is passed to function
  print('________________________________________-');
  for(int i = 0;i<=num;i++)
  {
     //if i is arm strong then print it else don't
     if(isArmString(i))
     {
       print(i);
     }
  }
  

}

//a function to check arm strong
bool isArmString(int number){
  //initial some variable
  int temp,digits =0, last = 0, sum = 0;

  //assign user entered number to temp variable
  temp = number;

// loop execute until temp is 0 and increment digits by 1 each loop
  while(temp>0){
    temp = temp~/10;
    digits++;
  }

  //reset temp to user entered number
  temp = number;

  //another loop for getting sum
  while(temp>0){
    last = temp % 10;
    sum = sum + pow(last, digits) as int;
    temp = temp~/10;   
  }

   // now if number and sum are equal its a arm strong number
  if(number == sum){
    return true;
  }else{
    return false;
  }
}

result output

print arm strong number from range specified


Recommended Dart programs

How to generate random number in dart

pattern program in dart

palindrome program in dart

String to ASCII in dart

Fibonacci sequence in dart

prime number program in dart

GetX Flutter check internet connection – Connectivity – State Management

0

Hi Guys, Welcome to Proto Coders Point.

In this Flutter tutorial(Article) we will learn how to check internet connection continuously in flutter by using flutter connectivity package & implement network change state management using Flutter GetX package.

About flutter connectivity package

This plugin is very useful if your app need internet connection to run the application perfectly, This Library allows your flutter Application to Discover Network Connectivity. This Flutter Library will also check if your  mobile is currently using cellular mobile data  or is using WiFi Connection.

This Flutter Plugin Perfectly works for Both Android and iOS devices, So it is been rated with 100 points in Flutter Library Store.

Video Tutorial


Flutter check internet connection using Connectivity and GetX State management package

Project Files Structure of references

Note: In File Structure, ‘generated_plugin_registrant.dart’ get automatically created when you add below dependencies. You no need to create it.

1. Add Dependencies

dependencies:
  get:
  connectivity:

As we know, we need 2 packages i.e. Flutter GetX and Flutter connectivity.

Flutter GetX: To implement State Management, suppose if Internet Connection changed, to update the state of app and tell about the network change by updating UI screen of users.

Flutter Connectivity: This package plugin helps to check connectivity, if you are connected to WIFI or Mobile Data or if flutter no internet connection. Note: Connectivity plugin has stopped further updated, so Kindly use Connectivity_plus. Don’t worry code is same as it is in Connectivity plugin.

2. GetX State management- flutter check internet connection

Now, Create a dart file in lib directory of your flutter project.

I have created the file and named it as ‘GetXNetworkManager.dart’

GetXNetworkManager.dart

This Class manager all the network related task such as checkConnectivity, ConnectivityResult weather your mobile is connected to WIFI, Mobile Data, or no Internet connection.

import 'dart:async';

import 'package:connectivity/connectivity.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';

class GetXNetworkManager extends GetxController
{
   //this variable 0 = No Internet, 1 = connected to WIFI ,2 = connected to Mobile Data.
   int connectionType = 0;

   //Instance of Flutter Connectivity
   final Connectivity _connectivity = Connectivity();

   //Stream to keep listening to network change state
   late StreamSubscription _streamSubscription ;

  @override
  void onInit() {
     GetConnectionType();
     _streamSubscription = _connectivity.onConnectivityChanged.listen(_updateState);
  }

  // a method to get which connection result, if you we connected to internet or no if yes then which network
   Future<void>GetConnectionType() async{
    var connectivityResult;
    try{
      connectivityResult = await (_connectivity.checkConnectivity());
    }on PlatformException catch(e){
      print(e);
    }
    return _updateState(connectivityResult);
   }

   // state update, of network, if you are connected to WIFI connectionType will get set to 1,
   // and update the state to the consumer of that variable.
   _updateState(ConnectivityResult result)
   {
     switch(result)
     {
       case ConnectivityResult.wifi:
               connectionType=1;
               update();
               break;
       case ConnectivityResult.mobile:
         connectionType=2;
         update();
         break;
       case ConnectivityResult.none:
         connectionType=0;
         update();
         break;
       default: Get.snackbar('Network Error', 'Failed to get Network Status');
       break;

     }
   }

  @override
  void onClose() {
    //stop listening to network state when app is closed
     _streamSubscription.cancel();
  }
}

3. Getx initial Binding

Now, create one more dart file for bindings between GetXNetworkManager.dart and main.dart.

I have create it and named it as ‘NetworkBinding.dart’

This dart file, class extends Bindings & must have a @override method i.e. Dependenies(), which will then load our GetXNetworkManager class by using Get.LazyPut().

import 'package:get/get.dart';
import 'package:getx_check_internet/GetxNetworkManager.dart';

class NetworkBinding extends Bindings{

  // dependence injection attach our class.
  @override
  void dependencies() {
    // TODO: implement dependencies
    Get.lazyPut<GetXNetworkManager>(() => GetXNetworkManager());
  }

}

4. main.dart file

In main.dart file , instead of simple MaterialApp, we are using GetMaterialApp, inside it we are using a property called as initialBinding that then invoke GetXNetworkManager class.

Then in stateful widget, we create an Instance of GetXNetworkManager(GetXController) class so that we can use properties of GetXNetworkManager from main.dart.

main.dart

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_check_internet/GetxNetworkManager.dart';
import 'package:getx_check_internet/NetworkBinding.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      //Initiate Bindings we have created with GETX
      initialBinding: NetworkBinding() ,
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {


  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  // create an instance
  final GetXNetworkManager _networkManager = Get.find<GetXNetworkManager>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Network Status',style: TextStyle(fontSize: 20),),
            //update the Network State
            GetBuilder<GetXNetworkManager>(builder: (builder)=>Text((_networkManager.connectionType == 0 )? 'No Internet' : (_networkManager.connectionType == 1) ? 'You are Connected to Wifi' : 'You are Connected to Mobile Internet',style: TextStyle(fontSize: 30),)),

          ],
        ),
      ),
    );
  }
}


Output


Palindrome program in dart – Check if Number, String is palindrome or not

0
palindrome program in dart
palindrome program in dart

Hi Guys, Welcome to Proto Coders Point.

In this dart programming article, we will learn what is a palindrome, A dart Programs on “how to check if a number is palindrome”, “check if string is palindrome or not”.

What is a Palindrome – number, string

Palindrome meaning(defination), A Number or a string when reversed looks same and pronounced same as it was before reversing.

For Example: 656 when reversed will be same, ( it’s a palindome number), 657 when reversed is 756 so ( it’s not a palindrome number). like wise 252,25252,49694.

String Example for palindrome: NITIN, MADAM, ABBA, MAM, STRAW WARTS, DAMMIT IM MAD.

Palindrome Number algorithm – Code Work flow

  1. Get a number to check if palindrome or not.
  2. Store the same number, in temp variable.
  3. Reverse number using mathematical operation or string methods.
  4. Now compare temp variable with the reversed number value.
  5. If both number match ‘Then it’s a palindrome number’
  6. Else ‘Not a Palindrome Number’

Now Let’s see a palindrome number program in dart language.

void main(){
  int reminder, sum =0, temp;
  int number = 54545;

  temp = number;

  // a loop to reverse a number
  while(number>0)
  {
    reminder = number % 10;  //get remainder
    sum = (sum*10)+reminder;
    number = number~/10;
  }
  
  if(sum == temp)
  {
    print('Its A Palindrome number');

  }else{
    print('Its A Not Palindrome number');
  }


 // StringNumber();
}
palindrome number output
not a palindrome number

Palindrome program in dart programming language (Another way)

Here in below dart program, A user can input either a number or string to check for palindrome or not.

Here we are accepting a input from a user and then reverse the string and then matching them.

How to reverse a string in dart

stringValue!.split('').reversed.join('')
import 'dart:io';
void main(){
print('Enter Words or number');
    // User enter a string or a number
    String? original =  stdin.readLineSync();
  
   // then we will reverse the input
   String? reverse = original!.split('').reversed.join('');

  // then we will compare
  if(original == reverse)
  {
    print('Its A Palindrome');

  }else{
    print('Its A Not Palindrome');
  }
 
}
check is given input is palindrome or not a palindrome

Recommended dart basic programs

Generate random number in dart

String to ASCII in dart

Pattern Program in dart

Fibonacci program in dart

prime number program in dart

Learn dart basic programs