Flutter Questions and Answers

What is Flutter?
Flutter is a mobile application SDK that includes frameworks, widgets, and tools, providing developers with a simple and efficient way to build and deploy beautiful mobile applications on Android and iOS.


What can Flutter do?
For users, Flutter can make the application interface beautiful and vivid


What types of applications can Flutter build?
Flutter is optimized for 2D mobile applications that want to run on Android and iOS. You can use Flutter to build full-featured applications, including cameras, geolocation, networking, storage, third-party SDKs, and more


Who created Flutter?
Flutter is an open source project with contributions from Google and the community


Does Flutter come with a framework?
Yes! Flutter uses modern frameworks inspired by React. Flutter's framework is designed to be layered and customizable (optional). Developers can choose to use only part of the framework or a different framework


Does Flutter have its own set of widgets?
It is! Flutter with a set of high-quality Material Design and Cupertino (iOS style) of the widget, including both layout and theme. Of course, these widgets are just a starting point. Flutter is designed to make it easy for you to create your own widgets, or customize existing widgets


Does Flutter come with a testing framework?
Yes, Flutter provides APIs for writing unit and integration tests. Learn more about Flutter testing .

We use the test function to test our SDK and measure the test coverage for each submission


What technology does Flutter use?
Flutter is built using C, C ++, Dart, and Skia (2D rendering engine). See this architecture diagram to better understand the major components


How does Flutter run my code on Android?
The C / C ++ code of the engine is compiled with Android's NDK, and any Dart code is AOT compiled into native code. Flutter applications run using a native instruction set (without involving the interpreter)


How does Flutter run my code on iOS?
The C / C ++ code of the engine is compiled using LLVM, and any Dart code is AOT compiled into native code. Flutter applications run using a native instruction set (without involving the interpreter)


What operating systems can I use to build Flutter applications?
Flutter supports development on Linux, Mac, and Windows


What language is Flutter developed in?
We studied a lot of languages ??and runtimes, and eventually adopted Dart as the language of the development framework and widget. The underlying graphics framework and Dart virtual machine are implemented in C / C ++


How does the Flutter application perform?
The Flutter application performs very well. Flutter is designed to help developers easily achieve a constant 60fps. Flutter applications run through natively compiled code-no interpreter is involved. This means that Flutter applications can be launched and executed quickly


How is the Flutter development experience? How long is it between editing and refreshing?
Flutter implements a hot-reload development cycle. You can implement sub-second overloading on your device or simulator.

Flutter's hot reloading is stateful , which means that the application state is retained after reloading. So you can quickly iterate through the various pages in your application without having to start over from the home screen after each reload.


How is Hot Reload different from a Full Restart?
Hot Reload works by injecting updated source code files into a running Dart VM (virtual machine). This includes not only adding new classes, but also adding methods and fields to existing classes, and changing existing functions. Although there are several types of code changes that cannot be hot restarted:

  • Global variable initializer.
  • Static field initializer.
  • main()Application method


What device and operating system versions does Flutter support?
Mobile operating system: Android Jelly Bean, v16, 4.1.x or later and iOS 8 or later.

Mobile hardware: 64-bit iOS devices (starting with iPhone 5S and newer iPhone models) and ARM Android devices


Why is flutter APK or IPA so big?
Generally, resources include images, sound files, fonts, etc. These are the majority of APK or IPA. Various tools in the Android and iOS ecosystem can help you understand what's in the APK or IPA.

Also, be sure to use the Flutter tool to create a release version of the APK or IPA. The release version is usually much smaller than the debug version

Dart Top 10 Interview Questions

1) What does ".." mean in Dart?

".." in Dart means "cascade operator", and is used for easy configuration.

The difference between ".." and "." Is that the return from calling ".." is equivalent to this, and "." Returns the value returned by the method


2) Explain Dart scope?

Dart is no "public" "private," and other keywords, the default is public, private variables with an underscore _beginning


3) Is Dart a single-threaded model? How does it work?

Dart is a single-threaded model

Dart runs in a single thread with a message loop mechanism, which contains two task queues, one is a "micro task queue" microtask queue and the other is called an "event queue" event queue .
After the entry function main () is executed, the message loop mechanism is started. First, the tasks in the micro task queue will be executed one by one in accordance with the FIFO order. After all the micro task queues are executed, the tasks in the event queue will be executed. After the event tasks are executed, the micro tasks will be executed. Endlessly


4) How does Dart multitasking work in parallel?

Dart doesn't have multithreading, Dart which provides a similar new thread, but the worker does not operate independently of shared memory - an isolate


5) What is Dart Future?

Dart runs in a single thread with a message loop mechanism, which contains two task queues, one is a "micro task queue" micro task queue and the other is called an "event queue" event queue .

Future is in fact the case to the "event queue" in insert an event, when there is free time to go to perform, when finished will default callback Future.then(v)method.

And we can also use Future.microtaskto insert a mission to "micro-task queue" method, which would improve the efficiency of his execution.

Because in each isolate of Dart, the execution priority is: Main> MicroTask> EventQueue


6) What is Dart Stream

Stream, like Feature, is a tool for handling asynchronous.

But the difference between Stream and Feature is that Stream can receive multiple asynchronous results, while Feature has only one.

Stream can be used to create Stream.fromFuture, can also be used StreamController to create and control.

Another point to note is that an ordinary Stream can only have one subscriber. If you want to subscribe, you must use it asBroadcastStream()


7) Explain Lifecycle of StatefulWidget?

initState(): Widget initializes the current State. The Context cannot be obtained in the current method. If you want to obtain it, you can try Future.delayed()

didChangeDependencies(): In initState()the call, State the time change of the object dependencies will be called.

deactivate(): When State the time is temporarily removed from the tree view calls this method, this method is also called when the page switching, and Android in the onPause same.

dispose(): Called when the widget is destroyed.

didUpdateWidget: Called when the widget state changes


8) How does Flutter communicate with Android iOS?

Flutter by PlatformChannelinteracting with native, which PlatformChannelis divided into three types:

BasicMessageChannel: Used to pass strings and semi-structured messages.
MethodChannel: Used to pass method calls. Flutter actively calls Native methods and gets the corresponding return value.
EventChannel: for communication of event streams


9) What are Widgets, RenderObjects, and Elements?

Widget Only used to store the information needed for rendering.
RenderObject Responsible for managing layout, drawing and other operations.
Element This is the entity on this huge control tree


10) What is state management and why is it needed?

First of all, state is actually a conceptual thing, distinguishing between global state and local state.

The local state is, for example, the information entered in a control, and the global state is, for example, the userId requested from the background after login.

When more and more global states exist and multiple pages share a state, we need to manage it.

Common state management is:

  • ScopedModel
  • BLoC
  • Redux / FishRedux
  • Provider

11) What is BLoC Mode?

BLoC is a method of building applications using reactive programming. This is a completely asynchronous world composed of streams

How to get complete address from latitude and longitude?

How to get following values from Latitude and Longitude in android

  • Street Address
  • City / State
  • Zip
  • Complete Address

We can achieve this by following code in android. 

Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());

