1. Download our Official Android App: Forums for Android!

webView | Native App | Open Website in Anderiod App |

Discussion in 'Android Development' started by irex, Jul 11, 2019.

  1. irex

    irex Lurker
    Thread Starter
    Rank:
    None
    Points:
    6
    Posts:
    2
    Joined:
    Jul 11, 2019

    Jul 11, 2019
    2
    1
    6
    Hi There

    I am stuck at following piece of code.

    when i write this piece of code
    myWebView = (WebView)findViewById(R.id.WebView);
    i get error "cannot resolve symbol 'webView'.

    Please anyone can help me how to fix this error.
    -------------------------
    ==for your reference i am copying MainActivity.Java code below ===

    package com.irex.lingo_6;

    import androidx.appcompat.app.AppCompatActivity;

    import android.os.Bundle;
    import android.webkit.WebSettings;
    import android.webkit.WebView;
    import android.webkit.WebViewClient;

    public class MainActivity extends AppCompatActivity {
    private WebView myWebView;
    @override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    myWebView = (WebView)findViewById(R.id.WebView);
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    myWebView.loadUrl("http://irex.pk/lingo-school/signin/index");
    myWebView.setWebViewClient(new WebViewClient());
    }

    @override
    public void onBackPressed() {
    if(myWebView.canGoBack()) {
    myWebView.goBack();
    }else {
    super.onBackPressed();
    }

    }
    }
    =====activity_main.xml===

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <WebView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:layout_editor_absoluteX="8dp"
    tools:layout_editor_absoluteY="8dp" />
    </androidx.constraintlayout.widget.ConstraintLayout>

    ============ android manifest.xml====

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.irex.lingo_6">
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <application
    android:allowBackup="true"
    android:icon="@Mipmap/ic_launcher"
    android:label="@String/app_name"
    android:roundIcon="@Mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@Style/AppTheme">
    <activity android:name=".MainActivity">
    <intent-filter>
    <action android:name="android.intent.action.MAIN" />

    <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    </activity>
    </application>

    </manifest>
     

    Advertisement

  2. Unforgiven

    Unforgiven ...eschew obfuscation...
    Moderator
    Rank:
     #1
    Points:
    4,488
    Posts:
    38,220
    Joined:
    Jun 23, 2010

    Jun 23, 2010
    38,220
    47,348
    4,488
    Male
    Douglas, MA
    Development thread moved to the dev area for better exposure. :)
     
  3. GameTheory

    GameTheory Android Expert
    Rank:
     #41
    Points:
    493
    Posts:
    3,973
    Joined:
    Jul 23, 2012

    There are many ways to write your webview code. Here is an example of how I do it.

    This is a webview class complete with page load progressbar and the ability to download from any download links. You can also pass any url to it or as many as you like. If you only need one static url, then change the "static String url" with your static url.

    Read the comments within the code as they explain what everything does.

    Code (Java):
    1. package com.webviewexample;
    2.  
    3. import android.Manifest;
    4. import android.annotation.SuppressLint;
    5. import android.app.DownloadManager;
    6. import android.content.pm.PackageManager;
    7. import android.graphics.Bitmap;
    8. import android.net.Uri;
    9. import android.os.Build;
    10. import android.os.Bundle;
    11. import android.os.Environment;
    12. import android.view.View;
    13. import android.webkit.CookieManager;
    14. import android.webkit.DownloadListener;
    15. import android.webkit.URLUtil;
    16. import android.webkit.WebView;
    17. import android.webkit.WebViewClient;
    18. import android.widget.ProgressBar;
    19. import android.widget.Toast;
    20.  
    21. import androidx.annotation.NonNull;
    22. import androidx.appcompat.app.AppCompatActivity;
    23. import androidx.core.app.ActivityCompat;
    24.  
    25. public class MyWebView extends AppCompatActivity {
    26.     // Declare our web view.
    27.     private WebView webview;
    28.  
    29.     // We can pass URLs from any other class to this string.
    30.     static String url;
    31.  
    32.     // Optional progress bar for page loading progress.
    33.     private ProgressBar progress;
    34.  
    35.     // A request code for our storage write request.
    36.     private static final int WRITE_STORAGE = 1;
    37.  
    38.     @SuppressLint("SetJavaScriptEnabled")
    39.     @Override
    40.     protected void onCreate(Bundle savedInstanceState) {
    41.         super.onCreate(savedInstanceState);
    42.         setContentView(R.layout.activity_webview);
    43.  
    44.         // Optional progress bar for page loading progress.
    45.         progress = findViewById(R.id.progressBar);
    46.  
    47.         // Attach our web view to our layout.
    48.         webview = findViewById(R.id.webView);
    49.         // Needed to interact with elements on most web pages.
    50.         webview.getSettings().setJavaScriptEnabled(true);
    51.         // This enables pinch to zoom.
    52.         webview.getSettings().setBuiltInZoomControls(true);
    53.         // Do not display the zoom controls on the screen.
    54.         webview.getSettings().setDisplayZoomControls(false);
    55.         // Loads a page to fit in the screen (zoomed out).
    56.         webview.getSettings().setLoadWithOverviewMode(true);
    57.         // Do not constrain the viewport to the web view dimensions.
    58.         webview.getSettings().setUseWideViewPort(true);
    59.         // Attach our web view to our WebViewClient.
    60.         webview.setWebViewClient(new MyWebViewClient());
    61.         // We call our url string variable to load.
    62.         webview.loadUrl(url);
    63.  
    64.         // Adds a DownloadListener to our web view. This allows us to click on
    65.         // download links and have items download to our downloads directory.
    66.         webview.setDownloadListener(new DownloadListener() {
    67.             public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
    68.                 String fileName = URLUtil.guessFileName(url, contentDisposition, mimetype);
    69.                 String cookie = CookieManager.getInstance().getCookie(url);
    70.                 DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    71.                 DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
    72.                 request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
    73.                 request.setAllowedOverRoaming(false);
    74.                 request.allowScanningByMediaScanner();
    75.                 request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
    76.                 request.addRequestHeader("Cookie", cookie);
    77.                 request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    78.                 // Check for storage write permission before attempting to download.
    79.                 if (getPermission()) {
    80.                     dm.enqueue(request);
    81.                 }
    82.             }
    83.         });
    84.  
    85.     }
    86.  
    87.     // Check if storage write permission has been granted. If not, request it.
    88.     private boolean getPermission() {
    89.         if (Build.VERSION.SDK_INT >= 23) {
    90.             if (ActivityCompat.checkSelfPermission(this,
    91.                     Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
    92.                 // True if permission granted exists.
    93.                 return true;
    94.             } else {
    95.                 // We ask for storage write permission if it doesn't exist.
    96.                 ActivityCompat.requestPermissions(this,
    97.                         new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_STORAGE);
    98.                 return false;
    99.             }
    100.         } else {
    101.             // True for SDK < 23
    102.             return true;
    103.         }
    104.     }
    105.  
    106.     // Check if user granted or denied storage write permission when requested and
    107.     // run code for either situation. This method is optional, but useful.
    108.     @Override
    109.     public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    110.         switch (requestCode) {
    111.             case WRITE_STORAGE: {
    112.                 if (grantResults.length > 0 &amp;&amp; grantResults[0] == PackageManager.PERMISSION_GRANTED) {
    113.                     Toast.makeText(getApplicationContext(), "Permission Granted!", Toast.LENGTH_LONG).show();
    114.                 } else {
    115.                     Toast.makeText(getApplicationContext(), "Permission Denied!", Toast.LENGTH_LONG).show();
    116.                 }
    117.             }
    118.         }
    119.     }
    120.  
    121.     // Attach our web view to our WebViewClient.
    122.     private class MyWebViewClient extends WebViewClient {
    123.         // This method makes sure that any links we click will open within
    124.         // our app instead of launching in the default web browser.
    125.         @Override
    126.         public boolean shouldOverrideUrlLoading(WebView view, String url) {
    127.             return super.shouldOverrideUrlLoading(view, url);
    128.         }
    129.  
    130.         // Since this method is called every time a new page starts to load, it's
    131.         // perfect to run our Progress Bar.
    132.         @Override
    133.         public void onPageStarted(WebView view, String url, Bitmap favicon) {
    134.             progress.setVisibility(View.VISIBLE);
    135.             super.onPageStarted(view, url, favicon);
    136.         }
    137.  
    138.         // Called whenever a page has finished loading. Here we can end our
    139.         // page loading progress bar and take it out of view.
    140.         @Override
    141.         public void onPageFinished(WebView view, String url) {
    142.             progress.setVisibility(View.GONE);
    143.             super.onPageFinished(view, url);
    144.         }
    145.  
    146.     }
    147.  
    148.     // If we have clicked through multiple pages, this allows the back button
    149.     // to take us back through each page.
    150.     @Override
    151.     public void onBackPressed() {
    152.         if (webview.canGoBack()) {
    153.             webview.goBack();
    154.         } else {
    155.             super.onBackPressed();
    156.         }
    157.     }
    158. }
    You can then pass a url to this class from any other class like this...

    Code (Java):
    1. public void googleButton(View view) {
    2.     MyWebView.url = "https://www.google.com/";
    3.     Intent intent = new Intent(this, MyWebView.class);
    4.     startActivity(intent);
    5. }
    I wrote a full tutorial complete with source code on github and a fully working app in the following link...
    https://intechgeek.com/android-webview/

    Try the sample app I provided to see if this code serves your purpose. Just check the app/release/ folder in the github source code.
     
    Greum and Unforgiven like this.
  4. 23tony

    23tony Well-Known Member
    Rank:
     #137
    Points:
    83
    Posts:
    189
    Joined:
    Mar 26, 2019

    Mar 26, 2019
    189
    72
    83
    Programmer
    Raleigh, NC
    First, that error would tend to indicate that you haven't imported WebView. @GameTheory's example shows that (line 16)

    Also, your WebView doesn't have an ID, and you're trying to use an id to get it
    Code (Text):
    1. <WebView
    2. android:layout_width="match_parent"
    3. android:layout_height="match_parent"
    4. tools:layout_editor_absoluteX="8dp"
    5. tools:layout_editor_absoluteY="8dp" />
    If you want to use ID, you'll need to add one, like
    Code (Text):
    1. <WebView
    2. android:id="@+id/webview"
    3. android:layout_width="match_parent"
    4. android:layout_height="match_parent"
    5. tools:layout_editor_absoluteX="8dp"
    6. tools:layout_editor_absoluteY="8dp" />
    and be sure to use the id exactly as defined.

    Follow that link @GameTheory shared, it looks like it will give you a good start.
     
    Unforgiven and GameTheory like this.
  5. irex

    irex Lurker
    Thread Starter
    Rank:
    None
    Points:
    6
    Posts:
    2
    Joined:
    Jul 11, 2019

    Jul 11, 2019
    2
    1
    6
    Thanks my friends. i have resolved it. :)
     
    Unforgiven likes this.
  6. Unforgiven

    Unforgiven ...eschew obfuscation...
    Moderator
    Rank:
     #1
    Points:
    4,488
    Posts:
    38,220
    Joined:
    Jun 23, 2010

    Jun 23, 2010
    38,220
    47,348
    4,488
    Male
    Douglas, MA
    I'm glad your all set. :) Never a bad idea to hang a like on the posts of folks that helped you. ;)
     
    GameTheory, Greum and Brian Berry like this.

Share This Page

Loading...