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" />
Related
I’ve create this Web View app, but something doesn’t work well. The page is reloaded over and over again. Could you help me to find why it is happens ?
I think this happens when it try to load the body content of the url.
package com.maunexus;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private WebView webView;
Activity activity;
private ProgressDialog progDailog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView=findViewById(R.id.webviewid);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("https://pari365.mg");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.super_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.menu_back:
onBackPressed();
break;
case R.id.menu_forward:
onForwardPressed();
break;
case R.id.menu_refresh:
webView.reload();
Toast.makeText(this, "Reloading... Please Wait!", Toast.LENGTH_SHORT).show();
break;
}
return super.onOptionsItemSelected(item);
}
private void onForwardPressed(){
if (webView.canGoForward()){
webView.goForward();
} else {
Toast.makeText(this, "Already there! ;)", Toast.LENGTH_SHORT).show();
}
}
public void onBackPressed(){
if (webView.canGoBack()){
webView.goBack();
}
}
}
There’s sometimes when the refresh is not happening, but the url does not load in full.
You need to add this line of code for accepting thirdparty cookies
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
CookieManager.getInstance().setAcceptThirdPartyCookies(webView,true);
}
It will work like a charm
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);
}
}
Hello coders out there!
I'm a beginner in android programming and my app won't show that there's no connection avaiable:
Shows: 404 HTML-screen |
Should-show: Message "no network connection"
Thank's for your help!
package net.schwarzis.htl_cloud;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
#SuppressLint("JavascriptInterface") public class MainActivity extends Activity {
/** Called when the activity is first created. */
private WebView browser = null;
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
// 1. Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// 2. Chain together various setter methods to set the dialog characteristics
builder.setMessage("Please connect to the internet...")
.setTitle("No network connection!");
// 3. Get the AlertDialog from create()
AlertDialog dialog = builder.create();
builder.show();
return true;
}
return false;
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
browser.loadUrl(url);
return true;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// connect to our browser so we can manipulate it
browser = (WebView) findViewById(R.id.mybrowser);
// get settings so we can config our WebView instance
WebSettings settings = browser.getSettings();
// JavaScript? Of course!
settings.setJavaScriptEnabled(true);
// clear cache
browser.clearCache(true);
final ProgressDialog pd=new ProgressDialog(this);
pd.setMessage("Lade...");
browser.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
pd.dismiss();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
pd.show();
browser.loadUrl(url);
return true;
}
});
// this is necessary for "alert()" to work
browser.setWebChromeClient(new WebChromeClient());
// add our custom functionality to the javascript environment
browser.addJavascriptInterface(new MyCoolJSHandler(), "Cloud");
// load a page to get things started
pd.show();
browser.loadUrl("http://cloud.schwarzis.net");
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
final ProgressDialog pd=new ProgressDialog(this);
pd.setMessage("Lade...");
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(browser.canGoBack() == true){
pd.show();
browser.goBack();
}else{
pd.show();
finish();
}
pd.dismiss();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
final class MyCoolJSHandler
{
// write to LogCat (Info)
public void Info(String str) {
Log.i("GoingNative",str);
}
// write to LogCat (Error)
public void Error(String str) {
Log.e("GoingNative",str);
}
// Kill the app
public void EndApp() {
finish();
}
}
}
Make sure you have added the "Internet" permission in the Manifest file.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Other than that, your code looks fine to me.
Hope it helps.
I'm using the following code to display a webview in my Android app.
package com.company.myapp;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class ArticlesActivity extends Activity {
/** Initialize the Google Analytics Tracker */
GoogleAnalyticsTracker tracker;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
getWindow().setFeatureInt(Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);
WebView webview = new WebView(this);
setContentView(webview);
setProgressBarVisibility(true);
webview.getSettings().setJavaScriptEnabled(true);
webview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
final Activity activity = this;
tracker = GoogleAnalyticsTracker.getInstance();
// Start the tracker, updating google every 20 seconds
tracker.start((String) getText(R.string.analyticsID), 20, this);
webview.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
activity.setProgress(progress * 100 );
}
});
webview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
});
webview.loadUrl("http://www.google.com");
}
#Override
public void onResume() {
tracker.trackPageView("ArticlesActivity");
super.onResume();
}
#Override
protected void onDestroy() {
super.onDestroy();
// Stop the tracker when it is no longer needed.
tracker.stop();
}
}
I would need to enable the back button to step back if history exists instead of just exiting the webview.
I've tried many different code examples such as this but can't get any to work. The app just shuts down when the back button is pressed.
Here's my code with the back button code but it just crashes the app when then back button is pressed:
package com.company.myapp;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class ArticlesActivity extends Activity {
WebView webview;
/** Initialize the Google Analytics Tracker */
GoogleAnalyticsTracker tracker;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
getWindow().setFeatureInt(Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);
WebView webview = new WebView(this);
setContentView(webview);
setProgressBarVisibility(true);
webview.getSettings().setJavaScriptEnabled(true);
webview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
final Activity activity = this;
tracker = GoogleAnalyticsTracker.getInstance();
// Start the tracker, updating google every 20 seconds
tracker.start((String) getText(R.string.analyticsID), 20, this);
webview.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
activity.setProgress(progress * 100 );
}
});
webview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
});
webview.loadUrl("http://www.google.com");
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
webview.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onResume() {
tracker.trackPageView("ArticlesActivity");
super.onResume();
}
#Override
protected void onDestroy() {
super.onDestroy();
// Stop the tracker when it is no longer needed.
tracker.stop();
}
}
Could someone help me with a solution?
Got it! Your problem in this line
WebView webview = new WebView(this);
Instead of using your member variable you are creating a variable inside function, and hence your member variable is null inside onKeyDown function.
Just replace it with
webview = new WebView(this);
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);