addresses = geocoder.getFromLocation(latitude, longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5

String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL

Get Address from Latitude and logintude android

How to validate email address in Android with Kotlin?

With the below code we can validate email address in android.

import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
   private lateinit var editText: EditText
   private lateinit var email: String
   private val emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+"
   override fun onCreate(savedInstanceState: Bundle?) {
      title = "KotlinApp"
      editText = findViewById(R.id.editText)
      email = editText.text.toString().trim()
   fun validateEmail(view: View?) {
      if (email.matches(emailPattern.toRegex())) {
         Toast.makeText(applicationContext, "Valid email address",
      } else {
         Toast.makeText(applicationContext, "Invalid email address",


How to search a string in MySql Table?

By using equal operator we can search a string inside table data.

Create a Table

mysql> create table UserTable
   -> (
   -> FirstName varchar(100),
   -> LastName varchar(100)
   -> );


Insert few records in the above created table

mysql> insert into DemoTable values('RR','Tutors');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable values('Miche','Tutortech');
Query OK, 1 row affected (0.19 sec)


Fetch all records from table by

mysql> select *from UserTable;

Ths will return below data

| FirstName | LastName |
| RR           | Tutors     |
| Miche     | Tutortech|
2 rows in set (0.00 sec)


Following is the query to search a MySQL table for a specific string

mysql> select *from DemoTable where LastName='Tutors';



| FirstName | LastName |
| RR        | Tutors   |
1 row in set (0.00 sec)

How to create a table in Java with JDBC Connection?

By using CREATE TABLE query we can create table.


CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
columnN datatype,
PRIMARY KEY( columns )


To create a table with JDBC we need to follow these steps

  • Register the driver − Register the driver class using the registerDriver() method of the DriverManager class. Pass the driver class name to it, as parameter.
  • Establish a connection − Connect ot the database using the getConnection() method of the DriverManager class. Passing URL (String), username (String), password (String) as parameters to it.
  • Create Statement − Create a Statement object using the createStatement() method of the Connection interface.
  • Execute the Query − Execute the query using the execute() method of the Statement interface.



import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class CreateTableExample {
   public static void main(String args[]) throws SQLException {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/Mydatabase";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Creating the Statement
      Statement stmt = con.createStatement();
      //Query to create a table
      String query = "CREATE TABLE Employees("
         + "ID INT NOT NULL, "
         + "NAME VARCHAR (20) NOT NULL, "
         + "AGE INT NOT NULL, "
         + "SALARY DECIMAL (18, 2), "
         + "ADDRESS VARCHAR (25) , "
         + "PRIMARY KEY (ID))";
      System.out.println("Table Created......");



while run the above program will return following output

Connection established......
Table Created......


What is the use of ‘git log’?

To find specific commits in your project history- by author, date, content or history ‘git log’ is used

What is the difference between git pull and git fetch?

Git pull command pulls new changes or commits from a particular branch from your central repository and updates your target branch in your local repository.

Git fetch is also used for the same purpose but it works in a slightly different way. When you perform a git fetch, it pulls all new commits from the desired branch and stores it in a new branch in your local repository. If you want to reflect these changes in your target branch, git fetch must be followed with a git merge. Your target branch will only be updated after merging the target branch and fetched branch.


How to delete branch in git?

To delete a branch use, the command “git branch –d [head]”

How to create branch in git?

By using below commands we can create/switch new branch


git checkout [branch name]

used to switch from one branch to another.

git checkout -b [branch name]

creates a new branch and also switches to it

How to resolve conflict in git?

To resolve the conflict in git, edit the files to fix the conflicting changes and then add the resolved files by running “git add” after that to commit the repaired merge,  run “git commit”.  

Git remembers that you are in the middle of a merger, so it sets the parents of the commit correctly

What is a ‘conflict’ in git?

A ‘conflict’ arises when the commit that has to be merged has some change in one place, and the current commit also has a change at the same place. Git will not be able to predict which change should take precedence

What is ‘head’ in git and how many heads can be created in a repository?

A ‘head’ is simply a reference to a commit object. In every repository, there is a default head referred as “Master”.  A repository can contain any number of heads

What is mean by ‘git config’ ?

The ‘git config’ command is use to set configuration options for Git installation.  

Like Behaviour of a repository, user info, preferences etc. can be defined through this command

git config user.email

git config --global user.email "your_email@example.com"


How can you create a repository in Git?

  • To create a repository, create a directory for the project if it does not exist
  • Run command “git init”. By running this command .git directory will be created in the project directory, the directory does not need to be empty

What is a repository in Git?

A repository contains a directory named .git, where git keeps all of its metadata for the repository. The content of the .git directory are private to git

What is a commit message?

The command that is used to write a commit message is “git commit -a”.
here -a on the command line instructs git to commit the new content of all tracked files that have been modified. Also, mention you can use “git add <file>” before git commit -a if new files need to be committed for the first time

List out Git repository hosting services

  • Pikacode
  • Visual Studio Online
  • Github
  • Gitlab
  • Bitbucket
  • SourceForge
  • GitEnterprise

What is the difference between Git and SVN?



Git is a Decentralized Version Control tool

SVN is a  Centralized Version Control tool

It belongs to the 3rd generation of Version Control tools

It belongs to the 2nd generation of Version Control tools

Clients can clone entire repositories on their local systems

Version history is stored on a server-side repository

Commits are possible even if offline

Only online commits are allowed

Push/pull operations are faster

Push/pull operations are slower

Works are shared automatically by commit

Nothing is shared automatically

What are the important features of Java 8?

Java 8 is the newest version of java released by oracle in the year of 2014. It includes various enhancements.

Following are features of Java 8:

  • Functional Interfaces
  • Stream API
  • Lambda Expressions
  • Java IO improvements
  • Collection API improvements
  • Default and static methods in interfaces
  • JDBC Enhancements
  • ForEach() method

What is the difference between JDK and JRE?

To run applications of java and also applets, JRE needed to be downloaded and to develop and run java applications and applets JDK is required


What is JRE?

Java Runtime Environment (JRE) is a part of Java development Kit (JDK). It provides a runtime environment for the java programs to get executed and it consists of certain set of programming tools for developing java applications


What is JDK?

Java Development KIT (JDK) is a software development environment which is used for developing java applications. Different JDKs are available for various platforms such as Windows, Linux etc..

What is a Class/Static Variables?

Class variables are also known as static variables. These are the variables that are declared within a class with static keyword but, outside of a method

What is Instance variable?

This is the variable which is declared within the class and outside of the method. Instance variable is created when an object is created with a keyword ‘new’ and destroyed when that object got destroyed

What is the Difference between Path and ClassPath in java?

Path is an environmental variable which specifies the bin directory path of JDK/JRE from which binaries under that directory can be accessed directly.

ClassPath is the location of .class file where classes we compiled will be available

Convert given time in String format to seconds

We can convert given time to seconds in different formats here we acan find below way

if the given time is minuts and seconds string


String time = "11:12"; //mm:ss
String[] timeinArray= time.split(":"); //will break the string up into an array
int minutes = Integer.parseInt(timeinArray[0]); //first element
int seconds = Integer.parseInt(timeinArray[1]); //second element
int duration = 60 * minutes + seconds; //add up our values


if given time in hours, minuts and seconds then

String time = "01:11:12"; //hh:mm:ss

String[] timeinArray= time.split(":"); //will break the string up into an array int

int hours = Integer.parseInt(timeinArray[0]); //first element int

int minutes = Integer.parseInt(timeinArray[1]); //second element

int seconds = Integer.parseInt(timeinArray[2]); //third element

int duration = 60 *60 * hours+60 * minutes + seconds; //add up our values


How to Create Objects in Java?

As per java, a class is nothing but blueprint of an objects, We create an object from a class. 
We have different ways to create object for class in Java.

1) Using new Keyword : 
Creating Object with new keyword is the  common way  in java.  By using this way we can call any constructor we want to call (no argument or parameterized constructors).

public class ObjectWithNew


    String name = "New Key Word";

    public static void main(String[] args) 


        // Here we are creating Object of 

        // ObjectWithNew using new keyword

        ObjectWithNew obj = new ObjectWithNew();






2) Using New Instance : Suppose if we know the name of the class & it has a public default constructor we can create an object by Class.forName.  Class.forName loads the Class in Java, it doesn’t create any Object. To Create an Object of the Class we have to use the new Instance Method of the Class.

public class ObjectWithNewInstance


    String name = "Object with New Instance";

    public static void main(String[] args)




            Class cls = Class.forName("ObjectWithNewInstance");

            ObjectWithNewInstanceobj =

                    (ObjectWithNewInstance) cls.newInstance();



        catch (ClassNotFoundException e)




        catch (InstantiationException e)




        catch (IllegalAccessException e)







 3) Using clone() method:

On calling  clone() for any object, the JVM creates a new object and copies all content of the previous object into it. Creating an object by the clone method does not invoke any constructor.
To use clone() method for an object we need to implement Cloneable and define the clone() method in it.

public class ObjectWithClone implements Cloneable



    protected Object clone() throws CloneNotSupportedException


        return super.clone();


    String name = "Object with Clone";


    public static void main(String[] args)


        ObjectWithClone  obj1 = new ObjectWithClone();



            ObjectWithClone obj2 = (ObjectWithClone ) obj1.clone();



        catch (CloneNotSupportedException e)







Memory Allocation in Java

 In java all variables are stored in a stack. local variables are de-allocated in a LIFO (Last in first out) order as soon as the method terminates.
All dynamically allocated arrays and objects are stored in heap.  No need to deallocate these memory in any specific order. They can be garbage collected (removed from the memory) as soon as  their use is over.

Garbage Collection in Java
       An object that is not referred by any reference variable will be deallocated their memory by the garbage collector. SO those variables become garbaged.

 Garbage Collection is automatic.
A reference variable is declared within a function, then that reference is invalidated soon as the function call ends.

What is Method Overloading in Java ?

Java is Object Oriented Programming Language, means it contains classes and objects.
A class in java contains methods and properties. A class with multiple methods with same and different arguments is called Method overloading.
 These arguments can be defined in different ways.

  • No of parameters
  • Data type of parameters
  • Sequence of parameters

void print(int i){
void print(double d){
void print(char c){

Method Overloading in Java is Static Polymorphism
Calls to overloaded methods will be resolved during compile time, In other words, when the overloaded methods are invoked, JVM will choose the appropriate method based on the arguments used for invocation. 


void add (int a, int b)
void add (int a, float b)
void add (float a, int b)
void add (int a, int b, float c)


Methods differing only in return type
Methods differing only in return type will not be treated as overloaded methods, it will be compilation error. For Example, the below given methods will give compilation error

void print(int k){
int print(int k)){
    return k;


Overloading the Constructors

public class Teacher{
    public Teacher(){
        mark = 100;
    public Teacher(int rollNo, double mark){
        this.rollNo = rollNo;
        this.mark = mark;


How can I get battery level and state (plugged in, discharging, charging, etc) in iOS?

We need to write below code for monitoring the battery

UIDevice.current.isBatteryMonitoringEnabled = true


After that we retrieve the battery state by using this method

var batteryState: UIDevice.BatteryState {
        return UIDevice.current.batteryState

And write switch cases for those batterysate and we can get the state.

func updateBatteryStateLabel() {
        switch batteryState {
        case .charging:
            status = "Charging"
        case .unknown:
            status = "Unknown"
        case .unplugged:
            status = "Unplugged"
        case .full:
            status = "Full"
        DispatchQueue.main.async {
            self.batteryStsLbl.text = "B: \(self.status)"


How do i get build/version number of an iOS App?

By using the below code we can get the version of the app


let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String

By using the below code we can get the build of the app

let build = Bundle.main.infoDictionary?["CFBundleVersion"] as? String




How to make a phone call in iOS 10 using Swift?

In simulator we can’t test in below code using device we can try

1234567970 - example phone number


let url: NSURL = URL(string: "TEL://1234567970")! as NSURL

        UIApplication.shared.open(url as URL, options: [:], completionHandler: nil)


We can write above code as one function and call that method in viewdidload. (Or) write above code as it is in viewdidload method.

How to take a screenshot on iOS programmatically ?

When we want to create screenshot programmatically in Ios follow the below code

if UIScreen.main.responds(to: #selector(NSDecimalNumberBehaviors.scale)) {
            UIGraphicsBeginImageContextWithOptions(self.view!.bounds.size, false, UIScreen.main.scale)
        self.view?.layer.render(in: UIGraphicsGetCurrentContext()!)
        let image : UIImage = UIGraphicsGetImageFromCurrentImageContext()!

//save the screen shot in photos album by using this below line

        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)

And save the screenshot  in photo library then we need to add the Privacy - Photo Library Additions Usage Description in Info.plist file


How to prevent the screen from sleeping in iOS Programmatically?

When most apps have no touches as user input for a short period, the system puts the device into a "sleep” state where the screen dims. This is done for the purposes of conserving power

By using this property isIdleTimerDisabled we can stop the iOS screen sleeping mode. When it is set to true means the screen will never dim or sleep while  your app is running.

When it is set to true - we don’t want to waste users battery life

UIApplication.shared.isIdleTimerDisabled = true


What is RxJava?

RxJava is essentially an asynchronous operation library, which is an asynchronous event library that allows you to process tedious and complex tasks with extremely simple logic

How can i get document id in Flutter Firestore?

In Flutter Firestore integration Firestore save data in the form of Documents and Collections.

Unlike SQl database in firestore there are no tables and rows. Always data will be store in the form of Documents.

What is Firestore Document?

A unit of Storage space in firestore is called Document.

These documents are stored inside collections.

Each Document resides inside collection, means collections are containers for the Documents.

Each Document contains unique represented by its id. This id called documentId


To get DocumentId for any document we need to create reference for that Document.

docRef:= client.Collection("collectionname").Doc("docname")



from instance of docRef we will get the Docuement id



How to create two dimensional array in ruby?

Ruby doesn't have any class like two dimensional Array.
The combination of 1dimensional array will called TWo dimensional array.

Let's create Two dimensional array


Array = [ [val1,val2], [val3,val4], ... ]



# a two-dimensional array declaration

arr = [[1,2],[2,3],['Sachin','India'],['Pointing','Australia']]

# printing

puts "The two dimensional Array elements are:"

print arr



The two dimensional Array elements are:
[[1, 2], [2, 3], ["Sachin", "India"], ["Pointing", "Australia"]]


Creating Two Dimensional Array with Array.new() method


 array_name = Array.new(size, Array.new)



How to Sort Array in Ruby?

Ruby has built-in methods to sort given array.

  • sort
  • sort_by
  • sort!


Array.sort -> new_array

This sort will retruns new Array

similarly sort! will also sort the array, instead of creating new array it will modify the existing array


# Array with initail values

numbers = [5,3,2,1]

# sort numbers array and return new array with sorted elements.



=> [1, 2, 3, 5]


with sort!

# Array with initail values

numbers = [5,3,2,1]

# sort numbers array and return new array with sorted elements.




=> [1, 2, 3, 5]


Customized Sorting With sort_by


Sort by length

strings = %w(foo test blog a)




=> ["a", "foo", "test", "blog"]


Example 2:

table = ["Kiran","Powel","Polard","Lara","Shreya","Shakeela"]

puts "Array sort implementation"

new_arr = table.sort{|a,b| b<=>a}

puts "Array after sorting: #{new_arr}"

puts "Original Array instance: #{table}"



Array sort implementation
Array after sorting: ["Shreya", "Shakeela", "Powel", "Polard", "Lara", "Kiran"]
Original Array instance: ["Kiran", "Powel", "Polard", "Lara", "Shreya", "Shakeela"]


Sort by Capital Words

Example 3:

text="Ruby is programming Language"



.sort_by { |w| w[0].match?(/[A-Z]/) ? 0 : 1 }

.join(" ")



=> "Ruby Language is programming"


Sort in Reverse Order

How to sort array revers order with length


strings = "Ruby is Programming language"

strings.split.sort { |a,b| a.length <=> b.length }



=> ["is", "Ruby", "language", "Programming"]


How to shuffle an array in Ruby?

shuffle!() is a Array class method which shuffles elements in an array





With shuffle!() method we will shuffle the given array elements.

a = [1, 22, 123, nil, 2, 3]

# declaring array

b = [12, 24, 41, 1, 48, 99]

# declaring array

c = [18, 22, 50, 6]

# shuffle! method example

puts "shuffle!() method form : #{a.shuffle!()}\n\n"

puts "shuffle!() method form : #{b.shuffle!()}\n\n"

puts "shuffle!() method form : #{c.shuffle!()}\n\n"



shuffle!() method form : [2, 1, 123, 3, nil, 22]

shuffle!() method form : [24, 99, 48, 1, 12, 41]

shuffle!() method form : [50, 18, 6, 22]


How to Replace array elements in Ruby?

This Example explain how to replacing elements in Array.
Replcing array elements in ruby by Array.replace() Method.




This method takes an array instance(object) as the parameter. It will throws exception if we do not provide any array instance


# array declaration

programming = ["Java","Flutter","Python","React"]

puts "Array replace implementation."

replacements = ["Kotlin","ReactNative"]


puts "Array elements are:"

print programming



Array replace implementation.
Array elements are:
["Kotlin", "ReactNative"]


How to get index of array element in Ruby

Ruby Array contains method index() to get the selected element index inside array.





# array declaration

lang = ["Java","Flutter","ReactNative","Ruby","Perl"]

puts "Array index implementation."

puts "Enter the element whose index you want to find:"

ele = gets.chomp

if(ind = lang.index(ele))

  puts "#{ele} found at index #{ind}"


  puts "Array doesn't contains given element"




Array index implementation.
Enter the element whose index you want to find:
Flutter found at index 1


How to add/remove elements to Array in Ruby?

To add or remove lements to/from array in Ruby we have different methhods.

Array.push method to add elements into Array


# creating an empty array

arr1 = Array.new()


# adding String element into arra1

arr1.push "another string";

puts arr1;

puts "\n Addding New Element"

# adding Integer element into arra1

arr1 .push 2;

puts arr1;


another string
Addding New Element
another string


Array.pop method to remove lement from array

pop() will remove one by one element from Array.


# creating an empty array

arr1 = Array.new()

# adding String element into arra1

arr1.push "another string";

puts arr1;

puts "\n adding New Element"

# adding Integer element into arra1

arr1 .push 2;

puts arr1;


puts "\n remove last Element"

puts arr1;


puts "\n remove last Element"

puts arr1;



another string

 adding New Element
another string

 remove last Element
another string

 remove last Element


How to delete specifi index Element from Array in Ruby?

Ruby Array has method delete_at() to delete element from specified index.


# creating an empty array

arr1 = Array.new()

# adding String element into arra1

arr1.push "another string";

puts arr1;

puts "\n adding New Element"

# adding Integer element into arra1

arr1 .push 2;

puts arr1;


puts "\n delete element at index 1"

puts arr1;



another string

 adding New Element
another string

 delete element at index 1
another string


Creating Array with Array.new(size, obj) in Ruby

In this example we are going to create array with two arguments in Ruby
Size: Size of array we are going to create
object: The element we are going to store in Array.


array_name = Array.new(size = 0, obj = nil);



# array declaration

arr1 = Array.new(size = 5, obj = "Ruby")


# printing array elements

puts "Elements of \'arr1\' are:"

puts arr1


# creating an empty array

arr2 = Array.new()

puts "Number of elements present in \'arr2\' are: #{arr2.count}"



Elements of 'arr1' are:
Number of elements present in 'arr2' are: 0


how to create an array with Array.[](*args) in Ruby ?


array_name = Array.[]('ele1', 'ele2' , ... ,'eleN')

Below example will show how to define and print array values.


# array declaration

arr = Array.[](1,"Java","FLutter",1.2)


# printing array elements

puts "Elements of \'arr\' are:"

puts arr


# empty array declaration

arr1 = Array.[]()

puts "Number of elements present in \'arr1\' are: #{arr1.count}"



Elements of 'arr' are:
Number of elements present in 'arr1' are: 0


How to create array from User input?

Below example will show it

Example 2

# input array elements

puts "Enter the first element "

ele1 = gets.chomp

puts "Enter the second element "

ele2 = gets.chomp

puts "Enter the third element "

ele3 = gets.chomp

puts "Enter the fourth element "

ele4 = gets.chomp


# creating array using input elements

arr = Array.[](ele1,ele2,ele3,ele4)


# printing array elements

puts "Array elements are:"

puts arr



Enter the first element 
Enter the second element 
Enter the third element 
Enter the fourth element 
Array elements are:


Ruby program to print an array

This example we are print an array values

arr= Array["Java","Kotlin","Flutter","Reactnative"]


#printing single element

puts arr[0]


#printing all the elements in a single row

print arr


#printing one by one using for loop

for i in arr

  puts i



#printing one by one without loop

puts arr



["Java", "Kotlin", "Flutter", "Reactnative"]


Ruby program to generate random numbers

To generate Random number in ruby we will use rand() method

#input upper and lower limits
puts "Enter Max number"
puts "Enter Min number"

#generate and print the random numbers
#between the given lower and upper limit
puts "The random numbers are..."
puts rand(min..max)
puts rand(min..max)
puts rand(min..max)
puts rand(min..max)
puts rand(min..max)



Enter Max number
Enter Min number
The random numbers are...


Ruby program to reverse a string

Reversing a string

We can print the reverse a given number by below ways

By .reverse predefined method

puts "Enter the String:"

puts "The reverse of #{str1} is #{str1.reverse}" 



Enter the String:
The reverse of ruby is ybur


By loop

puts "Enter the String:"

newstr= ' '

for  i in  1..str1.length
    newstr+=str1[str1.length - i]

puts "The reverse of #{str1} is #{newstr}"




Enter the String:
The reverse of ruby is ybur


Ruby program to check whether the given number is prime or not

Checking prime number

What is Prime number?

Prime numbers are those numbers which can only be divisible by itself or 1

puts "Enter the number:"
if (num==0)
    puts "0 is not prime"
        if (num%i==0)
    if count>1
        puts "#{num} is not a prime number"
        puts "#{num} is a prime number"



Enter the number:
2 is a prime number


Enter the number:
11 is a prime number


Ruby program to print Fibonacci series

Fibonacci program in Ruby
Fibonacci series is nothing but a series of numbers in which the current number is the sum of the previous two numbers


puts "Enter the number of terms:-"

puts "The first #{n} terms of Fibonacci series are:-"
        puts nextterm



Enter the number of terms:-
The first 4 terms of Fibonacci series are:-

Enter the number of terms:-
The first 6 terms of Fibonacci series are:-


Ruby program to check whether the given number is Armstrong

This Ruby example will check given number is Armstrong or not


puts "Enter the number"

sum = 0

while num!=0  #implementation of while loop

    puts "The #{temp} is Armstrong"
    puts "The #{temp} is not Armstrong"



Enter the number
The 153 is Armstrong


Ruby program to check whether the given number is palindrome

In this Ruby Example by using while loop we are checking the given number is Palindrome or not

puts "Enter the number"

sum = 0

while num!=0  #implementation of while loop

    puts "The #{temp} is a palindrome"
    puts "The #{temp} is not a palindrome"



First Run

Enter the number
The 123 is not a palindrome


Second Run

Enter the number
The 121 is a palindrome


Ruby program to Calculate the factorial of given number

In this Ruby example to calculate factorial of a number we are using while loop 

puts "Enter the number"

i = 1
fact = 1

while i <= num  #implementation of while loop
    fact *= i
    i += 1

puts "The factorial of #{num} is #{fact}"



Enter the number
The factorial of 5 is 120


Ruby program to add two integer numbers

Adding two numbers in Ruby

To add numbers in ruby we will use below methods

puts: This method is used to display some message to the user.
gets: This method is used to take input from the user.
.to_i: Convert String to Integer.
+: It is a mathematical operator which accepts two numerical parameters and returns a numerical value. A binary operator to add two values

# input the numbers and converting 
# them into integer 
puts "Enter first value: "
puts "Enter second value: "

# finding sum 

# printing the result
puts "The sum is #{sum}"


First run:
Enter first value:
Enter second value:
The sum is 357

Second run:
Enter first value:
Enter second value:
The sum is -23


Program to Print Triangle of Numbers in Ruby

This example will print the numbers in triangle format with increment numbers

array = (1..10).to_a

order = 1

limit = 4


(1..limit).each do |number|

array[order - 1, number].each{|i| print "#{i} " } # will print it in line

order += number

puts # will print a break between your lines




2 3 
4 5 6 
7 8 9 10 


How to Get Input with Gets in Ruby

Ruby provides a number of ways to get input from the user. we will use gets in this example. The gets method is basically the opposite of puts — instead of printing stuff, it gathers what the user types for you.

After print statement, collect the user’s input into a variable (shape_size):

puts "Welcome to Shapes"
print "How big do you want your shape? "
print "How big do you want your shape? "
shape_size = gets


What are the various Ruby runtimes, and how are they different?

mruby: Embedded version of ruby.
CRuby: Matz's Ruby Interpreter (MRI), C language implementation
JRuby: Based on JVM
Rubinius: LLVM(Low Level Virtual Machine)
Opal: turn Ruby into JavaScript
RubyMotion: write Cocoa native apps in Ruby

What are #method_missing and #send? Why are they useful?

method_missing, as the name suggests, is called when the method cannot be found. With this powerful meta-programming tool, we can create dynamic methods, such as the dynamic finder in Active Record

class Legislator
  # Pretend this is a real implementation
  def find(conditions = {})
  # Define on self, since it's  a class method
  def self.method_missing(method_sym, *arguments, &block)
    # the first argument is a Symbol, so you need to_s it if you want to pattern match
    if method_sym.to_s =~ /^find_by_(.*)$/
      find($1.to_sym => arguments.first)

Send is also a powerful tool for dynamic method invocation. Its function is to pass a method to the object in the form of parameters

class Box
  def open_1
    puts "open box"

  def open_2
    puts "open lock and open box"

  def open_3
    puts "It's a open box"

  def open_4
    puts "I can't open box"

  def open_5
    puts "Oh shit box!"

box = Box.new



What are some of your favorite gems? What are their alternatives?

Here are a few commonly used gems I like and their alternatives

  • Rails Efficient web development framework based on MVC design pattern. Alternative
  • Sinatra:: Lightweight web development options
  • jquery-rails:jQuery for rails.
  • haml-rails: Simplify the preparation of the view layer, less troublesome duplicate labels.
    • Alternative:erb-rails
  • devise: User authentication plugin.
  • rspec-rails:test
  • seed-fu: Data initialization
  • faraday: http request and html content analysis

What's the difference between a lambda, a block and a proc?

  1. The difference between Blocks and Procs
    1. Procs is an Object, but Block is not an object, it is just a code snippet
    2. Each method can only pass one code segment at most, but can pass multiple Proc
  2. Similarities and differences between Proc and Lambda

proc = Proc.new {puts "hello world"}
lambda = lambda {puts "hello world"}

proc.class  # rerturn 'Proc'
lambda.class # return 'Proc'

As can be seen from the above, in fact, Proc and lambda are both Proc objects.

lambdaWill check the number of parameters but procnot

lam = lambda { |x| puts x}
lam.call(2)  # print 2
lam.call  # Argument Error: wrong number of arguments (0 for 1)
lam.call(1,2) # Argument Error: wrong number of arguments (2 for 1)

pro = Proc.new {|x| puts x}
proc.call(2)  # print 2
proc.call    # return nil
proc.call(1,2) # print 1

lambda And proc the meaning of the 'return' key is not the same, but proc the return only call in the method body

def lambda_test
  lam = lambda { return }
  puts "hello"

lambda_test   # puts 'hello'

def proc_test
  pro = Proc.new {return}
  puts 'hello'

proc_test  # return nil  hello

Refer: What Is the Difference Between a Block, a Proc, and a Lambda in Ruby?

 How to create Gradient background for AppBar in Flutter

 How to create Gradient background for AppBar in Flutter

new Scaffold(
      appBar: AppBar(
        title: Center(child: Text('Gradient AppBar')),
        flexibleSpace: Container(
          decoration: new BoxDecoration(
            gradient: new LinearGradient(
                colors: [
                  const Color(0xFF3366FF),
                  const Color(0xFF00CCFF),
                begin: const FractionalOffset(0.0, 0.0),
                end: const FractionalOffset(1.0, 0.0),
                stops: [0.0, 1.0],
                tileMode: TileMode.clamp),
      body: ...,


What is difference between HashMap and HashSet in Java

HashMap and HashSet are part of collection framework

Let's check first

What is HashSet in Java?

HashSet is implementation of Set Interface which is not allow duplicate value. By default all methods in Collection Framework are also in Set Interface. Objects which are going to be stored in HashSet must override equals() and hashCode() method so that we can check for equality and no duplicate value are stored in our set. If we have created our own objects we need to implement hashCode() and equal() in such a manner that will be able to compare objects correctly when storing in a set so that duplicate objects are not stored, if we have not override this method objects will take default implementation of this method.

public boolean add(Object o)  Method is used to add an element in a set which returns false if it’s a duplicate value in case of  HashSet otherwise returns true if added successfully.


What is HashMap?

HashMap is an implementation of Map Interface, which maps a key to value. Duplicate keys are not allowed in a map. Basically map Interface has two implementation classes HashMap and TreeMap. Main difference is TreeMap maintains order of the objects but HashMap will not. HashMap allows null values and null keys.HashMap is not synchronized,but collection framework provide methods so that we can make them synchronized if multiple threads are going to access our hashmap and one thread structurally changes our map.

public Object put(Object Key,Object value) method is used to add an element in the map


Difference between HashMap and HashSet 

HashMap Hash Set
HashMap  is an implementation of Map interface HashSet is an implementation of Set Interface
HashMap Stores data in form of  key-value pair HashSet Store only objects
Put method is used to add element in map Add method is used to add element is Set
In hash map hashcode value is calculated using key object Here member object is used for calculating hashcode value which can be same for two objects so equal () method is used to check for equality if it returns false that means two objects are different
HashMap is faster than HashSet because unique key is used to access object HashSet is slower than Hashmap


How to Convert a Map to a List in Java Example

Map and List are two common data structures available in Java

The main difference between Map (HashMap, ConcurrentHashMap or TreeMap) and List is that Map holds two objects key and value while List just holds one object which itself is a value

How to Convert Map into List in Java with Example

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

public class JavamapToList {
    static boolean result;
    public static void main(String[] args)
      HashMap<String, String> javaMaps= new HashMap<String, String>();
        // preparing hashmap with keys and values
        javaMaps.put("JAVA1", "JAVA 1");
        javaMaps.put("JAVA2", "Core Java");
        javaMaps.put("Java3", "JEE");
        javaMaps.put("Java4", "Spring");
        System.out.println("Size of javaMapsMap: " + javaMaps.size());
        //Converting HashMap keys into ArrayList
        List<String> keyList = new ArrayList<String>(javaMaps.keySet());
        System.out.println("Size of Key list from Map: " + keyList.size());
        //Converting HashMap Values into ArrayList
        List<String> valueList = new ArrayList<String>(javaMaps.values());
        System.out.println("Size of Value list from Map: " + valueList.size());

        List<Entry> entryList = new ArrayList<Entry>(javaMaps.entrySet());
        System.out.println("Size of Entry list from Map: " + entryList.size());



Size of javaMapsMap: 4
Size of Key list from Map: 4
Size of Value list from Map: 4
Size of Entry list from Map: 4

What is Difference Between "==" and "equals" method in Java

Main difference between == and equals in Java is , "==" is used to compare primitives while equals() method is used to check equality of objects. Another difference between them is that, If both "==" and equals() is used to compare objects than == returns true only if both references points to same object while equals() can return true or false based on its overridden implementation.One of the popular cases is comparing two String in Java in which case == and equals() method return different results.


Comparing String with == and equals

public class JavaEquals {
    public static void main(String[] args)
        String myjava = new String("My Java Course");
        String javaStr = new String("My Java Course");

        //since two strings are different object result should be false
        boolean result = myjava == javaStr;
        System.out.println("Comparing two strings with == operator: " + result);

        //since strings contains same content , equals() should return true
        result = myjava.equals(javaStr);
        System.out.println("Comparing two Strings with same content using equals method: " + result);

        javaStr = myjava;
        //since both homeLoan and personalLoand reference variable are pointing to same object
        //"==" should return true
        result = (myjava == javaStr);
        System.out.println("Comparing two reference pointing to same String with == operator: " + result);




Comparing two strings with == operator: false
Comparing two Strings with same content using equals method: true
Comparing two reference pointing to same String with == operator: true


Comparing two objects with "==" and equals

public class JavaEquals {
    static boolean result;
    public static void main(String[] args)
        Object obj1 = new Object();
        Object obj2 = new Object();

        // == should return false
        result = (obj1==obj2);
        System.out.println("Comparing two different Objects with == operator: " + result);

        //equals should return false because obj1 and obj2 are different
        result = obj1.equals(obj2);
        System.out.println("Comparing two different Objects with equals() method: " + result);

        // "==" should return true because both obj1 and obj2 points same object
        result = (obj1==obj2);
        System.out.println("Comparing two reference pointing to same Object with == operator: " + result);




Comparing two different Objects with == operator: false
Comparing two different Objects with equals() method: false
Comparing two reference pointing to same Object with == operator: true

What is Java Collections Framework?

Java Collections Framework is a set of re-usable data structures and algorithms.
The Java Collections Framework provides common data structures implementations which are enough for general-purpose such as list, set, map, queue, tree, etc. These collections are high-performance, high-quality, and easy to use with very good documentation.
In addition, the Java Collections Framework provides useful and robust algorithms such as searching and sorting on collections, and the interoperability between collections and arrays

What is a Collection ?

A collection is a data structure that holds a set of objects in a specific manner. It looks like arrays but collections are more advanced and more flexible. An array simply stores a fixed number of objects, whereas a collection stores objects dynamically, i.e. you can add or remove objects as you wish.
A collection also provides useful operations such as adding, removing, retrieving objects.

How to join Multiple String Objects in Java 8

String.join() is introduced in Java8

We can use the String.join() method to join a number of String literals, String objects, String elements from an array, or String elements from List, Set or any collection because it accepts an Iterable


public class JoinString {
    public static void main(String[] args)
        String java= String.join("|", "Cor Java", "JDBC", "JEE");
            System.out.println("Java: " + java);


Java: Cor Java|JDBC|JEE

Join List of String 

List<String> mobiles = Arrays.asList("Apple", "Samsung", "MI");
            String str = String.join(",", mobiles);
            System.out.println("List Mobiles : " + str);


List Mobiles : Apple,Samsung,MI

Explain Fragment Life Cycle

The following are the Android Fragments Life Cycle Callbacks

Managing the life cycle of a fragment is lot like managing the life cycle of an activity

onAttach() : This method will be called first, even before onCreate(), letting us know that your fragment has been attached to an activity. You are passed the Activity that will host your fragment

onCreateView() : The system calls this callback when it’s time for the fragment to draw its UI for the first time. To draw a UI for the fragment, a View component must be returned from this method which is the root of the fragment’s layout. We can return null if the fragment does not provide a UI

onViewCreated() : This will be called after onCreateView(). This is particularly useful when inheriting the onCreateView() implementation but we need to configure the resulting views, such as with a ListFragment and when to set up an adapter

onActivityCreated() :This will be called after onCreate() and onCreateView(), to indicate that the activity’s onCreate() has completed. If there is something that’s needed to be initialised in the fragment that depends upon the activity’s onCreate() having completed its work then onActivityCreated() can be used for that initialisation work

onStart() : The onStart() method is called once the fragment gets visible

onPause() : The system calls this method as the first indication that the user is leaving the fragment. This is usually where you should commit any changes that should be persisted beyond the current user session

onStop() : Fragment going to be stopped by calling onStop()

onDestroyView() : It’s called before onDestroy(). This is the counterpart to onCreateView() where we set up the UI. If there are things that are needed to be cleaned up specific to the UI, then that logic can be put up in onDestroyView()

onDestroy() : onDestroy() called to do final clean up of the fragment’s state but Not guaranteed to be called by the Android platform.

onDetach() : It’s called after onDestroy(), to notify that the fragment has been disassociated from its hosting activity

What is Android Fragments?

Android Fragment is a “reusable self contained portions of a user interface” in an Android Activity used for creating dynamic and flexible user interface. 

Fragments has it’s own life cycle but it always be embedded with an activity so that the fragments life cycle is directly affected by the host activity’s life cycle


How to change the application launcher icon on Flutter?

We can change the Launcher icon in the below ways


Right click on the android folder in the project outline. Go to New > Image Asset. (Try right clicking the android/app folder if you don't see Image Asset as an option.) Now you can select an image to create your launcher icon from

It will create the launcher icon with all DPIs

Flutter launcher Icon


Prepare all respected icon set Now  In your Flutter project go to ios/Runner/Assets.xcassets/AppIcon.appiconset

and update the icons and json file

Flutter Launcher Icon Ios


How to Sort ArrayList of Object Type in Java? 

Collections class has a method Sort which is used to sort arraylist.

sort(List<T> list)
sort(List<T> list, Comparator<? super T> c)


If List contains String,int... we can use first method.

If the List contains Object type we have to use second method to sort List.

The Second method has parameter of type Comparator which compare the object by

compare(Object  o1, Object o2) method



import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class JavaApplication1 {

    public static void main(String[] args) {
        ArrayList<Employee>listEmp=new ArrayList();
        Employee emp1=new Employee("Name 1", 20000, "Associate Developer");

        Employee emp2=new Employee("Name 2", 18000, "Junior Developer");

         Employee emp3=new Employee("Name 3", 48000, "Manager");

        Employee emp4=new Employee("Name 4", 30000, "TeamLead");
        System.out.println("Before Sorting....");
        for(int k=0;k<listEmp.size();k++)
        System.out.println("Emp "+listEmp.get(k).name+" : Salary = "+listEmp.get(k).salary);
        Collections.sort(listEmp, new Comparator<Employee>() {

            public int compare(Employee o1, Employee o2) {
                     if (o1.getSalary()==o2.getSalary()) {
                        return 0;
                     } else if (o1.getSalary()>o2.getSalary()) {
                        return 1;
                     } else {
                        return -1;
         System.out.println("After Sorting....");
        for(int k=0;k<listEmp.size();k++)
        System.out.println("Emp "+listEmp.get(k).name+" : Salary = "+listEmp.get(k).salary);

class Employee {
        String name;
        int salary;
        String designation;

        public Employee(String name, int salary, String designation) {
            this.name = name;
            this.salary = salary;
            this.designation = designation;

        public String getName() {
            return name;

        public void setName(String name) {
            this.name = name;

        public int getSalary() {
            return salary;

        public void setSalary(int salary) {
            this.salary = salary;

        public String getDesignation() {
            return designation;

        public void setDesignation(String designation) {
            this.designation = designation;



Before Sorting....
Emp Name 1 : Salary = 20000
Emp Name 2 : Salary = 18000
Emp Name 3 : Salary = 48000
Emp Name 4 : Salary = 30000

After Sorting....
Emp Name 2 : Salary = 18000
Emp Name 1 : Salary = 20000
Emp Name 4 : Salary = 30000
Emp Name 3 : Salary = 48000


How to convert ArrayList to Array in Java

Arraylist has a method toArray() to convert List to Array.


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class JavaApplication1 {

    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();

        String[] stringArray = list.toArray(new String[0]);
        for(int k=0;k<stringArray.length;k++)





How to create Arraylist from Array in Java

To create Arraylist from given array use below code

new ArrayList<>(Arrays.asList(array));



import java.util.ArrayList;
import java.util.Arrays;

public class JavaApplication1 {

    public static void main(String[] args) {
        String name[]=new String[]{
            "Name 1",
            "Name 2",
            "Name 3"
        ArrayList<String>arrayList=new ArrayList<>(Arrays.asList(name));
        for(int k=0;k         System.out.println(arrayList.get(k));


Name 1
Name 2
Name 3


How to Fetch System UUID with Java Program?

We can get the System UUID by below code

public class DeviceInfo {
    //Get Windows Machine UUID
    public static String getWindowsDeviceUUID()
             String command = "wmic csproduct get UUID";
                StringBuffer output = new StringBuffer();

                Process SerNumProcess = Runtime.getRuntime().exec(command);
                BufferedReader sNumReader = new BufferedReader(new InputStreamReader(SerNumProcess.getInputStream()));

                String line = "";
                while ((line = sNumReader.readLine()) != null) {
                    output.append(line + "\n");
                String uuid=output.toString().substring(output.indexOf("\n"), output.length()).trim();;
                return uuid;
        }catch(Exception ex)
            System.out.println("OutPut Error "+ex.getMessage());
        return null;
    //Get Mac Machine UUID
    public static String getMacUUID()
             String command = "system_profiler SPHardwareDataType | awk '/UUID/ { print $3; }'";

            StringBuffer output = new StringBuffer();

            Process SerNumProcess = Runtime.getRuntime().exec(command);

            BufferedReader sNumReader = new BufferedReader(new InputStreamReader(SerNumProcess.getInputStream()));

            String line = "";

            while ((line = sNumReader.readLine()) != null) {
                output.append(line + "\n");

            String uuid=output.toString().substring(output.indexOf("UUID: "), output.length()).replace("UUID: ", "");



            return uuid;
        }catch(Exception ex)
            return null;


How does Flutter load images?

Flutter can be load images with below widgets.

  • Image.network
  • FadeInImage.memoryNetwork
  • Image.asset

Also have few plugins to load images

cached_network_image 2.0.0

Flutter library to load and cache network images. Can also be used with placeholders and error widgets.

flutter_advanced_networkimage 0.6.4


Advanced image cache loading and zoom control.

transparent_image 1.0.0


Simple transparent image, represented as Uint8List. Can be used as a placeholder when loading an image

Android Activity FullScreen - How to set activity to fullscreen mode in Android?

To make Activity fullscreen need to add below code

public void onCreate(Bundle savedInstanceState) {




How to split a string in Java

We can split the string in jave with below ways

Split method

static private void bySplit(String s)
    String[]ss=s.split(" ");
    for(int k=0;k<ss.length;k++)


By StringTokenizer class

static private void byTokenizer(String s)
    StringTokenizer st=new StringTokenizer(s," ");


static private void byTokenizer(String s)
    StringTokenizer st=new StringTokenizer(s," ");

static private void bySplit(String s)
    String[]ss=s.split(" ");
    for(int k=0;k<ss.length;k++)

public static void main (String[] args)
    byTokenizer("Welcome to Java");
    bySplit("Welcome to Java");


How to place a listview inside a SingleChildScrollView but prevent them from scrolling separately?

We can handle Listview inside SingleChildScrollView  by

Option 1:

Set shrinkWrap: true for Listview. This fixes the error message.

Set physics: NeverScrollableScrollPhysics()


Option 2:

   primary: false,
   shrinkWrap: true,

What corresponds to Intent in Flutter?

In Android, Intent there are two main uses: for activity jumping between, and for communication between components. 
But in flutter there is  no Intent such concept, although you can still start via local integration native integrations(using plugins ) Intent.

Flutter As there is no activity, fragmentthe component corresponding to the direct, but rather Navigator, Route to switch between the screens with which activity .

Route is the abstraction of the application screen and page, but Navigator is a management Route control . It can be Route seen roughly activity, but they have different meanings. Switch the screen Navigator by push and pop(can be seen as pushing and popping) Route, and the Navigator working principle can be seen as a stack, which push means switching forward and pop returning.

In Android, you need Android Manifest.xmlto declare activity, and in Flutter , you have the following page switching options:

Specify a () containing all Route names Map MaterialApp
Switch directly to Route(WidgetApp)
The following example is the Mapw ay:

void main() {
    home: MyAppHome(), // becomes the route named '/'
    routes: <String, Widget Builder> {
      '/a': (BuildContext context) => MyPage(title: 'page A'),
      '/b': (BuildContext context) => MyPage(title: 'page B'),
      '/c': (BuildContext context) => MyPage(title: 'page C'),

The following is the way to go Routedirectly pushto Navigatorthe name :


Another use Intentcase is to call external components, such as cameras, file selectors. In this case, you need to create a native platform integration (native platform integration), or use an

Intent for Drive PDF Viewer - How to open PDF in Google Drive with intent

We can open PDF in google drive by below code

Uri pdfUri = Uri.parse("pass you file path");             
Intent shareIntent = ShareCompat.IntentBuilder.from(this)
                                     .setText("Share PDF doc")
                                         .setStream(pdfUri )


How to Get bitmap from drawable: Android

To get Bitmap from resource image

Bitmap bitmap = ((BitmapDrawable)getResources().getDrawable(R.drawable.test)).getBitmap();

It will return the Bitmap 


To get the Bitmap from Imageview

 Drawable imgDrawable = imageview.getDrawable();
 Bitmap bitmap = ((BitmapDrawable) imgDrawable).getBitmap();


Android FCM not receiving notifications when app is removed from background

There are some reasons for this issue and sometimes its depends on device

CM having two ways to send notifications

Data messages

      "Nick" : "Mario",
      "body" : "great match!",
      "Room" : "PortugalVSDenmark"

it will trigger the FirebaseMessagingService onMessageReceived method. 
it will not work on some devices, when an app is in the background.


Notification Messages

      "title":"Portugal vs. Denmark",
      "body":"great match!"


Notification messages are delivered to the system notification tray when the app is in the background. 
For apps in the foreground, messages are handled by a callback function

onMessageReceived method of your FirebaseMessagingService


To avoid the issue of not receving messages
add below code in manifest file

    android:stopWithTask="false" />


If we set to true, this service with be automatically stopped when the user remove a task rooted in an activity owned by the application. The default is false.

If the flag is false, there is an onTaskRemoved callback in your Service class.

In this case you can detect the onTaskRemoved on "swipe" event and you can again start the FirebaseMessagingService

How to find Android Device UDID or unique ID?

We can find it by 

String android_id =

How to install/ uninstall apk by command line ADB

We can install/uninstall apk from device by terminal/command prompt

Step 1:  Open Terminal/Command Prompt 

Step 2:  Set your adb path

in my computer it is like this


Step 3:  Now check check the device connected or not by

  adb devices

it will show the list of devices attached

Now Install apk by 

adb -s "put your device id" install "put your apk path"

Uninstall apk by 

adb -s "put your device id" uninstall "put your package name"

Hide/Disable soft keyboard on Activity launch: Android

By default, Android will automatically assign initial focus to the EditText or focusable control in started activity . It naturally follows that the InputMethod (typically the soft keyboard) will respond to the focus event by showing itself.

To hide Keyboard we can do any of below way

add in Activity oncreate method before setContentView() method



or add below code  Manifest file to which activity we need to hide keyboard



Error: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path

First Check your server response is valid JSON or Not if not make it proper

To check the resposne you can add loggingInterceptor for OkHttpClient  

OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(new LoggingInterceptor()).build();
                static class LoggingInterceptor implements Interceptor {
        public Response intercept(Interceptor.Chain chain) throws IOException {
            Request request = chain.request();

            long t1 = System.nanoTime();
            Log.v("Request ",String.format("Sending request %s on %s%n%s",
                    request.url(), chain.connection(), request.headers()));

            Response response = chain.proceed(request);

            long t2 = System.nanoTime();
            Log.v("Request ",String.format("Received response for %s in %.1fms%n%s",
                    response.request().url(), (t2 - t1) / 1e6d, response.headers()));

            final String responseString = new String(response.body().bytes());

            Log.v("Request ","Response: " + responseString);

            return  response.newBuilder()
                    .body(ResponseBody.create(response.body().contentType(), responseString))


If every thing fine add GsonConverter with below code

 GsonBuilder gsonBuilder=new GsonBuilder();


Finally Retrofit object creation should be like below



Duplicate files during packaging of APK” build.gradle issue: Android Studio

First Recheck your build.gradle if there any duplicate dependencies added

if yes, remove those  rebuild application

if not 
add below lines of code 

android {
    packagingOptions {
        exclude ‘META-INF/LICENSE.txt’
        exclude ‘META-INF/NOTICE.txt’


How to avoid multiple button click at same time in android?

Some times user may clicks multiple times on same widget, at that time App misleads and gives crassh/un expected behaviour to user.
We can resolve this by using the below code

The standard way to avoid multiple clicks is to save the last clicked time and avoid the other widget clicks within a preferred time


private long lastPressesTime;

public void onClick(View v) {
    // Preventing multiple clicks, using threshold of 1 second
    if (SystemClock.elapsedRealtime() - lastPressesTime < 1000) {
    lastPressesTime = SystemClock.elapsedRealtime();
        case R.id.widget1:
        case R.id.widget2:


How to Exit android app on back pressed?

Some times we don't want to open activities after pressing back button, examples Splash Screen Activity, Welcome Screen Activity, We don’t need these activities in activity stack.

we can remove it from activity stack by below ways

Manifest file



Some times we want to close entire application on back press
just place this code in onBackPressed method

public void onBackPressed(){
    Intent a = new Intent(Intent.ACTION_MAIN);


or we can do by

public void onBackPressed() {


How do I check in SQLite whether a table exists?

We can check the table exists or not by execute simple query

private boolean isTableExists(SQLiteDatabase db, String table){
   String sql = "SELECT name FROM sqlite_master WHERE type='table' AND name='"+tableName+"'";
   Cursor mCursor = db.rawQuery(sql, null);
   if (mCursor.getCount() > 0) {
      return true;
   return false;


Just pass your table name in the above and you will find table exists or not


How to copy database from assets folder in android using kotlin

We can copy database from assets folde by

class CopyAssetDatabaseOpenHelper(private val context: Context) {

companion object {

    private val DB_NAME = "dbName.db"

fun openDatabase(): SQLiteDatabase {
    val dbFile = context.getDatabasePath(DB_NAME)

    if (!dbFile.exists()) {
        try {
           val checkDB = context.openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE,null)

        } catch (e: IOException) {
            throw RuntimeException("Error creating source database", e)

    return SQLiteDatabase.openDatabase(dbFile.path, null, SQLiteDatabase.OPEN_READWRITE)

private fun copyDatabase(context:Context) {
            val dbFile = context.getDatabasePath("logicaldb")
            val assetdb = context.assets.open("logicaldb")
            val currentDB = FileOutputStream(dbFile)

            val buffer = ByteArray(1024)
            while (assetdb.read(buffer) > 0) {
                Log.d("#DB", "Copying "+buffer.toString())




Android Studio project R can't find

While creating some projects, we often encounter the problem that the R file cannot be found, which causes the code to glow everywhere and affect reading. So how to resolve this problem?

Project code clean
First clean the project, after cleaning the project  R may not be generated automatically. We need to manually build the project to see if R is normal

Check whether R is imported in import and whether R can be imported automatically
If you can import the corresponding R in this step,Thats it our issue solved.

If not look at the corresponding XML file for errors, and modify it as prompted

This situation is not a problem with R, but an XML file error. Generally, it is red when the id is referenced (you can ignore this if you confirm that the xml is correct)

Look for the R file in the generated file path, if it can be found, and check whether the file size is greater than 2500k
If the file is larger than 2500k, you can fix this problem by customizing the properties of the IDE.

In Android Studio, click Help-> Edit Custom Properties in turn, and enter the following configuration. The unit is kb. You can take a look at the size of the R file and set a suitable value.







FragmentPagerAdapter deprecated, Since API 27.1.0 FragmentPagerAdapter is deprecated. What's the best alternative to use for this?

We were created FragmentPagerAdapter class like below 

class MyViewPagerAdapter(manager: FragmentManager) : FragmentPagerAdapter(manager)


By replacing the above code with below code we can resolve the error

class MyViewPagerAdapter(manager: FragmentManager) : FragmentPagerAdapter(manager, FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT)


How to make shadow for Container widget Flutter?


By Using boxShadow property of BoxDecoration widget we can make shadow for the Container.
  margin: EdgeInsets.all(16),
  decoration: BoxDecoration(
    color: Colors.white,
    borderRadius: BorderRadius.circular(8),
    boxShadow: [
        blurRadius: 6,
        spreadRadius: 4,
        color: Color.fromARGB(20, 0, 0, 0),
Image.asset("assets/imagename", height: 200,
  fit: BoxFit.fitWidth,)

What is the output of print str[3:8] if str = 'Python Programming'?


It will print characters starting from 3rd to 8th.

Output would be "hon P".

var = "Python Programming"

What is the output of print var?

It will print complete string.

Output would be Python Programming.

What are the supported data types in Python?

Python  data types are − Numbers, String, List, Tuple, Dictionary

What is PYTHONHOME environment variable?

PYTHONHOME - It is an alternative module search path. It is usually embedded in the PYTHONSTARTUP or PYTHONPATH directories to make switching module libraries easy.

Python a case sensitive language?

Yes, Python is a case sensitive programming language.

What is PYTHONSTARTUP environment variable?

PYTHONSTARTUP - It contains the path of an initialization file containing Python source code. It is executed every time you start the interpreter. It is named as .pythonrc.py in Unix and it contains commands that load utilities or modify PYTHONPATH.

What is PYTHONPATH environment variable?

PYTHONPATH - It has a role similar to PATH. This variable tells the Python interpreter where to locate the module files imported into a program. It should include the Python source library directory and the directories containing Python source code. PYTHONPATH is sometimes preset by the Python installer.

List the features of Python?

Following are some of the salient features of python 

  • It supports functional and structured programming methods as well as OOP.
  • It can be used as a scripting language or can be compiled to byte-code for building large applications.
  • It provides very high-level dynamic data types and supports dynamic type checking.
  • It supports automatic garbage collection.
  • It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

What is Python?

Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages.

How to get an image resource by it's name in android?

With Resources.getIdentifier() method we can get the resource id by its name.

If we know drawable name then we can get drawable id by 

int resId = getResources().getIdentifier("Name of Resource", "drawable", mApplicationContext.getPackageName());


If we know color name then we can get color id by 

int resId = getResources().getIdentifier("Name of Resource", "color", mApplicationContext.getPackageName());


Flutter - Vertical Divider - How to add Vertical Divider?

By using VerticalDivider widget we can add vertical divider in between widgets.

Sample code

  child: Row(
    mainAxisAlignment: MainAxisAlignment.spaceEvenly,



Color, endIndent, indent, thickness, width 

How to Generate signed apk with android studio

  1. Go to Build->Generate Signed APK->Next (module should be your current module)
  2. Click on create new
  3. Fill the form with the required details. Click on icon that will open up a navigator window which will ask you to select a .jks file. Navigate to a folder where you want your keystore file saved and then at the File Name box at the bottom of that window, simply enter a name and the press OK button. .
  4. Click on Next and then select Release, now you are done.

How to reduce APK package size?

The code
maintains good programming habits. Do not repeat or unused code. Add libs carefully and remove unused libs.
Use proguard to obfuscate the code, it will optimize the unused code, and can reduce the size of the installation package after obfuscation.
The part of native code, in most cases, only needs to support armabi and x86 architecture. If not necessary, consider removing the x86 part.

Use the Lint tool to find unused resources. Remove unused images, strings, XML, etc. Make sure there are no unused files for assets in the assets directory.
When generating the APK, the aapt tool itself will optimize the png, but before that, you can use other tools such as tinypng to further compress and preprocess the image.
jpeg is still png. Choose according to your needs. In some cases, jpeg can reduce the size of the picture. For 9.png images, the stretchable area should be cut as small as possible. In addition, you can avoid using the entire large image when using 9.png stretching to achieve the effect of large images.

The strategy
provides the image resources of hdpi, xhdpi, xxhdpi selectively. It is recommended to provide xhdpi pictures first. For mdpi, ldpi and xxxhdpi can provide different parts as needed.
Reuse existing image resources as much as possible. For example, you only need to provide a symmetrical picture, and another picture can be implemented by code rotation.
Functions that can be implemented in code, try not to use a lot of pictures. For example, to reduce the use of multiple pictures to make an animation-list AnimationDrawable, this approach provides multiple pictures that take up a lot of space

App Bundle

With the Android studio we have option to generate app bundle to publish the app.

Based on device configuration app bundle will install only that specific device related resources.

What are symmetric and asymmetric encryption in the way Android interacts with the server?

Symmetric encryption means that the same key is used to encrypt and decrypt data. The algorithm in this regard is DES.
Asymmetric encryption, encryption and decryption use different keys. Before sending data, you must agree with the server to generate a public key and a private key. The data encrypted with the public key can be decrypted with the private key, and vice versa. An algorithm for this is RSA. Both ssh and ssl are typical asymmetric encryption.

What happens next when the device switches between portrait and landscape?

  1. When the android: configChanges of the Activity is not set, the cut screen will re-call each life cycle, it will be executed once when the horizontal screen is cut, and it will be executed twice when the vertical screen is cut
  2. When the android: configChanges = "orientation" of the Activity is set, The screen cut will still call each life cycle again. It will only be executed once when the screen is cut horizontally or vertically.
  3. When setting the android: configChanges = "orientation | keyboardHidden" of the Activity, the screen cut will not re-call each life cycle, only onConfigurationChanged will be executed method

What is ANR? How to avoid and resolve it?

Application Not Responding, that is, the application has no response.
There are generally three types of ANR:
1: KeyDispatchTimeout (5 seconds) the main type of
key or touch event is not responding within a specific time

2: Broadcast Timeout (10 seconds)
BroadcastReceiver cannot be processed within a certain time

3: Service Timeout (20 seconds) - small probability
service cannot be completed within a certain time

There are generally two reasons for timeout:
(1) the current event has no chance to be processed (the UI thread is processing the previous event did not complete in time or the looper is blocked for some reason)
(2) the current event is being processed, but not in time carry out

The UI thread tries to do only UI-related work and time-consuming work (database operations, I/O, network connection, or other operations that may hinder the UI thread). Put it in a separate thread. Use Handler to handle UI thread and thread Interaction.

UI threads mainly include the following:
Activity: onCreate (), onResume (), onDestroy (), onKeyDown (), onClick ()
AsyncTask: onPreExecute (), onProgressUpdate (), onPostExecute (), onCancel ()
Mainthread handler: handleMessage () , post (runnable r)

Application Not Responding, that is, the application has no response.
There are generally three types of ANR:
1: KeyDispatchTimeout (5 seconds)-the main type of
key or touch event is not responding within a specific time

2: BroadcastTimeout (10 seconds)
BroadcastReceiver cannot be processed within a certain time

3: ServiceTimeout (20 seconds)-small probability
service cannot be completed within a certain time

There are generally two reasons for timeout:
(1) the current event has no chance to be processed (the UI thread is processing the previous event did not complete in time or the looper is blocked for some reason)
(2) the current event is being processed, but not in time carry out

The UI thread tries to do only UI-related work and time-consuming work (database operations, I/O, network connection, or other operations that may hinder the UI thread). Put it in a separate thread. Use Handler to handle UI thread and thread Interaction.

UI threads mainly include the following:
Activity: onCreate (), onResume (), onDestroy (), onKeyDown (), onClick ()
AsyncTask: onPreExecute (), onProgressUpdate (), onPostExecute (), onCancel ()
Main thread handler: handleMessage () , post (runnable r)

How to copy text from Text Widget flutter?


We don't have any property to copy text from Text widget in flutter.

in Flutter 1.9 introduced SelectableText widget.

  child: SelectableText("Copy Text value",style: TextStyle(),),

Whenlong click on this text now it will show the Clipboard copy option to copy the valu from widget.

Properties of SelectableText Widget

focusNode,style,strutStyle,textAlign,textDirection,showCursor = false,autofocus = false,
ToolbarOptions toolbarOptions,maxLines,cursorWidth = 2.0,cursorRadius,cursorColor,
dragStartBehavior = DragStartBehavior.start,enableInteractiveSelection = true,

With this widget we cn hanlde direct Click events for the Text widget.

Java Thread -  How to create Threads in Java?

There are two ways to create thread in Java

Inherited from the Thread class
Implementing the Runnable interface

Extends Thread

class MyThread extends Thread {  
    public void run() {  
        System.out.println("thread is running...");  

Implements Runnable

class MyThread implements Runnable {  
    public void run() {  
       System.out.println("thread is running...");  


How do I generate random numbers in Dart?

By Using Random class from math library we can generate rrandom number in flutter


import 'dart:math';

main() {
  var rng = new Random();
  for (var i = 0; i < 10; i++) {


To generate a list with random numbers 

import 'dart:math';

main() {
  var rng = new Random();
  var l = new List.generate(10, (_) => rng.nextInt(100));

This will generate list with 10 random numbers between 0-99 

How to handle the code after showDialog is dismissed in Flutter?

By using the then function we can handle the code after dialog dismiss

if( isShow==fasle){
  context: context,
  builder: (BuildContext context) {
    // return object of type Dialog
    return AlertDialog(
      title: new Text("Alert Dialog title"),
      content: new Text("Alert Dialog body"),
      actions: <Widget>[
        // usually buttons at the bottom of the dialog
        new FlatButton(
          child: new Text("Close"),
          onPressed: () {
            isShow = false;


In the above code when "isShow" value is false then i am going to show the Dialog and while showing the dialog set  variable "isShow" to true

After dismiss the dialog again set the value to fasle, so that ican show the dialog alternatively, but when i press the back button this will not set the "isShow" to fasle, for the next iteration it will not show the Dialog.

To handle this scenario i have added then() function for the showDialog.

Let's updated code is 

if( isShow==fasle){
  context: context,
  builder: (BuildContext context) {
    // return object of type Dialog
    return AlertDialog(
      title: new Text("Alert Dialog title"),
      content: new Text("Alert Dialog body"),
      actions: <Widget>[
        // usually buttons at the bottom of the dialog
        new FlatButton(
          child: new Text("Close"),
          onPressed: () {
            isShow = false;


  isShow = false;



By this way we can hanlde back button event also.

Could not inflate Behavior subclass android.support.design.widget.
BottomSheetBehavior How resolve this exception?

If you are using the Androidx Jetpack dependencies then






How To Set TextView Text Color Programmatically?

With setTextColor() method we can set the color for Textview.
For this method we need to pass color vallu




ContextCompat.getColor(context, R.color.your_color);)

Is There A Way To Get The Source Code From An APK File? (or) How to decompile apk?

For APK reverse engineering we have lots of ways.

Option 1: From Android Studio

Use the “Profile or Debug APK” feature in Android Studio

This will open and explore the APK - in Android Studio. Classes are de-compiled into small Resources are not retrieved and things like “Go to definition”, “Find all links” and debugging does not work without source code 

Option 2: 

  • Download apktool.bat(or apktoolfor Linux) and apktool_.jar from http://ibotpeaches.github.io/Apktool/install/
  • Rename the file to the jar from above apktool.jar and place both files in the same folder,
  • Open a Command line window  and change to this folder; make sure the Java environment is installed 
  • Run apktool decode [apk file]
    • This will generates : resource files,AndroidManifest.xml


  • Unzip the APK file with the unpacker of your choice
    • This will generate :classes.dex


  • Download and extract dex2jar- from http://code.google.com/p/dex2jar/downloads/detail?name=dex2jar-
  • Drag classes.dex to dex2jar.bat(or enter \dex2jar.bat classes.dex in the DOS field, Linux to use dex2jar.sh)
    •  This will generate :classes_dex2jar.jar


  • Unpack classes_dex2jar.jar(may be optional depending on the decompiler used)
  • Decompile class files (e.g. with JD-GUI or DJ Decompiler )
    •  This will generate : source code

Option 3:

Use below Online tool to decompile APK


What is "shared preferences" in Android ?

Shared Preferences is one of data storage mechanism in Android.

It is a xml file store the data in key-value pair.

It will store the small amount of data.

It can be store only primitive data.

Common use case of Shared Preference 

1. Check the User Login session inside the application

2. Show the demo/intro/welcome Screens one time per application

3. Small amount of data passed to across activities which is hard with Intents


How do I open a web browser (URL) from my Flutter code?


Flutter have a plugin for launching a URL in the mobile platform url_launcher

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

void main() {
  backgroundColor: Colors.grey,
  appBar: AppBar(
    backgroundColor: Colors.deepPurple,
    title: Text("Webview Examples"),
  body: Container(
    margin: EdgeInsets.all(20),
    child: RaisedButton(
      padding: EdgeInsets.all(12),
      child: Text("Browser",style: TextStyle(
          color: Colors.white,fontSize: 18
      color: Colors.red,
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(15)
      onPressed: () {

_launchURL() async {
  const url = 'https://flutter.io';
  if (await canLaunch(url)) {
    await launch(url);
  } else {
    throw 'Could not launch $url';


What is Intent? What is the difference between an implicit intent and an explicit intent?

Intent is a messaging object that can be use to pass data between different components(activities/service/BroadcarReceivers...).
 in other words
 Intents are asynchronous messages which allows Android components to request functionality from other components. For example an Activity can send an Intents to the Android system to starts another Activity
 In Android we have two types of Intents.
 Implicit Intent
 Intent which will be used to call system apps like Gmail,Gallery,SMS...

Lets check below code 

Intent sendIntent = new Intent();
sendIntent.putExtra(Intent.EXTRA_TEXT, textMessage);

Explicit Intent
 Intent which will be used to call our application components(Activities/Services...)

Intent intent = new Intent(first.this, second.class);


How to change package name in flutter?

For Android

To change the package name we just need to update appliationid in build build.gradle only

defaultConfig {
    applicationId "your.package.name"
    minSdkVersion 16
    targetSdkVersion 27
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

For iOS

Change the bundle identifier from your Info.plist file inside your ios/Runner directory



How to get screen size (width,height) in Android?

With the Display object we can get the Screen width and height

Display display = getWindowManager().getDefaultDisplay(); 
int width = display.getWidth();
int height = display.getHeight();


But getWidth(),getHeight() are deprecated from Android API Level 13 and introduced getSize() method

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
int width = size.x;
int height = size.y;


How to convert DP to Pixel and Pixel to Dp?

To Convert dp to px or px to dp fisrt we need to calculate device Density DPI
we will get density DPI fromDisplaymetrics object.

Lets create DisplayMetrics object

DisplayMetrics displayMetrics= getResources().getDisplayMetrics();

Now calculate devie Density DPI 

float densityDpi=displayMetrics.densityDpi;
float defaultDPI=DisplayMetrics.DENSITY_DEFAULT;

Convert dp to px


Convert px to dp



How to stop EditText  focus at Activity startup in Android?

We can achive this by below ways

add android:windowSoftInputMode="stateAlwaysHidden"
in manifest file on specifica Activity.


Add below code to its parent widget

How to save activity State in Android?

Before Architecture Components we were used to save the UI state by onSaveInstanceState() method


We need to override onSaveInstanceState(Bundle savedInstanceState) and store the application state values in the form of bundle

public void onSaveInstanceState(Bundle savedInstanceState) {

  savedInstanceState.putBoolean("mybool", true);
  savedInstanceState.putInt("myint", 1);
  savedInstanceState.putString("mystring", "Back to Activity State");


Saved instanceState could save only parceble data.
This have limit to staore small amount of parceble data


ViewModel instance is part of Applications process  and hence it is able to handle configuration changes.
If process dies, ViewModel instance lost and all the saved state will also be lost. 

It will work for large objects also.
Don't have any restritions to save the state.
You can read about Viewmodel here

What is the difference between match_parent and fill_parent?

Both properties are same there is no functional difference,

Google just changed the name from fill_parent to match_parent, from API level 8 (Android 2.2). 
For compatibility reason FILL_PARENT is still available

How do I supply/set an initial value to a text field in Flutter ?

By Using TextEditingController we can set initial value to Text filed.

class LandingPage extends StatefulWidget{
  State createState() =>LandingPageState();


class LandingPageState  extends State {
  TextEditingController _controller;

  void initState() {
    _controller = new TextEditingController
(text: 'Enter Values');

  Widget build(BuildContext context) {
    return new Column(
      children: [
        new TextField(
          controller: _controller,


By Using  TextFormField

class LandingPageState extends State {
  TextEditingController _controller;

  @override void initState() {
    _controller = new TextEditingController (text: 'Enter Values');

  @override Widget build(BuildContext context) {
    return new Column(children: [ 
      autofocus: false,
      initialValue: 'your initial text',
      decoration: InputDecoration(
        hintText: 'Last Name',


How to handle Scaffold.of() called with a context that does not contain a Scaffold exception?

This Exception was cause by using the context of Scaffold widget instead of Child widget in the widget Tree.

We handle this exception by two ways

Option1) Using Builder widget

    appBar: AppBar(
        title: Text('Builder Widget'),
    body: Builder(
        builder: (context) => 
            child: RaisedButton(
            color: Colors.pink,
            textColor: Colors.white,
            onPressed: () {
 final snackBar = SnackBar(content: Text('Flutter SnackBar'));

            child: Text('Display SnackBar'),


Option1) By Using Scaffold key

  key: _scaffoldKey,
  appBar: AppBar(
    title: Text('Builder Widget'),
  body:  Center(
    child: RaisedButton(
      color: Colors.pink,
      textColor: Colors.white,
      onPressed: () {
        final snackBar = SnackBar(content: Text('Flutter SnackBar'));
      child: Text('Display SnackBar'),


How can i use hexadecimal color code in Flutter?

In Flutter the  Color  class only accepts integers as parameters
Other wise we need to use names constructors fromARGB/fromRGBO
If we have the Hexa color code then we need to convert this hexa color code into int type color code.
Option 1:
This we can achive by replace "#" with 0XFF in Hexa string and create const color variable by

const color = const Color(0xff0276e8);

Then we can use this value to any where.
Option 2:
Create a class which extends color class

class ColorUtil extends Color {
  static int _getColorFromHex(String hexColor) {
    hexColor = hexColor.toUpperCase().replaceAll("#", "");
    if (hexColor.length == 6) {
      hexColor = "FF" + hexColor;
    return int.parse(hexColor, radix: 16);

  ColorUtil(final String hexColor) : super(_getColorFromHex(hexColor));

and use this in any wdiget by

Color color=ColorUtil("#0276e8")
Color color=ColorUtil("0276e8")


How to create Toast in Flutter?

1) To show the Toast messages in Flutter we can use  Snackbar widget.

To show snackbar we need to use scaffoldWidget.

      SnackBar(content: Text('This is Snackbar toast'))



2) By Using Flutter fluttertoast 3.1.3 plugin aslo we canshow the Toast Messages.

        msg: "This is Plugin Toast Message",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0


How to remove debug banner in flutter?

On MaterialApp widget set debugShowCheckedModeBanner to false

 debugShowCheckedModeBanner: false


What is Context?

Context is an abstract class, whose implementation is provided by Android System.

It provide acces to application related resources,databses,shared preferences...

We have different ways to access the context.

  • getContext()
  • getBaseContext()
  • getApplicationContext()
  • getActionBar().getThemedContext()


When to use getContext()?

Any instance which is not running long time, there we can use getContext().

We can use it in long running instances but we need to hanlde it by theire lifecycle methods to avoid memory leaks.


When to use getBaseContext()?

Inside activity life cycle we can use the getBaseContext(), this will be lives until the activity lifecycle alive.


When to use getApplicationContext()?

getApplicationContext() returns the application context of entire application. It will live untile the application life cycle, once application terminated it will destory


When to use getThemedContext()?

This context will be used to hanlde the views theme context inside the actionbar.


Note: we have to use proper context on the lifecycle of each instance to avoid the memory leaks in the application.


What is Application?

Application is base class in Android, which contains all components like activites,services...

The Application class is first instanitated while running any application.

We can write Custom Application class by extending the Application class.


class MyApplication extends Application{

    public void onCreate() {



We can declare any single instance classes here and use entire application.

To execute this class we need to set Application name in  manifest file.


What is NetworkOnMainThread Exception?

This exception is occurs when we call the network calls in Main Thread.
Long Running process never run on Main Thread.
To solve this problem, having following ways

1) Strict mode:

write this code in your onCreate method

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll()



2) AsynkTask
write your code inside doInBackground() method


 private class DownloadFilesTask extends AsyncTask<Void, Void, Void> {
     protected Long doInBackground(URL... urls) {
// write your code here
         return ;
3) Using Thread 
 Thread thread = new Thread(new Runnable(){
    public void run() {
        try {
            //Your code goes here
        } catch (Exception e) {


Check List for Generate Signed APK Android

Manifest file

  • Provide the Package name
  • Provide the app version name (should be higher value if the app already submitted in playstore). For updated apps, version name depends on the features. If the updated version is major release, increase the digit value. If the updated version is minor release, just increase the decimal value. 
    • Ex: 1.0,1.1 etc,
  • Provide the app version code (should be higher value if the app already submitted in playstore)
    • Ex: 1,2,3… (Integer values)
  • If your app wants run on future sdk versions don’t mention max-sdk.
  • Minimum SDk version (which is, app will support the from this lower sdk version)
  • If App working with network call, give the Internet permission.
  • <uses-feature />, if the app required the hardware components mandatory, you should mention that in <user-feature/> tag with attribute  required=true
  • Add require permissions in side <uses-permission> tag.
  • App should be in release mode,(android:debuggable="false")
  • Declare all your activities,services and receivers with required attributes.
  1. Remove logs or comment all(not mandatory,but it is good to remove)

  2. Pointing all service calls to production server.

  3. Generate signed apk.
    a) For generating signed apk we need keystore file, create a keystore file.
    b) Generate Signed apk with keystore file (should be same keystore file for future

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

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="package name"



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

    <uses-sdk   android:minSdkVersion="minimum version "/>

<uses-feature android:glEsVersion="0x00010001"

         android:required="true" />

   <application android:name="App name"


    android:icon="app_icon"  android:label="app_name" 



    <activity android:name="Packagename.Activity Name"



            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />



     <activity android:name="Packagename.Next Activity" />


If we use the Gradle Build Tool 

All we need to maintain the version details, dependencies in the App Level gradle file



Key Points to remember while develop the Android Application.


  1. Proper Usage of Intents.

    1.  Intent intent=new Intent(Intent.ACTION_SEND);

  2. Use Fragments when it requires.

    1.  Fragments are not having UI and not requires any permission to access.

    2.  It will give best UI development for phones and Tablets.

  3. Avoid ANR(Application Not Responding) calls

    1.  ANR will come when long running process is running on Main thread.

    2.  Run those in Background thread or any other.

  4. Use Proper libraries and when it needed, and build gradle file proper

  5. Not understanding Bitmaps/Avoiding the usage of Bitmaps

  6. Not Setting minSdkversion, compileSdkversion and targetSdkVersion in build.gradle file

  7. Not optimizing bandwidth usage/ poor Memory Management

  8. Not developing your apps with different sizes / Your apps is not compatible with all devices (screens) / UI (User Interface) is not compatible with all sizes of devices

  9. Not having an idea about the user interaction with app/ not thinking whether the app is user-friendly or not (Because everyone may not use your app the same way you would use it)


  • When we are writing code for any app, it should be easy to understand and readable to any other developer because we have to work with a team. We should specify the code with comments explaining your coding lines. We should keep in mind some points as below:

    • We should follow the naming conventions provided by Java coding standards because Java would be your basic language for Android apps development

    • Use full English descriptors that accurately describe the variable, field, class or interface.

    • Each and every function should be commented properly

    • Each block of code must be surrounded by try-catch block so that the application does not crash

    • There has to be separate packages for Activities, Constant Data and Class Data Objects for the application.

    • Progress dialog should be used wherever there is some heavy processing or network operation running

    • Use custom styles and themes to make the UI consistent throughout the application if the UI is customized as per the client requirements

What is the Different Between val and var in Kotlin?

if we define a variable with  val  its value never changed. where as if we defin the varibale with  var its value will be change.

Like Stirng in java  val   in kotlin is immutable. 


How to check Android version?

Open your phone settings.


Scroll to bottom of the page and tap on About Phone

See Image 2

There You will find the Android version Label. Based on version it may vari the Location.

See Image 3

In Oreo version it will be under System Update

What are Android Versions available?

The First Android version 1.0 was launched with T-Mobile G1 aka HTC Dream.

Every Android version was named in Alphabatical order. Current Latest version is 10 with the Name of Android-Q (API level is 29).

Name API Level  Release
Android 1.5, Cupcake 3 April 27, 2009
Android 1.6, Donut 4 September 15, 2009
Android 2.0-2.1, Eclair 5-7 October 26, 2009
Android 2.2-2.2.3, Froyo 8 May 20, 2010
Android 2.3-2.3.7, Gingerbread 9-10 December 6, 2010
Android 3.0-3.2.6, Honeycomb 11-13 February 22, 2011
Android 4.0-4.0.4, Ice Cream Sandwich 14-15 October 18, 2011
Android 4.1-4.3.1, Jelly Bean 16-18 July 9, 2012
Android 4.4-4.4.4, KitKat 19-20 October 31, 2013
Android 5.0-5.1.1, Lollipop 21-22 November 12, 2014
Android 6.0-6.0.1, Marshmallow 23 October 5, 2015
Android 7.0-7.1.2, Nougat 24-25 August 22, 2016
Android 8.0-8.1, Oreo 26-27 August 21, 2017
Android 9.0, Pie 28 August 6, 2018
Android 10.0, Android-Q 29 September 3, 2019


What is Android?

Android is an Mobile Operating System, which is a stack of Software for mobile devices. The Application executes within its own process.

It is developed by Google and later OHA(Open Handset Alliance).

Android code can be written by Using JAVA/Kotlin programing lanaguages.


How to set the TextFormField/TextField border color

by add the enableBorder property to the widget, we can set the color of the border.

enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: BorderSide(
              color: Colors.pink

How to navigate to  new screen without back screen

By using Navigator.pushReplacement(), we can achive this
For Navigator.push() use navigator.pushReplacement();
For Navigator.pushNamed() use navigator.pushReplacementNamed();

How to make a widget Center vertically inside a SingleChildScrollView

Make your main widget as Center widget.
body: Center(child: SingleChildScrollView(
      child:  Column(
                  mainAxisSize: MainAxisSize.max,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [

How to find the Screen orientation in flutter

orientation orientation=MediaQuery.of(context).orientation;

Can  we use Container color and decoration properties at once?

No if use both properties throws error "Cannot provide both a color and a decoration"

How to remove Yellow lines under Text Widgets in Flutter?

We can remove yellow lines by adding the Parent widget as "Material" or use "Scaffold"

return MaterialApp(
      home: Scaffold(
        body: Container(
          child: SingleChildScrollView(child: Text('Test')),

What is Flutter?

Flutter is a open-source cross-platform mobile app development framework which is by Google. Initially released on May 2017; and Flutter got its first stable 1.0 release on December 4th, 2018.