webview in android - java

i was working on webview following the link http://developer.android.com/resources/tutorials/views/hello-webview.html and it is working fine but the problem is i cant view the whole page i mean that it is horizontally not scrollable.
how can i view the whole page by scrolling both horizontally and vertically?
Activity
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class HelloWebView extends Activity {
/** Called when the activity is first created. */
WebView mWebView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("http://www.google.com");
mWebView.setWebViewClient(new HelloWebViewClient());
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="horizontal|vertical"
/>

If you have the webview defined in your xml, you can do the following:
android:scrollbars="horizontal|vertical"

You can do the following:
mWebView.setVerticalScrollBarEnabled(true);
mWebView.setHorizontalScrollBarEnabled(true);

Related

'Attempt to invoke virtual method 'android.webkit.WebSettings android.webkit.WebView.getSettings()' on a null object reference' on activity open

I want to open a atctivity, that includes a browser, when i press the button 5 times.
Here is my MainActivity.java:
package de.gamingwave.browser;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
private static int druecken = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setDruecken(getDruecken() + 1);
System.out.println(getDruecken());
if (druecken == 5){
Intent activity2Intent = new Intent(getApplicationContext(), browser.class);
startActivity(activity2Intent);
}
}
});
}
public static int getDruecken() {
return druecken;
}
public static void setDruecken(int druecken) {
MainActivity.druecken = druecken;
}
}
Here is the browser.java:
package de.gamingwave.browser;
import android.annotation.SuppressLint;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
public class browser extends AppCompatActivity {
// Declare View object references
EditText etUrl;
Button btnGo;
WebView webView;
ProgressBar progressBar;
ProgressDialog progressDialog;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
// Instantiate View objects
etUrl = findViewById(R.id.etUrl);
btnGo = findViewById(R.id.btnGo);
webView = findViewById(R.id.webview);
progressBar = findViewById(R.id.progressBar);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading Please Wait...");
// Create a WebSettings object
// Set Zoom Controls
webView.getSettings().setBuiltInZoomControls(true);
// JavaScript is by default turned off in WebView. To enable JavaScript we can call
// setJavaScriptEnabled() method on webSettings object and pass true as parameter.
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAllowContentAccess(true);
webView.getSettings().setAllowFileAccess(true);
/*
Now, when the user clicks a link from a web page in your WebView, the
default behavior for Android is to launch an application that handles
URLs. Typically, system's default web browser opens and loads the
destination URL. However, you can override this behavior for your
WebView, so that links open within your WebView and hence within the app.
You can then allow the user to navigate backward and forward through their web page history
that's maintained by your WebView. To accomplish this, we need to create a subclass of
WebViewClient and override it's shouldOverrideUrlLoading() method. Let's do that.
*/
webView.setWebViewClient(new MyWebViewClient());
if (!checkConnection()) {
showDialog();
}
// Attach OnClickListener with the Button
btnGo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Get the text from EditText
String url = etUrl.getText().toString().trim();
// If entered url doesn't start "http://" or "https://" we need to append it
// before the url.
if (!url.startsWith("http://") || !url.startsWith("https://")) {
url = "https://" + url;
}
// To load the webView with the url we need to call loadUrl() method
// of the WebView class, passing url as parameter.
webView.loadUrl(url);
}
});
webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
setTitle("Loading...");
progressBar.setProgress(newProgress);
progressDialog.show();
if (newProgress == 100) {
setTitle(webView.getTitle());
progressDialog.dismiss();
}
super.onProgressChanged(view, newProgress);
}
});
webView.setDownloadListener(new MyDownLoadListener());
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// When you return false you're telling Android not to override; let WebView
// load the page
return false;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
webView.setVisibility(View.GONE);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
webView.setVisibility(View.VISIBLE);
}
}
/* Run the application. (pause)
Let's specify a url in the EditText field and press the ENTER button to launch the website.
But before that please make sure that you are connected to the internet.
The site looks good in WebView.
As you can see, the url loads properly in WebView but if we click the Back button,
the app gets closed even though we’ve navigated through a few pages within the WebView itself.
Let's see how we can handle navigation in WebView with Back Button.
To go through the browsing history on pressing the Back button we need to override
onBackPressed() method as follows.
*/
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to Exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
// The WebView maintains a browsing history just like a normal browser.
// If there is no history then it will result in the default behavior of the Back button i.e.
// closing the app.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navPrev:
onBackPressed();
break;
case R.id.navNext:
if (webView.canGoForward()) {
webView.goForward();
}
break;
case R.id.navReload:
checkConnection();
}
return super.onOptionsItemSelected(item);
}
private boolean checkConnection() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
if (capabilities != null) {
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
return true;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
return true;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) {
return true;
}
}
} else {
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
return true;
}
}
}
return false;
}
private void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Connect to WIFI or Exit")
.setCancelable(false)
.setPositiveButton("Connect to WIFI", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
}
})
.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public class MyDownLoadListener implements DownloadListener {
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
if (url != null) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
}
}
}
Here is the activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:text="Senden"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="#+id/button"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" app:backgroundTint="#1BB500"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text="Name"
android:ems="10"
android:id="#+id/editTextTextPersonName" tools:layout_editor_absoluteY="127dp"
tools:layout_editor_absoluteX="105dp"/>
</androidx.constraintlayout.widget.ConstraintLayout>
And here is the activity_browser.java:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
tools:context=".browser"
android:padding="10dp">
<!-- Lets design the layout -->
<!-- Create a horizontal LinearLayout to display the EditText and the ENTER Button. -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/etUrl"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="9"
android:ems="10"
android:maxLines="1"
android:hint="Enter Url"
android:inputType="textPersonName"
android:minHeight="52dp"
android:drawableLeft="#drawable/ic_baseline_search_24"/>
<Button
android:id="#+id/btnGo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="#0070c7"
android:textColor="#android:color/white"
android:layout_weight="1"
android:text="Go" />
</LinearLayout>
<!-- Add a RelativeLayout to contain a ProgressBar and a WebView
that fills the rest of the screen. -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="gone"/>
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/webview"
android:visibility="gone"/>
</RelativeLayout>
</LinearLayout>
What's wrong with this code?
Thank's for helping.
The button should open a new browser activity.

