Sunday, April 28, 2024
HomeAndroidCreate Android app for Website/ Blog using WebView in New Android Studio

Create Android app for Website/ Blog using WebView in New Android Studio

-

How to create Android app for website using WebView:

With a steep increase of Mobile users, many of website owners are now creating an android app for their website. This helps in increasing their user database. In this tutorial, I will show you how to create a basic android app for your website using WebView in android. We will use New Android Studio to create this project. Make sure that your website is crafted for Responsive Web Design in order for this tutorial to work.

[widget id=”text-15″]

If you are using a WordPress or any other CMS (Content Management System), make sure you are using a responsive theme. Now Get ready to create your own Android app for your Website!

The complete code to create android app for website can be cloned / downloaded from the link attached below:

Click Here to Download

Create Android App for Website:

create android app for website

Requirements and Recommended Tutorials for this article:

To Create Android App, first you need to know following requirements:

  1. How to implement a splash screen for your Android Project.
  2. How to create android Project using Android Studio.
  3. A Responsive Website.
  4. A little bit of Java.

Steps for Creating Android App for your Website using WebView:

  1. Create a New Android Project and Name it any thing you want. Here I am Creating an Android App for this Website, coderefer.com. So I am naming it as CodeRefer. We have already discussed about Creating Android Project in our Previous articles, I will just go briefly.
  2. Now select minimum SDK. I am selecting minimum SDK as API 10. Select Blank Activity > Next> Finish. I am leaving the names of activity and xml file as per default name. This completes creating Android Project.[widget id=”text-3″]
  3. Now you can Implement the Splash Screen. We have discussed about how to implement a splash screen in our previous article.
  4. Now open Main Activity.java from Project Name > app > src > main > java > MainActivity
  5. Now type the following code:
    package com.coderefer.coderefer;
    
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.content.DialogInterface;
    import android.graphics.Bitmap;
    import android.os.Bundle;
    import android.view.KeyEvent;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.webkit.WebSettings;
    import android.webkit.WebView;
    import android.webkit.WebViewClient;
    import android.widget.ProgressBar;
    
    
    public class MainActivity extends Activity {
    
     private WebView mWebView;
     ProgressBar progressBar;
    
    
     @Override
     protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
    
     mWebView = (WebView) findViewById(R.id.activity_main_webview);
    
     progressBar = (ProgressBar) findViewById(R.id.progressBar1);
    
     WebSettings webSettings = mWebView.getSettings();
     webSettings.setJavaScriptEnabled(true);
     mWebView.loadUrl("http://13.126.215.213.xip.io/test");
     
     }
    }

     

    Here you need to specify which url to load in WebView’s loadUrl Just type your web address there. Here I am using my website url : http://13.126.215.213.xip.io/test for which I want to design app for.

    [widget id=”text-15″]

    We now edit activity_main.xml by clicking text tab and paste the following code to display progressbar and to display your website after it is fetched:

  6. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
        android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
    
        <ProgressBar
            android:layout_centerHorizontal="true"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:layout_gravity="center_vertical|center_horizontal"
            android:id="@+id/progressBar1"/>
    
        <TextView
            android:layout_below="@+id/progressBar1"
            android:layout_height="wrap_content"
            android:id="@+id/LoadingText"
            android:layout_width="fill_parent"
            android:text="Loading, Please Wait.."
            android:textSize="20sp"
            android:gravity="center_horizontal">
        </TextView>
    
        <WebView
            android:id="@+id/activity_main_webview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    
    </RelativeLayout>
  7. Make sure you added Internet permission for your manifest. If not add this piece of code in your manifest:
    <uses-permission android:name="android.permission.INTERNET"/>

    Now you can run your app to display your Website, but here is the problem: When you click on any link on your website, it opens your mobile browser instead of showing the link in your app. We need to make sure that any link opens in the app itself.[widget id=”text-3″]

    To make any link to work in the app itself, replace the code with the following in MainActivity.java:

  8. package com.coderefer.coderefer;
    
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.content.DialogInterface;
    import android.graphics.Bitmap;
    import android.os.Bundle;
    import android.view.KeyEvent;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.webkit.WebSettings;
    import android.webkit.WebView;
    import android.webkit.WebViewClient;
    import android.widget.ProgressBar;
    
    
    public class MainActivity extends Activity {
    
        private WebView mWebView;
        ProgressBar progressBar;
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            mWebView = (WebView) findViewById(R.id.activity_main_webview);
    
            progressBar = (ProgressBar) findViewById(R.id.progressBar1);
    
            WebSettings webSettings = mWebView.getSettings();
            webSettings.setJavaScriptEnabled(true);
            mWebView.loadUrl("http://13.126.215.213.xip.io/test");
            mWebView.setWebViewClient(new HelloWebViewClient());
    
    
        }
    
        private class HelloWebViewClient extends WebViewClient{
    
    
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                // TODO Auto-generated method stub
                super.onPageStarted(view, url, favicon);
            }
    
            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, String url)
            {
                webView.loadUrl(url);
                return true;
            }
    
            @Override
            public void onPageFinished(WebView view, String url) {
                // TODO Auto-generated method stub
                super.onPageFinished(view, url);
    
                progressBar.setVisibility(view.GONE);
            }
    
        }
    
    
        @Override
        public boolean onKeyDown(int keyCode, KeyEvent event)
        { //if back key is pressed
            if((keyCode == KeyEvent.KEYCODE_BACK)&& mWebView.canGoBack())
            {
                mWebView.goBack();
                return true;
    
            }
    
            return super.onKeyDown(keyCode, event);
    
        }
    
    
    
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_main, menu);
            return true;
        }
    
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();
    
            //noinspection SimplifiableIfStatement
            if (id == R.id.action_settings) {
                return true;
            }
    
            return super.onOptionsItemSelected(item);
        }
    
        public void onBackPressed() {
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                    MainActivity.this);
    
            // set title
            alertDialogBuilder.setTitle("Exit");
    
            // set dialog message
            alertDialogBuilder
                    .setMessage("Do you really want to exit?")
                    .setCancelable(false)
                    .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                            // if this button is clicked, close
                            // current activity
                            MainActivity.this.finish();
                        }
                    })
                    .setNegativeButton("No",new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                            // if this button is clicked, just close
                            // the dialog box and do nothing
                            dialog.cancel();
                        }
                    });
    
            // create alert dialog
            AlertDialog alertDialog = alertDialogBuilder.create();
    
            // show it
            alertDialog.show();
        }
    }
    

    Here we additionally setup WebViewClient to display any link in the app itself and we also overrided onKeyDown method to implement WebView’s goBack Method. We used onBackPressed Method to display Exit Dialog if user presses back key from the specified URL.

  9. Now you can change the launcher icons by replacing the icons in mipmap folders generally located at C:\Users\username\AndroidStudioProjects\CodeRefer\app\src\main\res. To generate icon pack you can use this link.

