Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts

Thursday, February 16, 2023

dlopen failed: cannot locate symbol "__emutls_get_address" referenced by "/lib/arm64/libfolly_runtime.so"

dlopen failed: cannot locate symbol "__emutls_get_address" referenced by "/data/app/xadfadsfas==/xxxxxxx==/lib/arm64/libfolly_runtime.so"


https://github.com/facebook/react-native/blob/main/ReactAndroid/src/main/jni/third-party/folly/CMakeLists.txt

target_compile_options(folly_runtime PUBLIC ${folly_FLAGS})

target_include_directories(folly_runtime PUBLIC .)

Where, In the app. we need to check runtime libraries, 

Which will be residing under jniLibs folder.

If your application includes multiple shared libraries, you should use libc++_shared.so.

On Android, the libc++ used by the NDK is not the same as the one that's part of the OS. This gives NDK users access to the latest libc++ features and bug fixes even when targeting old versions of Android. The trade-off is that if you use libc++_shared.so, you must include it in your app. If you're building your application with Gradle this is handled automatically.

Old versions of Android had bugs in PackageManager and the dynamic linker that caused installation, update, and loading of native libraries to be unreliable. In particular, if your app targets a version of Android earlier than Android 4.3 (Android API level 18), and you use libc++_shared.so, you must load the shared library before any other library that depends on it.

libc++ is not a system library. If you use libc++_shared.so, it must be included in your app. If you're building your application with Gradle this is handled automatically.

run the command nm -gD libc++_shared.so

Where __emutls_get_address method is missing in the libc++_shared.so, Update the latest libc++_shared.so, the problem will be solved

Monday, October 19, 2015

Google Maps No Longer Requires STORAGE Permission!

For a long time, Google Maps Android SDK requires us to have WRITE_EXTERNAL_STORAGE permission. It was not the case when they first released the SDK.

I didn’t want to have that storage permission first, because In app permission “The permission description says that the application can access files on the devices such as images, videos or audio”
I had lots of 1, 2, 3 stars in app ratings because of this. Users say that “Why do you request access for my photos and videos?”. They are right! They are always right. I don’t want to access your photos and I won’t. I am forced to have that permission.
Android Marshmallow brought us run-time permissions. They are great! Users do not see permissions when they install or update the app. Users have more control over the app’s functionality.
for example, a user could choose to give a camera app access to the camera but not to the device location.
But imagine you have an app with Google Maps integration, and imagine you have to request WRITE_EXTERNAL_STORAGE on runtime to show the map. How would you explain that to users? Runtime permissions that are not obvious and require explanation are the worse. This is one of them.
Fortunately, they fixed the issue and removed storage permission. But not for all, just for Android Marshmallow.
If you use Google Maps and you want to target Android Marshmallow, this is what you need to do:
  • First you need to use Google Play Services 8.1.0
  • Second, you need to add maxSdkVersion property in your permissions as shown below:



They also say in the documentation that they will remove it completely in the next release.
From the next release of the Google Play services SDK, the requirement for the WRITE_EXTERNAL_STORAGE permission will be completely dropped from the Google Maps Android API.

Note: Please do the described changes in your application if you have Google Maps and want to target Android M!


Thanks for reading :) 
Whether this post is helpful?

Have something to add to this post? If you have any other quick thoughts/hints that you think people will find useful? Share it in the comments. feedback are welcome...

Sunday, March 1, 2015

Android and the DEX 64K Methods Limit & Online Tool

Our apps are limited to a 64K method reference limit. If your app reaches this limit, the build process outputs the following error message:

Unable to execute dex: method ID not in [0, 0xffff]: 65536

Tools

This is a drap and drop tool which helps us to find the number of method in apk http://inloop.github.io/apk-method-count/.
Which helps us to be in safe-guard in optimizing things. Know we need some solutions to optimize the problem. Let find them

Solutions

MultiDex

MultiDex allows you to use multiple DEX files contained within one APK. With a few steps, your classes will split automatically into several DEX files (classes.dex,classes2.dex, classes3.dex, etc) in case you reach the method index limit.
ProGuard
ProGuard is a tool that shrinks, optimizes and obfuscates your code by removing unused code and renaming classes, fields and methods with semantically obscure names.

JarJar

Jar Jar Links is a utility that makes it easy to repackage Java libraries and embed them into your own distribution.

Conclusion