Applying WebView on setOnClickListener

Currently I'm a beginner in android. Right now I'm trying to make my ListView item open a layout which contain WebView when any item is clicked. Each item will direct to a different page. But I'm not sure how can I achieve this. This is my code.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.activity_listview, null);
}
FeedItem p = getItem(position);
if (p != null) {
TextView tt1 = (TextView) v.findViewById(R.id.title_text);
TextView tt2 = (TextView) v.findViewById(R.id.date_text);
if (tt1 != null) {
tt1.setText(p.getTitle());
}
if (tt2 != null) {
tt2.setText(p.getPubDate());
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
FeedItem q = getItem(position);
if(q.getLink() != null){
//Toast.makeText(getContext(), "" + q.getLink(), Toast.LENGTH_SHORT).show();
}
}
});
}
return v;
}
Your Question is totally opinion based. both can be used as per app's requirement.
Default Browser
it is easy to use just 4 or file lines and you are good to go. but it gets user out of application.
How to use it.
Intent intent= new Intent(Intent.ACTION_VIEW,Uri.parse(YOUR_URL));
startActivity(intent);
WebView
can be used as a part of application. you need to create on activity containing webview and call intent from where you want to open webview.
Example
Layout
<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"
tools:context=".MainActivity">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/webView" />
</RelativeLayout>
java
public class WebViewActivity extends Activity {
private WebView wv1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wv1=(WebView)findViewById(R.id.webView);
wv1.getSettings().setLoadsImagesAutomatically(true);
wv1.getSettings().setJavaScriptEnabled(true);
wv1.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wv1.loadUrl(your_url);
}
}
and just call this from where you want to open Webview.
Intent intent= new Intent(MainActivity.this,WebViewActivity.class);
startActivity(intent);
refer this link.
I hope it is clear.
You can modify little bit according to your requirement and need to put your import your package.
if(q.getLink() != null){
Intent intent = new Intent(getActivity(), BrowserActivity.class);
intent.putExtra("url", q.getLink());
startActivity(intent);
}
BrowserActivity
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.Toast;
import com.yourproject.R;
public class BrowserActivity extends FragmentActivity {
WebView webview;
public BrowserActivity() {
// Required empty public constructor
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.comment_detail);
String url = getIntent().getStringExtra("url");
Log.d("URL ", url);
webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setBuiltInZoomControls(true);
webview.getSettings().setSupportZoom(true);
webview.loadUrl(url);
webview.setWebViewClient(new WebViewClient() {
public void onPageStarted(WebView view, String url) {
}
public void onPageFinished(WebView view, String url) {
// do your stuff here
MyApplication.hideTransparentProgressDialog();
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(CommentDetails.this, description, Toast.LENGTH_SHORT).show();
}
});
}
}
comment_detail.xml
<include
android:id="#+id/headerTV"
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
layout="#layout/title_bar_layout_job_info" />
<WebView
android:layout_below="#+id/headerTV"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/webview">
</WebView>
To open browser use intent:
String url = "https://www.google.com/";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
and for webview :
XML Code:
<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/webView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
JAVA Code:
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
public class WebViewActivity extends Activity {
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.google.com");
}
}
you can also load your own html file on WebView.

How to open URL in an Activity (instead of a new browser)?

