Read & Store cookies created in WebView - java

I have a Android Application which is basically uses WebView for all interaction..
How can i access (read) Cookies which are created in WebView (if someone logs in) and than store them somewhere, maybe in SharedPreferences, so that later i can use them.
For example.. on quitting the application .. i can say "Thank Mr.XYZ,do u really want to quit"
Here is my code...
package com.example.hellowebview;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class HelloWebView extends Activity {
WebView webview;
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
CookieSyncManager.getInstance().sync();
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webview);
webview.setWebViewClient(new HelloWebViewClient(
));
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("http://www.mysite.com/mobile");
}
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Thank <<Name Cookie value from Webview >>>,do u really want to quit?")
.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();
}
}

To work with WebView cookies, you can use CookieManager which has some getter and setter methods for you.
http://developer.android.com/reference/android/webkit/CookieManager.html

Related

I want to show my externalurl link coming from api in webview in my application

My Code :
My Adapter
#Override
public void onBindViewHolder(#NonNull SliderAdapter.SliderHolder holder, int position) {
final HomePage.ContentList item = homePageList.get(position);
SliderHolder viewHolder = (SliderHolder) holder;
viewHolder.txt_category.setText(item.getCategoryName());
viewHolder.title_item_list_pager.setText(item.getTitle());
if (item.getImage() != null)
Glide.with(holder.itemView).load(item.getImage()).into(viewHolder.img);
Log.d("TEST103-2", "PV");
viewHolder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), NewsDetail.class);
intent.putExtra("newsdetail",homePageList.get(position).getExternalUrl());
v.getContext().startActivity(intent);
}
});
}
news detail class
package com.platin.android;
import android.os.Bundle;
import android.webkit.WebView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class NewsDetail extends AppCompatActivity {
WebView newsdetail;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_detail);
newsdetail = findViewById(R.id.newsdetail);
newsdetail.getSettings().setJavaScriptEnabled(true);
newsdetail.loadUrl(getIntent().getStringExtra("newsdetail"));
}
}
I want to show my externalurl link coming from api in webview in my application.
When I click for detail, it opens on google chrome. but I want it to show in application.
set setWebViewClient in your WebView also you can enable javaScript
webView.loadUrl(getIntent().getStringExtra(LINK));
webView.setWebViewClient(new MyWebViewClient());
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
and Clint is:
private class MyWebViewClient extends WebViewClient {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
}

Faster activity transition

