WebView controller Android - android

I am working on WebView. I don't know whether it's possible or not. I am opening an url inside of this view which is basically a login page. Now want to get the information whether user has successfully logged in or not. If yes then navigate to custom page (Android native) else keep on that page.
Thanks in advance.

We can achieve it via using this..
Create a function of javascript in the HTML page of Login Success/Failue HtmL page.
in this javascript function ,call your native Function by Using addJavascriptInterface:
package com.example.androidjsdemo;
import java.io.File;
import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
#JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
// Here you can Start WhatEver Activty launch///////
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webMy = (WebView) findViewById(R.id.webMy);
webMy.addJavascriptInterface(new WebAppInterface(this), "Android");
WebSettings setting = webMy.getSettings();
setting.setJavaScriptEnabled(true);
//File file = new File("andoid");
webMy.loadUrl("file:///android_asset/mine.html");
}
#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);
}
}
mine.html
<HTML>
<script>
function called()
{
// alert("hi");
Android.showToast("Hi Testing");
}
</script>
<Body>
Hi Sumit
<button onclick="called()">click me</button>
</Body>
</HTML>
activity_main.xml
<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="com.example.androidjsdemo.MainActivity" >
<WebView
android:id="#+id/webMy"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>

When user complete successful singing he should redirect to other web page with url that indicate the login was successful. it can look something like http://www.yourwebsite.com/islogin?yes.
than all you need to do is to check in your app what the login status by verify that the url contain islogin and that it set to yes and do whatever you want.
here a small sample to help you begin:
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(isUserLoggedIn(url)){
doWork();
return true;
} else {
return false;
}
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
}
public void onPageFinished(WebView view, String url) {
}
});

For Example below is your login URL which you load in webview for login
String loginURL = "http://www.myurl.com/login";
Two possibility, when user click on login button
1) Success
Navigate to Other page as per web code. So we need to check it and open our native application screen.
2) Fail
Same login page but display error message according to user input.
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains(loginURL)) {
// Login Fail
return false;
} else {
// Login Success
// Open Android Native screen
return true;
}
}
});

Related

How to show error message in my android webview app when no internet is connected to mobile

iam begineer in android development , i would like to diplay my custom/own error message instead of web page not avaialble message when my device is not connected to internet .
Here is my Main activity.java Source:
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.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ShareActionProvider;
public class MainActivity extends Activity {
private WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl("http://tech2dsk.blogspot.in/");
mWebView.setWebViewClient(new com.example.tech2dsk.tech2dsk.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);
}});
}
#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;
}
}
and here is myappwebviewclient.java source :
import android.content.Intent;
import android.net.Uri;
import android.webkit.WebView;
import android.webkit.WebViewClient;
/**
* Created by Karthik's on 3/5/2015.
*/
public class MyAppWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(Uri.parse(url).getHost().endsWith("tech2dsk.blogspot.in")) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
}
}
Plz help me in Fixing this.
Check this link on stackoverflow. They talk about to check and customize.
or if want to check if it was internet connection, you can use:
public static boolean checkAppConnectionStatus(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
return true;
}else{
return false;
}
}
So you can call anywhere:
if (!Utils.checkAppConnectionStatus(ActivityClass.this)){
Toast.makeText(ActivityClass.this,"No internet connection", Toast.LENGTH_SHORT).show();
Edit Answer
To create a layout to show when doesn't have internet you can do:
One way, is create a layout and set visible or invisible.
Other way is Inflate a new Layout.
Here I'll show to you how to create a layout and make visible or invisible.
First of all, create your basic layout to show when doesn't have internet:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/no_internet_connection"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:visibility="gone">
<TextView
android:id="#+id/no_internet_connection_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="center_horizontal"
android:text="Error: No internet connection!"
android:textSize="25sp"/>
</RelativeLayout>
note android:visibility="gone" set your layout invisible and it doesn't fill any space in your main layout.
Now include in your main activity <include layout="#layout/name_of_your_activity"/>
Create two methods in a class that you can access easily(I recommend to put together with your checkAppConnectionStatus(Context context)
public static void setLayoutInvisible(View viewName) {
if (viewName.getVisibility() == View.VISIBLE) {
viewName.setVisibility(View.GONE);
}
}
public static void setLayoutVisible(View viewName) {
if (viewName.getVisibility() == View.GONE ) {
viewName.setVisibility(View.VISIBLE);
}
}
So now just work with these methods in your main activiy, like:
private View mNoInternetConnection;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// Get layout that you had included in you main_activiy.xml
mNoInternetConnection = findViewById(R.id.no_internet_connection);
.
.
.
.
..
...
....
// Check the internet connect
if (!Utils.checkAppConnectionStatus(ActivityClass.this)){
// If do not have internet connection, set layout visible
Utils.setLayoutVisible(mNoInternetConnection);
}else{
// If have internet connection, set layout invisible
Utils.setLayoutInvisible(mNoInternetConnection);
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nf = cm.getActiveNetworkInfo();
if (nf != null && nf.isConnected()){
// do your stuff here
} else {
Toast.makeText(getApplicationContext(), "No Internet Connection", Toast.LENGTH_LONG).show();
}
}

How to remove white padding block from bottom of android webview app?

Im pretty new to android coding and I just created a webview app for my church. The apk was generated successfully but I still keep getting this annoying white space at the bottom of the screen.
To date I have removed all the android:padding references in the content_main.xml file but still am having no success.
Ive also searched on here to see if anyone else had the same issue but those threads only helped me get rid of the padding code and not this annoying white space at the bottom.
If you need me to post any code please let me know. Thanks in advance!
Here is a picture of what I am talking about with the white block at bottom
activity_main.xml------------------
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimaryDark"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
activity_main.xml------------------
content_main.xml-------------------
<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_vertical|center_horizontal">
</TextView>
<WebView
android:id="#+id/activity_main_webview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
content_main.xml------------------
MainActivity.java------------------
package org.communionchapelefca.ccsatx;
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://communionchapelefca.org/edy-home");
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();
}
}
MainActivity.java------------------
For the html code for the page we use Wordpress to host it. I've disabled all footers and such for what I think are the likely culprits. When opening the page (www.communionchapelefca.org/edy-home) it does not display the white block at the bottom.
Let me know if I need to post any other XML or java files. Thanks for your help.
Well all I did to fix it was hit the enter key about five times (to add space between the last text within the document). Then I added text to the bottom of my html document and then colored that text the same color as the background. Not a pretty fix but it worked.