Can anyone please help me check my code to see why it cannot be
launched in the app itself but directs me to a browser? ): Thanks!!
MAIN ACTIVITY.JAVA
package com.intelligami.androidwebviewapp;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ShareActionProvider;
public class MainActivity extends Activity {
private WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl("http://intelligami.com/submitqn");
mWebView.setWebViewClient(new com.intelligami.androidwebviewapp.MyAppWebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
//hide loading image
findViewById(R.id.progressBar1).setVisibility(View.GONE);
//show webview
findViewById(R.id.activity_main_webview).setVisibility(View.VISIBLE);
}});
}
private class MyWebViewClient extends MyAppWebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
private ShareActionProvider mShareActionProvider;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
/** Inflating the current activity's menu with res/menu/items.xml */
getMenuInflater().inflate(R.menu.menu_main, menu);
/** Getting the actionprovider associated with the menu item whose id is share */
mShareActionProvider = (ShareActionProvider) menu.findItem(R.id.share).getActionProvider();
/** Setting a share intent */
mShareActionProvider.setShareIntent(getDefaultShareIntent());
return super.onCreateOptionsMenu(menu);
}
/** Returns a share intent */
private Intent getDefaultShareIntent(){
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "Convert Website to Android Application");
intent.putExtra(Intent.EXTRA_TEXT," Vist www.AndroidWebViewApp.com if you Want to Convert your Website or Blog to Android Application");
return intent;
}
}
MY APP VIEW CLIENT. JAVA
package com.intelligami.androidwebviewapp;
import android.content.Intent;
import android.net.Uri;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MyAppWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(Uri.parse(url).getHost().endsWith("intelligami.com/submitqn")) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
}
}
Where is the error? :D
It keeps opening up in the browser.
In the following line:
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
you're asking Android to open a URL using the intent constant ACTION_VIEW - so it defaults to the external browser.
Here a full example (taken from here) that shows how to open the url using a WebViewClient:
package com.paresh.webviewclientdemo;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
/*
* Demo of creating an application to open any URL inside the application and clicking on any link from that URl
should not open Native browser but that URL should open in the same screen.
*/
public class WebViewClientDemoActivity extends Activity {
/** Called when the activity is first created. */
WebView web;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
web = (WebView) findViewById(R.id.webview01);
web.setWebViewClient(new myWebClient());
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl("http://www.google.com");
}
public class myWebClient 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 view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
}
// To handle "Back" key press event for WebView to go back to previous screen.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) {
web.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}

How to create an android app that opens a website

I'm using eclipse. Just started with android web apps :) !
I want to create a web application that whenever it's open, it loads a website.
Nothing visual, no buttons.
This is the main blank code I have:
package com.example.yellowtest;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here the sample code for web application
activity_layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<WebView
android:id="#+id/google"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</RelativeLayout>
Main class
public class MainActivity extends Activity {
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
webView = (WebView) findViewById(R.id.google);
startWebView("https://www.google.com/");
}
#SuppressLint("SetJavaScriptEnabled")
private void startWebView(String url) {
webView.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog;
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onLoadResource (WebView view, String url) {
if (progressDialog == null) {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
}
public void onPageFinished(WebView view, String url) {
try {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
} catch(Exception exception) {
exception.printStackTrace();
}
}
});
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(false);
webView.getSettings().setBuiltInZoomControls(true);
webView.loadUrl(url);
}
#Override
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
}
use this permission in your AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl("http://google.com");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Have alook at PhoneGap/Cordova, webaps with API
http://cordova.apache.org/
Use this below code. It contains webview client which is safest one.
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
/*
* Demo of creating an application to open any URL inside the application and clicking on any link from that URl
should not open Native browser but that URL should open in the same screen.
*/
public class WebViewClientDemoActivity extends Activity {
/** Called when the activity is first created. */
WebView web;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
web = (WebView) findViewById(R.id.webview01);
web.setWebViewClient(new myWebClient());
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl("http://www.google.com");
}
public class myWebClient 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 view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
}
// To handle "Back" key press event for WebView to go back to previous screen.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) {
web.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}

Viewing website in a webview brings up webpage not available

Hey all first Android project here...
I found this code for loading a website inside a webview:
package com.example.mainactivity;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
private WebView mWebView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
mWebView = new WebView(this);
mWebView.loadUrl("http://www.google.com");
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
this.setContentView(mWebView);
}
#Override
public boolean onKeyDown(final int keyCode, final KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
However, it tells me (when i am debugging it via Eclipse and my phone via USB) that:
webpage not available
What am i missing here? I know my phone has internet connection.
Ah.... i didn't have the permissions in my manifest file....
<uses-permission android:name="android.permission.INTERNET" />

Categories

Resources