I have created a basic Activity with a WebView. I have added a method in the WebView which loads an error.html page from the asset folder when the WebView receives a HTTP error. I wanted to hide the Share menu item when this error.html page was loaded and so, I moved this to a new Activity.
Now, what's happening is, when there's a connectivity error, the default connectivity error of Android loads first and then the Activity transition takes place. Thus, even though the transition is working fine, users can see the deault Android connectivity error page for a few milliseconds. Is there any way in which I can hide that error page completely as such the users can only see my custom error page.
Here's my MainActivity.java:
package com.ananya.brokenhearts;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebChromeClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
#SuppressWarnings("deprecation")
public class MainActivity extends AppCompatActivity
{
private WebView WebView;
private ProgressBar ProgressBar;
private LinearLayout LinearLayout;
private String currentURL;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView = findViewById(R.id.webView);
ProgressBar = findViewById(R.id.progressBar);
LinearLayout = findViewById(R.id.layout);
ProgressBar.setMax(100);
WebView.loadUrl("https://www.brokenhearts.ml/index.html");
WebView.getSettings().setJavaScriptEnabled(true);
WebView.getSettings().setUserAgentString("Broken Hearts/1.0");
WebView.setWebViewClient(new WebViewClient()
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
LinearLayout.setVisibility(View.VISIBLE);
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url)
{
LinearLayout.setVisibility(View.GONE);
super.onPageFinished(view, url);
currentURL = url;
}
#Override
public void onReceivedError(WebView webview, int i, String s, String s1)
{
Intent intent = new Intent(MainActivity.this, ErrorActivity.class);
startActivity(intent);
finish();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url2)
{
if (url2.contains("www.brokenhearts.ml"))
{
view.loadUrl(url2);
return false;
} else
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url2));
startActivity(intent);
return true;
}
}
});
WebView.setWebChromeClient(new WebChromeClient()
{
#Override
public void onProgressChanged(WebView view, int newProgress)
{
super.onProgressChanged(view, newProgress);
ProgressBar.setProgress(newProgress);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.backward:
onBackPressed();
break;
case R.id.forward:
onForwardPressed();
break;
case R.id.refresh:
WebView.reload();
break;
case R.id.share:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT,currentURL);
shareIntent.putExtra(Intent.EXTRA_SUBJECT,"Copied URL");
startActivity(Intent.createChooser(shareIntent,"Share URL"));
break;
case R.id.update:
Intent intent = new Intent(MainActivity.this, UpdateActivity.class);
startActivity(intent);
finish();
break;
case R.id.exit:
new AlertDialog.Builder(this,R.style.AlertDialog)
.setIcon(R.drawable.ic_error_black_24dp)
.setTitle("Are you sure you want to exit?")
.setMessage("Tapping 'Yes' will close the app. Tap 'No' to continue using the app")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
finish();
}
})
.setNegativeButton("No", null)
.show();
break;
}
return super.onOptionsItemSelected(item);
}
private void onForwardPressed()
{
if (WebView.canGoForward())
{
WebView.goForward();
} else
{
Toast.makeText(this, "Can't go further", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed ()
{
if (WebView.canGoBack())
{
WebView.goBack();
} else
{
new AlertDialog.Builder(this,R.style.AlertDialog)
.setIcon(R.drawable.ic_error_black_24dp)
.setTitle("Are you sure you want to exit?")
.setMessage("Tapping 'Yes' will close the app. Tap 'No' to continue using the app")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
}
Prior to this, I was directly loading the error.html page in the MainActivity itself when there was an error and thus, the default error page wasn't visible. But, I wanted to hide the Share button when error.html page was loaded. I didn't know how to do and I didn't get any response to that question where I had posted it. Thus, I thought of creating a seperate Activity to load the error.html which can let me hide the Share menu icon.
Also, I've tried to add the WebView.loadUrl("file:///android_asset/error.html"); in the same method before that intent hoping that it'll load before the Activity transition, however, that didn't help. I can still see the default Android connectivity error page.
Just to clarify, this is the default error page that I'm talking about: https://i.stack.imgur.com/bMMHh.png
and there's a custom one that I've made that I'm displaying now in the ErrorActivity.java.
What can I do about this?
Hide the webview when an error occured.
#Override
public void onReceivedError(WebView webview, int i, String s, String s1)
{
WebView.setVisibility(View.GONE);**hide the webview when an error occured**
Intent intent = new Intent(MainActivity.this, ErrorActivity.class);
startActivity(intent);
finish();
}
Regarding hiding the share menu icon, you could always use onPrepareOptionsMenu() to hide your share menu if there is any error flag.
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
menu.findItem(R.id.share).setVisible(!isPageError);
return true;
}
which would require you to have a isPageError boolean set to true in your
#Override
public void onReceivedError(WebView webview, int i, String s, String s1{
isPageError = true;
}

Android WebView button to activate Rewards Ad

So I found some code (How to call admob Interstitial ad from android webview JavascriptInterface) that allows the use of javascript on a webview page to activate within the app.
Now The issue I'm having is when the button is pressed, it toasts that the Ad hasn't loaded. Why isn't it loading the ad?
Here is the full code used in the MainActivity.java
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;
public class MainActivity extends AppCompatActivity {
public InterstitialAd mInterstitialAd;
WebView ProfOak;
String URL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AdView mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
URL = "http://url-here";
ProfOak = findViewById(R.id.ProfOak);
ProfOak.getSettings().setJavaScriptEnabled(true);
ProfOak.getSettings().setDomStorageEnabled(true);
ProfOak.getSettings().setUseWideViewPort(true);
ProfOak.setWebChromeClient(new WebChromeClient());
ProfOak.addJavascriptInterface(new WebAppInterface(this), "Android");
ProfOak.setVerticalScrollBarEnabled(false);
ProfOak.setWebChromeClient(new WebChromeClient());
ProfOak.setBackgroundColor(Color.TRANSPARENT);
ProfOak.loadUrl(URL);
ProfOak.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView ProfOak, int errorCode, String description, String failingUrl) {
try {
ProfOak.stopLoading();
} catch (Exception e) {
}
if (ProfOak.canGoBack()) {
ProfOak.goBack();
}
ProfOak.loadUrl("about:blank");
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Connection Required");
alertDialog.setMessage("This app requires an active Internet Connection to communicate with the Database.");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Try Again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(getIntent());
}
});
alertDialog.show();
super.onReceivedError(ProfOak, errorCode, description, failingUrl);
}
});
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/5224354917");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
mInterstitialAd.setAdListener(new AdListener(){
#Override
public void onAdLoaded(){
}
#Override
public void onAdClosed() {
// Load the next interstitial.
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
});
}
public void displayLoadedAd(){
runOnUiThread(new Runnable() {
public void run() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
else
Toast.makeText(getApplicationContext(), "Ad not loded", Toast.LENGTH_SHORT).show();
}
});
}
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
#JavascriptInterface
public void showAdFromJs(){
Toast.makeText(mContext, "Loading Ad", Toast.LENGTH_SHORT).show();
displayLoadedAd();
}
}
public class myWebClient extends WebViewClient
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
//Controlling navigation
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (ProfOak.canGoBack()) {
ProfOak.goBack();
}
else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
This is what i have in the webview URL
<input class="button" type="button" value="Ignore this" onclick="myFunction()">
<script type="text/javascript">
function myFunction() { Android.showAdFromJs(); };
</script>
It seems that you are using ad-unit id for rewarded video i.e
ca-app-pub-3940256099942544/5224354917.
For Interstitial the test ad unit id is
ca-app-pub-3940256099942544/1033173712. Refer to https://developers.google.com/admob/android/test-ads