Your basic mobile App for your Website is now ready! Leave your comments below if there are any queries.

[widget id=”text-15″]

66 COMMENTS

  1. I am getting an error in MainActivity.java

    (this is underlined red)@Override
    public boolean shouldOverrideURLLoading(WebView webView, String url)
    {
    webView.loadUrl(url);
    return true;
    }

    The actual error is listed as:
    Error:(44, 9) error: method does not override or implement a method from a super type

    Any ideas?

  2. Hi,

    Thank you very much for your tutorial. I learnt to create an app in less than two hours.
    Could you guide me on how to enable pinch zoom in and out , in this same method. Will be very helpful.

    Thank you
    Aditya Elango

  3. Thanks indeed for this nice piece. However, when a device losses an internet access, the webview displays error message and show the URL… Now how to hide this URL when no internet access is available?

  4. Thank you for your tutorials. But I have a little problem with my app. I connect 2 tutorials in one app(about webview and splash screen). And know, when I am installing it on mobile, in screen it is showing to applications. One with splash screen and one without it. Can anyone help me to solve this problem?

  5. Dear Vamsi Tallapudi,
    Thanks a lot for this detailed tutorial.
    I was able to make my app within 15 mins even since I do not have any knowledge of coding (am a mechanical geek).
    Only problem I am facing is that I have a upload button on my responsive website and this upload option is not working in app.
    Noting happens when the button is clicked.
    Could you please suggest some solution for this. Otherwise it is a fantastic guide.
    Jaspal Singh
    Jaspal Singh

    • Remove the following lines from the Relative Layout of activity_main.xml:
      android:paddingLeft=”@dimen/activity_horizontal_margin”
      android:paddingRight=”@dimen/activity_horizontal_margin”
      android:paddingTop=”@dimen/activity_vertical_margin”
      android:paddingBottom=”@dimen/activity_vertical_margin”

  6. To make any link to work in the app itself section you have given code for main activity , but what abut layout xml?
    Or we don’t need to change the xml file? (Sorry newbie to all of this)

  7. I did all the above steps…
    but when I install the app its shows ” unfortunately force stopped”
    I’m new in this… can u pls help me in this

  8. Hey, This tutorial ROCKS.
    Just one question… My web app has margins like a border (white border) around it. How can I make the page to full screen?

  9. Hi friends,

    How to make a android app for my website, my website is responsive site, already i tried to make android app, but its fail, android studio needs many add-ons in SDK manager or any other, i already copy source code from this code refer for my app,

    The android studio AVD manager not working correctly, i want to make android app and i want to this app working on android v4.0 devices…

    I need some information, friends give your suggestions :

  10. Thank you for your tutorials. But I have a little problem with my app. I
    connect 2 tutorials in one app(about webview and splash screen). And
    know, when I am installing it on mobile, in screen it is showing to
    applications. One with splash screen and one without it. How to keep only one ?

    And After Splash Screen Loading Please wait comes, can we make it visible on Splash screen and as soon as loading done direct website comes ?

    When website loads it has padding, i trued your solution of removing padding from main activity but still padding comes

    Thanks for Great Tutorials. (Kindly answer this as almost all users are having this questions)

    • Did you solve your problems?

      I am trying to do the same, but I am dealing with a different problem: my webview is very laggy after implementing the splashscreen.

      Did you face this problem?

  11. this is wonderful though i have found that my website is not compatible with WebView is there a way for the .APK to open the site with another browser?

  12. Hi,

    I do not have discuss, hence posting here. I am using your how to build webview app tutorial with splash screen tutorial. I have done everything as you told. Just that while building app, I am getting error message for ” menu ” and ” action_settings ” part of the following code. They are shown in red and console says

    Error:(134, 36) error: cannot find symbol variable menu

    Error:(146, 23) error: cannot find symbol variable action_settings

    :app:compileReleaseJavaWithJavac FAILED

    Error:Execution failed for task ‘:app:compileReleaseJavaWithJavac’.
    > Compilation failed; see the compiler error output for details.


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
    return true;
    }

    Any help possible ?

  13. I am facing another issue now. I used the webview app for discuss.flarum.org. Everything went well for me except that the site loads as if no JS is loaded. That’s been an issue with the script since some time. But what puzzles me is that the web version of the website is working fine. Is there anything we can do to solve it ? The script author said clear cache. I am not sure how to ” clear cache ” when we in app and using it for the first time on phone.

  14. Wonderful tutorial: the best I have read so far!

    Would it be easy to add a splash screen to it?

    And, besides a splash screen, what more improvementes would you recommend for a website app?

  15. hi there, im getting the following error in the MainActivity extends Activity {} method:

    error:cannot find symbol method findViewByID (int)

    ive tried creating a method called findViewByID but i still get runtime errors

    any suggestions anyone??

  16. i m new in . i used this code for change my website into android app… it works properly in lollipop and 6 but not running on kitkat and jelly bean phones… help me pls

  17. Hey Man, Your Tutorials are just awesome but can u please let me know about how to add download manager in my app, because I have a .Mp3 site and whenever I click on download song button my app got stuck… so please help me to make webview app with download manager…

  18. Hi please help me i am unable to run it on my mobile this error comes
    Error:Could not create service of type ProjectEvaluator using BuildScopeServices.createProjectEvaluator().
    > Could not determine implementation class for service ‘org.gradle.configuration.project.ProjectConfigureAction’ specified in resource ‘jar:file:/I:/Android/Android%20Studio/gradle/gradle-2.10/lib/plugins/gradle-ide-2.10.jar!/META-INF/services/org.gradle.configuration.project.ProjectConfigureAction’.

  19. I am getting a error in MainActivity.java

    menu_main cannot be resolved or is not a field

    how can i remove that error?

  20. unable to resolve problem with menu in “getMenuInflater().inflate(R.menu.menu_main, menu);” and action_settingin “if (id == R.id.action_settings) “” part please help…

  21. additional code to remove error R.menu problem

    create a new file named “main_menu.xml” in folder res>menu>main_menu.xml
    Write below code in main_menu.xml

  22. thank for your tuts its worked for me.so some error .i fix that like error cache miss this is due to the missing of code in manifest . i didn’t care about it .so thank you for your support

  23. Hi,

    I need some help to solve my problem. Problem is

    I was created android app from my website, so I want to make mobile number clickable and after click on mobile number open caller page and if more than 1 caller apps available then show popup.

    Thanx in advance.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.

LATEST POSTS

3 Sum | Leetcode #15 | 100 Days of Code Day 10

Today we are going to solve 3 Sum - our first Medium Level Array problem from Coderefer DSA Sheet. If you are new to this...

Best Time to Buy and Sell Stock – Day 7 | 100 Days of Code

Welcome to Day 7 of 100 Days of Code where today we solve yet another most frequently asked easy array problem called - Best Time...

Contains Duplicate – Day 8 | 100 Days of Code

Welcome to Day 8 of 100 Days of Code and today we are going to solve yet another easy-level problem - Contains Duplicate as part...

Two Sum – Day 6 | 100 Days of Code

Welcome to Day 6 of 100 Days of Code where we solve the most frequently asked Easy level Array problem - Two Sum. Let us...

Follow us

1,358FansLike
10FollowersFollow
400SubscribersSubscribe

Most Popular