At this point, Google Play Services is perhaps the biggest common threat on your methods count. I would love to see this API broken into separate modules. A detailed summary of this problem was published a while ago by Jake Wharton & Android and the dex 64k methods limit by Tom Renzik, so feel free to dive into that as well.

Another interesting blog post was published a while ago by Cyril Mottier, illustrating how to reduce APK size using various different techniques. 



Thanks for reading :) 
Whether this post is helpful?

Have something to add to this post? If you have any other quick thoughts/hints that you think people will find useful? Share it in the comments.

Wednesday, February 25, 2015

Usage of Android manifestmerger

Before going into manifestmerger, we will have questions why to merge?
Let start ...
Why to merge manifest files?
Assume we have a multiple libraries and each of them contribute Activity/Receiver/Services and many more into the application. Managing all in one manifest files makes like miserable.
To solve the above approach, we can manage their own Activity/Receiver/Services and more in their own manifest file and build time, we can combined all together.
Now, how to merge manifest file?
ADT 20.0.0 introduced new property to help in merging the manifest files, which helps in merging all the manifest files using property “manifestmerger.enabled “.

What the manifestmerger.enabled do?

It automatically merges the library project manifest files into the including project's manifest. Just by using the manifestmerger.enabled property, we can enable this feature.

We need to add this property in the project.properties file of your project.

What errors we may face?

If the configuration is done properly in the manifest file, we may face “Unknown error merging manifest” Android Manifest Merger Problem.

Solution to solve this exception:

Be clear in using of android:targetSdkVersion and android:minSdkVersion.
Your minSdkVersion of library should not be less than your project minSdkVersion and Your targetSdkVersion of library should not be more in than your project manifest file.




Thanks for reading :) 
Whether this post is helpful?

Have something to add to this post? If you have any other quick thoughts/hints that you think people will find useful? Share it in the comments.

Thursday, November 6, 2014

Android : Usages & Issues of Toolbar (Material Compatibility) in Appcompat 21

Toolbar Widget

Toolbar is fully supported in AppCompat and has feature and API parity with the framework widget. In AppCompat,Toolbar is implemented in the android.support.v7.widget.Toolbar class. There are two ways to use Toolbar:
  • Use a Toolbar as an Action Bar when you want to use the existing Action Bar facilities (such as menu inflation and selection, ActionBarDrawerToggle, and so on) but want to have more control over its appearance.
  • Use a standalone Toolbar when you want to use the pattern in your app for situations that an Action Bar would not support; for example, showing multiple toolbars on the screen, spanning only part of the width, and so on.
Toolbar supports a more focused feature set than ActionBar. From start to end, a toolbar may contain a combination of the following optional elements:
  1. A navigation button
  2. A branded logo image
  3. A title and subtitle
  4. One or more custom views
  5. An action menu

Things to do remind while Implementing ToolBar

IllegalStateException (windowActionBar)

java.lang.RuntimeException: Unable to start activity ComponentInfo{}: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.

Solution:

add
 <item name="windowActionBar">false</item>  
in theme.

Apply Styles for Version above API level 14+


   <color name="holo_blue_light">#ff33b5e5</color>  
   <color name="green">#36A245</color>  
   <color name="ripple_material_light">#40000000</color>  
   <style name="AppBaseTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">  
     <item name="windowActionBar">false</item>  
     <item name="colorPrimary">@color/holo_blue_light</item>  
     <item name="colorPrimaryDark">@color/green</item>  
     <item name="colorAccent">@color/ripple_material_light</item>  
   </style>  

Above 21+


   <style name="AppBaseTheme" parent="android:Theme.Material.Light">  
     <item name="windowActionBar">false</item>  
     <item name="colorPrimary">@color/ripple_material_light</item>  
     <item name="colorPrimaryDark">@color/green</item>  
     <item name="colorAccent">@color/holo_blue_light</item>  
   </style>  

Styling of ToolBar:

Styling of Toolbar is done differently to the standard action bar, and is set directly onto the view.

   <android.support.v7.widget.Toolbar  
     xmlns:app="http://schemas.android.com/apk/res-auto"  
     android:id="@+id/my_awesome_toolbar"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:background="?attr/colorPrimary"  
     android:minHeight="?attr/actionBarSize"  
     app:theme="@style/ThemeOverlay.AppCompat.Light" />  

ThemeOverlay.AppCompat.Light : Changes the Toolbar title text color to Black.
ThemeOverlay.AppCompat.Dark.ActionBar : Changes the Toolbar title text color to White.


Usage of inflateMenu in Toolbar:

If you're using setSupportActionBar(toolbar); then inflateMenu of toolbar cannot be used, because Toolbar is acting like Actionbar. So, all the menu related callbacks are default.

The only time you need to call toolbar.inflateMenu() is when you are using the Toolbar as a standalone widget. In this case you need to manually populate the Toolbar with content/actions. For instance, if you want it to display actions, you need to inflate a menu into it:

 Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);  
 // Set an OnMenuItemClickListener to handle menu item clicks  
 toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {  
 @Override  
 public boolean onMenuItemClick(MenuItem item) {  
      switch (item.getItemId()) {  
      case R.id.searchItem:  
           Toast.makeText(getApplicationContext(), "Search", Toast.LENGTH_SHORT).show();  
           break;  
      case R.id.filterItem:  
           Toast.makeText(getApplicationContext(), "Filter", Toast.LENGTH_SHORT).show();  
           break;  
      }  
      return true;  
      }  
 });  
 // Inflate a menu to be displayed in the toolbar  
 toolbar.inflateMenu(R.menu.toolbar_menu);  
 
res/xml/toolbar_menu.xml  
 <?xml version="1.0" encoding="utf-8"?>  
 <menu xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:app="http://schemas.android.com/apk/res-auto" >  
   <item  
     android:id="@+id/searchItem"  
     android:icon="@android:drawable/ic_menu_search"  
     android:title="Search"  
     app:showAsAction="always"/>  
   <item  
     android:id="@+id/filterItem"  
     android:icon="@android:drawable/ic_menu_info_details"  
     android:title="Info"  
     app:showAsAction="always"/>  
 </menu>  


Navigations in Toolbar:

Here we can see how toolbar navigation works and this is similar to the action of setDisplayHomeAsUpEnabled(true) in the actionbar.
Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
toolbar.setTitle("Second Activity");
toolbar.setNavigationIcon(R.drawable.ic_up);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
           NavUtils.navigateUpTo(SecondActivity.this, IntentCompat.makeMainActivity(new ComponentName(SecondActivity.this, SecondActivity.class)));
           }
});


Customize Toolbar:

The customization of the toolbar here is to center align the title text and it is as follows.

<android.support.v7.widget.Toolbar  
     xmlns:app="http://schemas.android.com/apk/res-auto"  
     android:id="@+id/my_awesome_toolbar"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:background="?attr/colorPrimary"  
     android:minHeight="?attr/actionBarSize"  
     app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" >  
     <TextView  
       android:id="@+id/toolbar_title"  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:layout_gravity="center"  
       android:singleLine="true"  
       android:text="Toolbar Title"  
       android:textColor="@android:color/white"  
       android:textSize="18sp"  
       android:textStyle="bold" />  
</android.support.v7.widget.Toolbar>  


Source Code
You can download the source code by clicking here: ToolBarMaterialComp Source Code.  This project is built using eclipse IDE. Unzip and import the project into Eclipse, it’s a good idea to use the Project by clean and rebuild from the project menu. It works in all API levels above 2.3.

As always, thanks for reading :) 
Don't forget to +1 this blog and share this post on Google+ if you found it interesting!

Have something to add to this post? If you have any other quick thoughts/hints that you think people will find useful? Share it in the comments & feedback's are welcome.

Wednesday, September 24, 2014

Android: Material Theme in Kitkat

Material Theme look and feel can be easily achieve in KitKat because of the new features Translucent UI in KitKat, where you have the ability to sit behind status and navigation bars

We can getting material theme look and feel in 2 ways.

1. We can write our own styles.xml and modify according to our needs.
2. Import SystemBarTint library and apply changes as per need.

First Approach using styles.xml:

We can build our own theme by setting with Translucent Theme in xml

If you are seeking more control over translucent decor, consider using a custom theme that extends something other than *.TranslucentDecor and use the following style properties in your theme:

 <item name="android:windowTranslucentStatus">true</item>  
 <item name="android:windowTranslucentNavigation">true</item>  

If your content does not need to be full bleed you can structure your layouts in such a way that the content will reside in an area of the screen that is not blocked by the status or navigation bar. To do this you would set android:fitsSystemWindows="true" on the content layout/view in your layout xml or in style.xml as
  <item name="android:fitsSystemWindows">true</item>.  
.
Add Some Color to the status bar, just set the windowBackground attribute in my theme.
 <item name="android:windowBackground">@color/window_bg</item>  

Second Approach Using SystemBarTine:

This library jgilfelt-SystemBarTint offers a simple way to create a background "tint" for the system bars. Internally even this library is depended on the Translucent  theme.


Source Code
You can download the source code by clicking here: MaterialThemeLookInKitKat.  This project is built using eclipse IDE. Unzip and import the project into Eclipse, it’s a good idea to use the Project by clean and rebuild from the project menu. This example is built using 2nd approach.

Output:



Thanks for reading :) 
Whether this post is helpful?

Have something to add to this post? If you have any other quick thoughts/hints that you think people will find useful? Share it in the comments.

Friday, September 12, 2014

Android: Image loading libraries Picasso vs Glide

This post is about image loading libraries, which could help us in avoiding complex codes.

Downloading of images, caching and reusing of images are know part of all the application and it became part of developers life. While doing this process, We need to consider few things...

  • Loading process should be asynchronously.
  • Image should display when it is loaded successfully, In case if it is not downloaded then placing some place holders.
  • Caching Image rather than downloading every time.

There are more libraries in the market which helps us in avoiding to do all these exercises and here I am going to discuss about Picasso and Glide. Where this two libraries looks similar in the way of implementation and Its easy to integrate in the middle of the application, since its a just a one line code to load image.

There are lot of features in the two libraries and few are listed below, where I can compare them easily.

Wednesday, August 13, 2014

Solution/Precaution to avoid android.os.TransactionTooLargeException

Exception: :mad:

 java.lang.RuntimeException: android.os.TransactionTooLargeException  
 at android.accounts.AccountManager.addAccountExplicitly(AccountManager.java:568)  

Reason: ;))

The Binder transaction failed because it was too large.
During a remote procedure call, the arguments and the return value of the call are transferred as Parcel objects stored in the Binder transaction buffer. If the arguments or the return value are too large to fit in the transaction buffer, then the call will fail and TransactionTooLargeException will be thrown.

Possibility Cases: :-w 

There are two possible outcomes when a remote procedure call throws TransactionTooLargeException.

  • Either the client was unable to send its request to the service (most likely if the arguments were too large to fit in the transaction buffer).
  • The service was unable to send its response back to the client (most likely if the return value was too large to fit in the transaction buffer).
It is not possible to tell which of these outcomes actually occurred. The client should assume that a partial failure occurred.

Assumption: :-?

While adding account to AccountManager. Adds an account directly to the AccountManager with the help of service call.
When there is a huge amount of data getting exchanged between a service and an application, we will get android.os.TransactionTooLargeException.

Solution/Precaution to avoid android.os.TransactionTooLargeException *-:)

We don't have direct solution but we can take precaution to avoid exception.
  1. Try to keep all transactions relatively small.
  2. Do not exchange huge data (roughly not greater than 512KB) between services and application because the Binder transaction buffer has a limited fixed size, currently 1Mb, which is shared by all transactions in progress for the process. 


Thanks for reading :) 
Whether this post is helpful?

Have something to add to this post? If you have any other quick thoughts/hints that you think people will find useful? Share it in the comments and feedback are welcome...

Sunday, July 27, 2014

Android Supporting tools for Developers / Designers

This post is going to give some useful tools which android developers could be found easy during application development. I have listed down few useful tools below.

Tools Used for Designers / Developers


Android Button Maker is online tool to generate buttons code for Android Apps. Android API provide Drawable Resources where XML file defines geometric shape, including colors, border and gradients.
These button is generating based on shape drawable XML code which load faster compare to normal png buttons. You can customize button properties in setting panel and get source code.




Android uses Density Independent Pixel (dpi) values to scales the actual screen size. To get device pixel density use getResources().getDisplayMetrics().density;


Open Source Utilities to Optimize PNG Images

There are free tools such as OptiPNG or PNGCrush or TinyPNG for optimizing PNG image files. These tools are open-source and use command line utilities for optimizing PNG images. They can compress the image by using various combinations of algorithms, such as changing the bit depth, replacing unwanted chucks of data with text, delta filters, and so forth to provide the smallest compressed output.

If your app is highly depend on art/creative then you should think over optimizing and shrinking art/creative to decrease file size, it would help you to decrease APK size.



A web-based set of tools for generating graphics and other assets that would eventually be in an Android application's res/ directory.
Currently available asset generators area available for:
OTHER GENERATORS MISCELLANEOUS ASSET CREATION TOOLS
COMMUNITY TOOLS SIMILAR TOOLS FROM THE OPEN SOURCE COMMUNITY

Tools Used for Developers