Progress Bar only loads first time. On second page it does not show

Hello i have java code where progressBar Loads just for first time only.
second time when surfing inner pages it does not shows at all.
package ext.packagename.apk;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
WebView web;
ProgressBar progressBar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.activity_main);
OneSignal.startInit(this).init();
web = (WebView) findViewById(R.id.activity_main_webview);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
//open in webview
//web.setWebViewClient(new myWebClient());
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl("http://example1.com");
// opening in browser instead of WebView
web.setWebViewClient(new MyAppWebViewClient());
}
public class MyAppWebViewClient extends WebViewClient
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(Uri.parse(url).getHost().endsWith("exmaple1.com") || Uri.parse(url).getHost().endsWith("example2.com") || Uri.parse(url).getHost().endsWith("example3.com") ) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
}
}
// 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;
} else {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Alert")
.setMessage("exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
return super.onKeyDown(keyCode, event);
}
}
Progressbar is loading very fine at first time when main page loads. after that it disappear.
Use
progressBar.setVisibility(View.VISIBLE);
in onPageStarted method

#Project - WebView goBack() Return

After searching on stackoverflow and testing all codes, my Return goBack(); doesn't work.
I do a WebView,
- URL work
- ZOOM work
But I need to reload last page so this is my code I added :
MainActivity.java
package org.sbynight.app;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebChromeClient;
import android.view.KeyEvent;
public class MainActivity extends Activity {
WebView view;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView view = (WebView) this.findViewById(R.id.webView1);
//URL du website - DO NOT CHANGE IT
String url = "http://www.mydomaine.com/";
//loads the WebView completely zoomed out
view.getSettings().setSupportZoom(true);
view.getSettings().setBuiltInZoomControls(true);
//loads WebView Client
view.getSettings().setLoadWithOverviewMode(true);
view.setWebViewClient(new WebViewClient());
view.setWebChromeClient(new WebChromeClient());
view.getSettings().setAppCacheEnabled(false);
//loads URL
view.loadUrl(url);
}
//loads RETURN URL on lastpage
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && this.view.canGoBack()) {
this.view.goBack();
return true;
} else {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Fermer SByNight")
.setMessage("Etes-vous sur de vouloir quittez SByNight?")
.setPositiveButton("Oui", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("Non", null)
.show();
}
return true;
}
}
PS: I tested with goPressed(); doesn't work too!
SO you want to go back to the last page if there is one to go back to when the back key is pressed?
use the following:
#Override
public void onBackPressed() {
if(this.view.canGoBack())
{
this.view.goBack();
}
else {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Fermer SByNight")
.setMessage("Etes-vous sur de vouloir quittez SByNight?")
.setPositiveButton("Oui", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
finish();
}
})
.setNegativeButton("Non", null)
.show();
}
}
}
I haven't really checked the rest of your code. Just the invokable function.

Categories