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:

ListView(
   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() {
  runApp(MaterialApp(
    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 :

Navigator.of(context).pushNamed('/b');


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")
                                         .setType("application/pdf")
                                         .setStream(pdfUri )
                                         .getIntent()
                                 .setPackage("com.google.android.apps.docs");
startActivity(shareIntent);

 

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

{
  "message":{
    "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "data":{
      "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

{
  "message":{
    "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "notification":{
      "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

<service
    android:name="com.yourapp.SERVICE"
    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 =
                Settings.Secure.getString(getContentResolver(),
                        Settings.Secure.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

C:\Users\User\AppData\Local\Android\Sdk\platform-tools>

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

getWindow().setSoftInputMode(
    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
);

 

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

<activity
    android:name=".MyActivity"
    android:windowSoftInputMode="stateAlwaysHidden"/>

 

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 {
        @Override
        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))
                    .build();
        }}

 

If every thing fine add GsonConverter with below code

 GsonBuilder gsonBuilder=new GsonBuilder();
        gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
        gsonBuilder.setLenient();
        

 

Finally Retrofit object creation should be like below

Retrofit.Builder()
        .addConverterFactory(GsonConverterFactory.create(gsonBuilder.create()))
      .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
        .baseUrl(ApiCall.BASE_IRL)
        .client(client)
        .build();

 

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;

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

 

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
android:noHistory="true"

<activity
    android:name="com.example.activity"
    android:label="" 
    android:noHistory="true">
</activity>

 

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

@override
public void onBackPressed(){
    Intent a = new Intent(Intent.ACTION_MAIN);
    a.addCategory(Intent.CATEGORY_HOME);
    a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(a);
}

 

or we can do by

public void onBackPressed() {
  finish();
}

 

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;
   }
   mCursor.close();
   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)

            checkDB?.close()
            copyDatabase(dbFile)
        } 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) {
                currentDB.write(buffer)
                Log.d("#DB", "Copying "+buffer.toString())
            }

            currentDB.flush()
            currentDB.close()
            assetdb.close()

        }
    }

 

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.

idea.max.intellisense.filesize=6000

 

references

https://developer.android.com/studio/intro/studio-config

https://www.jetbrains.com/help/idea/2016.2/file-idea-properties.html

 

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.
Container(
  margin: EdgeInsets.all(16),
  decoration: BoxDecoration(
    color: Colors.white,
    borderRadius: BorderRadius.circular(8),
    boxShadow: [
      BoxShadow(
        blurRadius: 6,
        spreadRadius: 4,
        color: Color.fromARGB(20, 0, 0, 0),
      ),
    ],
  ),
  child: 
Image.asset("assets/imagename", height: 200,
  fit: BoxFit.fitWidth,)
);

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

IntrinsicHeight(
  child: Row(
    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
    children:[
    Text('One'),
    VerticalDivider(),
    Text('Two'),
    VerticalDivider(),
    Text('Three'),],
  ),
)
 

 

Properties:

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.

Resources
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)
other

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)
other

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.

Container(
  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,
onTap,scrollPhysics,textWidthBasis

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

example:

import 'dart:math';

main() {
  var rng = new Random();
  for (var i = 0; i < 10; i++) {
    print(rng.nextInt(100));
  }
}

 

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

 isShow=false;
if( isShow==fasle){
showDialog(
  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;
            Navigator.of(context).pop();
          },
        ),
      ],
    );
  },
)
}

 

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 

isShow=false;
if( isShow==fasle){
showDialog(
  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;
            Navigator.of(context).pop();
          },
        ),
      ],
    );
  },
)

.then((value){

  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

replace 

app:layout_behavior="android.support.design.widget.BottomSheetBehavior"

with 

app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior"


 

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

textView.setTextColor(Color.parseColor("#ffffff"));

textView.setTextColor(Color.rgb(200,0,0));

textView.setTextColot(

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-0.0.9.15.zip from http://code.google.com/p/dex2jar/downloads/detail?name=dex2jar-0.0.9.15.zip&can=2&q=
  • 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

http://www.javadecompilers.com/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() {
  runApp(
Scaffold(
  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("http://rrtutors.com/");
      },
    ),
  ),
)
);
}

_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.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, textMessage);
sendIntent.setType("text/plain")
startactivity(sendIntent);

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

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

 

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

<key>CFBundleIdentifier</key>
<string>com.your.packagename</string>

 

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();
display.getSize(size);
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

dp*(densityDpi/defaultDPI);

Convert px to dp

px*(densityDpi/defaultDPI);

 

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
android:focusableInTouchMode="true"
android:focusable="true"

How to save activity State in Android?

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

SaveInstanceState:

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

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  super.onSaveInstanceState(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

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{
  @override
  State createState() =>LandingPageState();

}

class LandingPageState  extends State {
  TextEditingController _controller;

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

  @override
  Widget build(BuildContext context) {
    return new Column(
      children: [
        new TextField(
          controller: _controller,
        ),
      ],
    );
  }
}

 (OR)

By Using  TextFormField

class LandingPageState extends State {
  TextEditingController _controller;

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

  @override Widget build(BuildContext context) {
    return new Column(children: [ 
TextFormField(
      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

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

},
            child: Text('Display SnackBar'),
            ),
        ),
    ),
);

 

Option1) By Using Scaffold key

GlobalKey<ScaffoldState>_scaffoldKey=GlobalKey();
Scaffold(
  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'));
       
        _scaffoldKey.currentState.showSnackBar(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.

Scaffold.of(context).showSnackBar(
      SnackBar(content: Text('This is Snackbar toast'))
);

 

 

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

Fluttertoast.showToast(
        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

MaterialApp(
 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{

@Override
    public void onCreate() {
        super.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()
.build();

StrictMode.setThreadPolicy(policy);

 

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(){
    @Override
    public void run() {
        try {
            //Your code goes here
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});

thread.start(); 

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
    releases)

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

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

package="package name"

android:versionCode="1"

android:versionName="1.0">

    <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:debuggable="false"

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

    android:theme="@style/AppTheme">

 

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

     >

        <intent-filter>

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

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

        </intent-filter>

    </activity>

     <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

build.gradle

  

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.

Related Posts View All