During development you typically add a lot of resources such as files, layouts, or drawables. As you go back and made changes and improvements, some of these resources are no longer used, and get left in your code. To detect such unused resources and remove them from your APK file, use the android-unused-resources tool. It scans your project and identifies unused resources. Removing them minimizes the build time and reduces the APK file size.



The Android Layout Finder helps you create the code that ties your Android UI and Java code together.
It's real easy! Just paste your Android XML layout code in the first text field, pick the views that you need, and your code is automatically generated for you.
No more typing out all those nearly identical findViewById() and findFragmentById() calls in your activities or fragments whenever you change your Android layouts.
This tools having special output settings, which helps us in generating code type using RoboGuice, member variable and so on.




Similar to the above layout to Java code generator, we have one android-code-generator-plugin for eclipse which generates code from xml, which Generating Activity Class code based on XML layout.


Generate Plain Old Java Objects from JSON or JSON-Schema.
This tools helps in giving annotation style like Jackson 2.x, Jackson 1.x, Gson.
Note: Your input Json Cannot be more than 51200 characters.




There are some other tool for Json to POJO conversion, but it is not like the above one, we can't copy and paste the Json, rather than we should give the json url as input. For more info check Jsongen.byingtondesign


Thanks for reading :) 
Whether this post is helpful?

Have something to add to this post? If you have any other quick thoughts/hints that you think people will find useful? Share it in the comments and feedback are welcome.

Friday, July 11, 2014

Android: iOS Style Badge App Icon for Sony, Samsung and HTC devices

This post is continue to one of my old post Android Get iOS Style Badge App Icon

Know a days we are seeing facebook,whatsapp and lots of apps are using badges on the app icon and  they are not replacing any app icon and they are able to achieve badge on app icon and we should be having question, How it is possible?

iOS style badge icon is achieved in android by few manufactures (Sony, Samsung, HTC...) but the way of implementation is different from each one of the manufacture for the badge on app icon.

Before implementing the badge on app icon, check the manufacture and then support.

// The manufacturer of the product/hardware.
Build.MANUFACTURER;

Lets go with each of the manufacture implementation:
Sony:

Manifest File changes:

 <uses-permission android:name="com.sonyericsson.home.permission.BROADCAST_BADGE" />  

Code Changes:

 try {  
      intent.setAction("com.sonyericsson.home.action.UPDATE_BADGE");  
      intent.putExtra("com.sonyericsson.home.intent.extra.badge.ACTIVITY_NAME", "com.vardhan.notificationbadgesample.MainActivity");  
      intent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", true);  
      intent.putExtra("com.sonyericsson.home.intent.extra.badge.MESSAGE", badgeno);  
      intent.putExtra("com.sonyericsson.home.intent.extra.badge.PACKAGE_NAME", "com.vardhan.notificationbadgesample");  
      sendBroadcast(intent);  
 } catch (Exception localException) {  
      Log.e("CHECK", "Sony : " + localException.getLocalizedMessage());  
 }  


HTC:

Manifest File changes:

 <uses-permission android:name="com.htc.launcher.permission.READ_SETTINGS" />  
 <uses-permission android:name="com.htc.launcher.permission.UPDATE_SHORTCUT" />  


Code Changes:

 try {  
      Intent localIntent1 = new Intent("com.htc.launcher.action.UPDATE_SHORTCUT");  
      localIntent1.putExtra("packagename", "com.vardhan.notificationbadgesample");  
      localIntent1.putExtra("count", badgeno);  
      sendBroadcast(localIntent1);  
      Intent localIntent2 = new Intent("com.htc.launcher.action.SET_NOTIFICATION");  
      ComponentName localComponentName = new ComponentName(this, "com.vardhan.notificationbadgesample.MainActivity");  
      localIntent2.putExtra("com.htc.launcher.extra.COMPONENT",      localComponentName.flattenToShortString());  
         localIntent2.putExtra("com.htc.launcher.extra.COUNT", 10);  
      sendBroadcast(localIntent2);  
 } catch (Exception localException) {  
      Log.e("CHECK", "HTC : " + localException.getLocalizedMessage());  
 }  


Samsung:

Manifest File changes:

   <uses-permission android:name="com.sec.android.provider.badge.permission.READ" />  
   <uses-permission android:name="com.sec.android.provider.badge.permission.WRITE" />  