How to load a webpage into webview in android app?

I am trying to make a simple android app that loads a webpage into a WebView.
package com.example.abhi.molinahealthcare;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class Molina_HealthCare extends ActionBarActivity {
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
WebView webview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_molina__health_care);
WebView myWebView = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new MyWebViewClient());
openURL();
}
private void openURL() {
webview.loadUrl("http://www.google.com");
webview.requestFocus();
}
#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_molina__health_care, 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);
}
}
ACTIVITY:-
<WebView
android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
I was not able to open it. I have the INTERNET permission declared in the AndroidManifest.xml
You are not initializing webview object of WebView which you are using in openURL method. do it by initializing webview instead of myWebView in onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_molina__health_care);
webview = (WebView) findViewById(R.id.webview);
...

How to get link in a webview and pass it on to the google doc viewer in android?

Okay so here is my main activity class.
In my WebView there are various links (mostly PDF). Now when a user clicks a link then what I'd like to do is i would like to load the URL in a variable then pass this variable to Google doc viewer code inside the WebView only to show the PDF contents.
package com.aeonindustries.skfgi;
import android.os.Bundle;
import android.webkit.WebView;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webView=(WebView)findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setVerticalScrollBarEnabled(false);
webView.loadUrl("file:///android_asset/index.html");
}
#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;
}
}
So how am going to do that?
Thanks in advance.
Ok, here some code:
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// insert here code to handle your goal
return true;
}
And somewhere in your Activity:
webView.setWebViewClient(new MyWebViewClient());

Trying to create menu item links on android

Can't get it to link to webpages. "Reset" and "About" should do. Using webview. Need for the links to open within the webview.
here's the MainActivity.java:
package com.test.apppackage;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class MainActivity extends Activity {
private WebView mWebview ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mWebview = new WebView(this);
mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript
final Activity activity = this;
mWebview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
}
});
mWebview .loadUrl("https://www.google.com");
setContentView(mWebview );
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch(id) {
case android.R.id.menu_reset:
mWebview .loadUrl("https://www.bbc.co.uk");
setContentView(mWebview );
break;
}
return super.onOptionsItemSelected(item);
}
public class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
here's the activity main.xml file
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/menu_reset"
android:title="#string/menu_reset"
android:showAsAction="ifRoom"
/>
<item
android:id="#+id/menu_about"
android:title="#string/menu_about"
android:showAsAction="never"
/></menu>
here's the strings.xml file
<?xml version="1.0" encoding="utf-8"?>
<string name="app_name">App name</string>
<string name="menu_reset">Reset</string>
<string name="menu_about">About app</string>
You are confusing android.R and R
Your items are called #+id/menu_reset, which is created in your com.test.apppackage.R.java file.
But you are later comparing to android.R.id.menu_reset, which would be in android.R.id, but doesn't exist.
You need to use only your R.java in this case. Use com.test.apppackage.R.id.menu_reset.
In some cases, you can use android values, but anyway mixing won't work.
edit
apparently, android.R.menu_reset doesn't even exist
more edit
R is actually R.id, of course

Categories

Resources