Code Changes:

 try {  
    ContentResolver localContentResolver = getContentResolver();  
    Uri localUri = Uri.parse("content://com.sec.badge/apps");  
    ContentValues localContentValues = new ContentValues();  
    localContentValues.put("package", "com.vardhan.notificationbadgesample");  
    localContentValues.put("class", "com.vardhan.notificationbadgesample.MainActivity");  
    localContentValues.put("badgecount", Integer.valueOf(badgeno));  
    String str = "package=? AND class=?";  
    String[] arrayOfString = new String[2];  
    arrayOfString[0] = "com.vardhan.notificationbadgesample";  
    arrayOfString[1] = "com.vardhan.notificationbadgesample.MainActivity";  
      int update = localContentResolver.update(localUri, localContentValues, str, arrayOfString);  
      if (update == 0) {  
           localContentResolver.insert(localUri, localContentValues);  
      }  
 } catch (IllegalArgumentException localIllegalArgumentException) {  
      Log.e("CHECK", "Samsung1F : " + localIllegalArgumentException.getLocalizedMessage());  
 } catch (Exception localException) {  
      Log.e("CHECK", "Samsung : " + localException.getLocalizedMessage());  
 }  


Output


Source Code
You can download the source code by clicking Source Code Click Here: .  This project is built using eclipse IDE. Unzip and import the project into Eclipse, it’s a good idea to use the Project by clean and rebuild from the project menu. It works in all API levels above 9

Thanks for reading :) 
Whether this post is helpful?

Have something to add to this post? If you have any other quick thoughts/hints that you think people will find useful? comments/feedback are welcome.

Tuesday, July 1, 2014

Android : Workaround for webview not loading https url

Basic steps to show WebView in the application
  1. Use WebView element in the layout xml.
  2. Provide internet permission in the AndroidManifest.xml file.
  3. loadUrl on WebView object.
  1. main.xml in the res/layout folder

 <?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
      android:layout_width="fill_parent"  
      android:layout_height="fill_parent"  
      android:orientation="vertical" >  
      <WebView  
           android:id="@+id/ displayWebview "  
           android:layout_width="fill_parent"  
           android:layout_height="fill_parent" />  
 </LinearLayout>   
  1. Application must have access to the Internet. To get Internet access, request the INTERNET permission in the AndroidManifest.xml file

 <manifest ... >  
   <uses-permission android:name="android.permission.INTERNET" />  
     ...  
 </manifest>  
  1. call the loadUrl() on webview object inside the onCreate() method of your activity class and pass the url as a parameter to it .

WebView webView = (WebView) findViewById(R.id.displayWebview);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("https://www.google.co.in/");

Problem: WebView is not loading if the request is https.
When we try url with https request, we may face blank page or error message saying “web page not available”

Issue:
WebView support ssl default and If we want to support third party then with few methods like setCertificate and so on we can make it. However, WebView Shows blank screen if it is not supporting the certificates. So, Catch the exception in onReceivedSslError method and do respective action when certificate is not supported. When certificate is not supported we may get blank screen or “Web Page not available, The webpage at might be temporarily down or it may have moved permanently to a new web address”.

Solution:

There is a Work around to solve the issue by Overriding onReceivedSslError method of WebViewClient as shown below.

webView = (WebView) findViewById(R.id.displayWebview);
webView.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedSslError(final WebView view, final SslErrorHandler handler, SslError error) {
    Log.d("CHECK", "onReceivedSslError");
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    AlertDialog alertDialog = builder.create();
    String message = "Certificate error.";
    switch (error.getPrimaryError()) {
        case SslError.SSL_UNTRUSTED:
            message = "The certificate authority is not trusted.";
            break;
        case SslError.SSL_EXPIRED:
            message = "The certificate has expired.";
            break;
        case SslError.SSL_IDMISMATCH:
            message = "The certificate Hostname mismatch.";
            break;
        case SslError.SSL_NOTYETVALID:
            message = "The certificate is not yet valid.";
            break;
    }
    message += " Do you want to continue anyway?";
    alertDialog.setTitle("SSL Certificate Error");
    alertDialog.setMessage(message);
    alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Log.d("CHECK", "Button ok pressed");
            // Ignore SSL certificate errors
            handler.proceed();
        }
    });
    alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Log.d("CHECK", "Button cancel pressed");
            handler.cancel();
        }
    });
    alertDialog.show();
    }
});
webView.loadUrl("https://www.google.co.in/");




Thanks for reading :) 
Whether this post is helpful?

Have something to add to this post? If you have any other quick thoughts/hints that you think people will find useful? comments / feedback are welcome.