I am stuck at the last phase of my project. I am developing a android webview app in which user can share the current loaded page in there social apps. My share button is in the top at the toolbar. Currently I am able to share the loaded url through the share button but when I jump to a new page and press share button, still initial loaded url is shared. Here I need to share the current url from the toolbar menu.
Please help
Following is my code
package com.newsflashjharkhand.newflash;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.support.v7.widget.Toolbar;
import android.widget.Toast;
public class NewsFlash extends AppCompatActivity {
ProgressBar superProgressBar;
ImageView superImageView;
WebView superWebView;
String mUrl = "";
private String mTitle = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news_flash);
Toolbar toolbar = findViewById(R.id.toolbaar);
setSupportActionBar(toolbar);
superProgressBar = findViewById(R.id.newsprogressbar);
superImageView = findViewById(R.id.newsimage);
superWebView = findViewById(R.id.newswebview);
superProgressBar.setMax(100);
superWebView.loadUrl("https://www.google.com/");
superWebView.getSettings().setJavaScriptEnabled(true);
superWebView.setWebViewClient(new WebViewClient(){
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
mUrl = view.getUrl();
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
mTitle = view.getTitle();
getSupportActionBar().setTitle(mTitle);
super.onPageFinished(view, url);
}
});
superWebView.setWebChromeClient(new WebChromeClient(){
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
superProgressBar.setProgress(newProgress);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.btn_share:
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = mUrl;
sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share Using"));
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed(){
if (superWebView.canGoBack()) {
superWebView.goBack();
}
else{
final AlertDialog.Builder builder = new AlertDialog.Builder(NewsFlash.this);
builder.setMessage("Are you sure you want to exit?");
builder.setCancelable(true);
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
}
You should set WebViewClient with your webview like below:
WebView webview = new WebView(context);
webview.setWebViewClient(new WebViewClient()
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
Log.d("WebView", "your current url when webpage loading.." + url);
}
#Override
public void onPageFinished(WebView view, String url) {
Log.d("WebView", "your current url when webpage loading.. finish" + url);
super.onPageFinished(view, url);
}
#Override
public void onLoadResource(WebView view, String url) {
// TODO Auto-generated method stub
super.onLoadResource(view, url);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
System.out.println("when you click on any interlink on webview that time you got url :-" + url);
return super.shouldOverrideUrlLoading(view, url);
}
});
You can get current loaded url from shouldOverrideUrlLoading() .
Related
I just make a web browser and uploaded on play store but This is not working on my some of friends device (redmi note 8),(redmi 9). when he click on link a blank page will come same as when divice is not connected to internet. my app link - https://play.google.com/store/apps/details?id=com.zimax.forxbrowser .
my java code of first page-
package com.zimax.forxbrowser;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
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.inputmethod.EditorInfo;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
public class BrowserView extends AppCompatActivity {
private String url;
private ProgressBar progressBar;
SwipeRefreshLayout mySwipeRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_browser_view2);
final WebView webview = findViewById(R.id.webView);
final EditText urlET = findViewById(R.id.urlET);
final ImageView homeBtn = findViewById(R.id.homeIcon);
url = getIntent().getStringExtra("url");
final String urlData = url.substring(0, 4);
if(!urlData.contains("www")){
url = "www.google.com/search?q="+url;
}
urlET.setText(url);
webview.setWebViewClient(new WebViewClient(){
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
urlET.setText(url);
}
});
//Progress Bar
progressBar = (ProgressBar) findViewById(R.id.progressBar);
webview.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
if(progress<100 && progressBar.getVisibility() == progressBar.GONE){
progressBar.setVisibility(ProgressBar.VISIBLE);
}
if(progress == 100){
progressBar.setVisibility(ProgressBar.GONE);
}
}
});
//BackButton
webview.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
WebView webView = (WebView) v;
switch(keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()) {
webView.goBack();
return true;
}
break;
}
}
return false;
}
});
urlET.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(actionId == EditorInfo.IME_ACTION_SEARCH){
final String urlTxt = urlET.getText().toString();
if(!urlTxt.isEmpty()){
final String urlData = urlTxt.substring(0, 4);
if(!urlData.contains("www")){
url = "www.google.com/search?q="+url;
}
else {
url = urlTxt;
}
}
}
return false;
}
});
//download any thing
webview.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl(url);
homeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
}
I am expecting to work on all android similar to working on my device.
On this page: https://developer.android.com/training/app-links/deep-linking, in the
'Read data from incoming intents'
section, Google mentions:
Once the system starts your activity through an intent filter, you can
use data provided by the Intent to determine what you need to render.
Call the getData() and getAction() methods to retrieve the data and
action associated with the incoming Intent.
And that's exactly what I'm trying to do, but, I'm unable to get help.
In this activity of mine:
package com.application;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
#SuppressWarnings("unused")
public class SplashActivity3 extends Activity
{
Handler Handler;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash3);
Handler = new Handler();
Handler.postDelayed(new Runnable()
{
#Override
public void run()
{
Intent intent = new Intent(SplashActivity3.this, MainActivity.class);
startActivity(intent);
finish();
}
},
1500);
Intent appLinkIntent = getIntent();
String appLinkAction = appLinkIntent.getAction();
Uri appLinkData = appLinkIntent.getData();
}
}
I want to know (later tranfer it to another activity), the URL that was clicked on to open my app.
Basically, my app is using App Links (referred to as Deep Linking by some). So, in a case where a user 'A', sends user 'B' a link of a page on my website and B has my app installed, he/she will be able to open the link in my app instead of the browser.
As of now, B can open the link in my app, but, my app will always load the 'home page' (it's because I have coded my app to open the home page by default). I want to load the page that brought B in my app.
For a real life example, just like Facebook's app does. Suppose I share a link of a Facebook page or a profile to my friend. It's a standard HTTP link that's displayed in my web browser. Probably, I shared it with him on WhatsApp. He touches the link to open it. He has the official Facebook app installed on his phone. So, Android asks him if he wants to open the link in the Facebook app or in the browser. Now, when he chooses the browser, it's no problem at all. But, when he chooses the Facebook app, the app loads the profile or the page that exists on the link and not the home page of Facebook. That's what I want to achieve.
Please note, I'm talking about standard HTTP links here and not my app specific URIs.
UPDATE:
Here's something I tried now:
This is the same activity as above, I modified it like this:
package com.application;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
#SuppressWarnings("unused")
public class SplashActivity3 extends Activity
{
Handler Handler;
#Override
protected void onCreate(Bundle savedInstanceState)
{
final Intent appLinkIntent = getIntent();
final String appLinkAction = appLinkIntent.getAction();
Uri appLinkData = appLinkIntent.getData();
final Bundle bundle = new Bundle();
bundle.putString("web", appLinkAction);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash3);
Handler = new Handler();
Handler.postDelayed(new Runnable()
{
#Override
public void run()
{
Intent intent = new Intent(SplashActivity3.this, WebViewActivity.class);
intent.putExtras(bundle);
startActivity(intent);
finish();
}
},
1500);
}
}
And the activity in which I'm loading the URL:
package com.application;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.preference.PreferenceManager;
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 WebViewActivity extends AppCompatActivity
{
private WebView WebView;
private ProgressBar ProgressBar;
private LinearLayout LinearLayout;
private String currentURL;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState)
{
WebView wv = new WebView(this);
wv.loadUrl("file:///android_asset/eula.html");
wv.getSettings().setJavaScriptEnabled(true);
wv.getSettings().setUserAgentString("customUA");
wv.setWebViewClient(new WebViewClient()
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url3)
{
view.loadUrl(url3);
return true;
}
});
final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean agreed = sharedPreferences.getBoolean("agreed",false);
if(!agreed)
{
new AlertDialog.Builder(this, R.style.AlertDialog)
.setIcon(R.drawable.ic_remove_circle_black_24dp)
.setTitle(R.string.eula_title)
.setView(wv)
.setCancelable(false)
.setPositiveButton(R.string.accept, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("agreed", true);
editor.apply();
}
})
.setNegativeButton(R.string.decline, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
finish();
}
})
.show();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView = findViewById(R.id.webView5);
ProgressBar = findViewById(R.id.progressBar5);
LinearLayout = findViewById(R.id.layout5);
ProgressBar.setMax(100);
Bundle bundle = getIntent().getExtras();
String url = bundle.getString("web");
WebView.loadUrl(R.string.url);
WebView.getSettings().setJavaScriptEnabled(true);
WebView.getSettings().setUserAgentString("customUA");
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)
{
WebView.setVisibility(View.GONE);
Intent intent = new Intent(WebViewActivity.this, ErrorActivity.class);
startActivity(intent);
finish();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url2)
{
if (url2.contains("www.mydomain.tld"))
{
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)
{
super.onPrepareOptionsMenu(menu);
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#SuppressLint("SetJavaScriptEnabled")
#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);
startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.shareWith)));
break;
case R.id.update:
Intent intent = new Intent(WebViewActivity.this, UpdateActivity.class);
startActivity(intent);
finish();
break;
case R.id.about:
WebView wv2 = new WebView(this);
wv2.loadUrl("file:///android_asset/about.html");
wv2.getSettings().setJavaScriptEnabled(true);
wv2.getSettings().setUserAgentString("customUA");
wv2.setWebViewClient(new WebViewClient()
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url4)
{
view.loadUrl(url4);
return true;
}
});
new AlertDialog.Builder(this, R.style.AlertDialog)
.setIcon(R.drawable.ic_info_black_24dp)
.setTitle(R.string.info)
.setView(wv2)
.setPositiveButton(R.string.okay, null)
.show();
break;
case R.id.exit:
new AlertDialog.Builder(this,R.style.AlertDialog)
.setIcon(R.drawable.ic_error_black_24dp)
.setTitle(R.string.title)
.setMessage(R.string.message)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
finish();
}
})
.setNegativeButton(R.string.no, null)
.show();
break;
}
return super.onOptionsItemSelected(item);
}
private void onForwardPressed()
{
if (WebView.canGoForward())
{
WebView.goForward();
} else
{
Toast.makeText(this, R.string.noFurther, 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(R.string.title)
.setMessage(R.string.message)
.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
finish();
}
})
.setNegativeButton(R.string.no, null)
.show();
}
}
}
But, I'm getting Cannot resolve symbol url error at WebView.loadUrl(R.string.url);
What to do?
I have an activity with a basic WebView. In that, I have a menu item which launches a Share intent and allows users to share the URL that they were browsing at that point of time. I also have an error HTML page which is loaded when the WebView gets any HTTP error. So, basically, I want the Share menu item to be hidden (or at least share some other URL that I can set) when that error document is loaded.
Here's my MainActiviity.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.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;
}
public void onReceivedError(WebView webview, int i, String s, String s1)
{
WebView.loadUrl("file:///android_asset/error.html");
}
#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.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();
}
}
}
Regarding hiding the share menu icon, you could always use onPrepareOptionsMenu() to hide your share menu if there is an 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;
}
I solved it using moving my error page to another activity. This is my new MainActiviy.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)
{
WebView.loadUrl("file:///android_asset/error.html");
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();
}
}
}
and ErrorActivity.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.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;
#SuppressWarnings("deprecation")
public class ErrorActivity extends AppCompatActivity
{
private ProgressBar ProgressBar;
private LinearLayout LinearLayout;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_error);
android.webkit.WebView webView = findViewById(R.id.webView3);
ProgressBar = findViewById(R.id.progressBar3);
LinearLayout = findViewById(R.id.layout3);
ProgressBar.setMax(100);
webView.loadUrl("file:///android_asset/error.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);
}
});
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.menu3, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.refresh:
Intent intent = new Intent(ErrorActivity.this, MainActivity.class);
startActivity(intent);
finish();
break;
case R.id.update:
Intent intent2 = new Intent(ErrorActivity.this, UpdateActivity.class);
startActivity(intent2);
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);
}
#Override
public void onBackPressed ()
{
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();
}
}
I have a Question I'm new in android app development.
Here is my MainActivity.java
package com.koridevbrowser.app;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class MainActivity extends AppCompatActivity implement ValueEventListener{
private TextView mText;
private WebView mWebView;
ProgressBar progressBar;
private Toolbar toolbar;
private DatabaseReference database = FirebaseDatabase.getInstance().getReference();
private DatabaseReference mconf = database.child("version");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
mText = (TextView) findViewById(R.id.About);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
String userAgent = mWebView.getSettings().getUserAgentString();
mWebView.getSettings().setUserAgentString(userAgent);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl("http://www.kori-developer.com");
mWebView.setWebChromeClient(new WebChromeClient());
mWebView.setWebViewClient(new HelloWebViewClient());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
mWebView.loadUrl("http://kori-developer.com/");
return true;
case R.id.KoriFiles:
mWebView.loadUrl("http://kori-developer.com/forum/11-koridev-releases/");
return true;
case R.id.KoriRules:
mWebView.loadUrl("http://kori-developer.com/forum/26-foren-regeln/");
return true;
case R.id.KoriDonate:
mWebView.loadUrl("http://kori-developer.com/store/");
return true;
case R.id.KoriContact:
mWebView.loadUrl("http://kori-developer.com/contact/");
return true;
case R.id.KoriAbout:
Toast.makeText(MainActivity.this, "Version: 0.3b", Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue(String.class) !=null) {
String value = dataSnapshot.getKey();
if(value.equals("version")) {
String text = dataSnapshot.getValue(String.class);
mText.setText(text);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
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);
}
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 KoriDev?")
.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();
}
}
I will try to read the version from the realtime database here:
case R.id.KoriAbout:
Toast.makeText(MainActivity.this, "Version: 0.3b", Toast.LENGTH_LONG).show();
But I don't know how to setup this with the Realtime Database from Firebase.
A picture from my database :
its real time by default...I believe. if you change it in firebase, it'll change it on your app. but, for what you have, you have it hard coded into your toast.
You need to do something like this:
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("version");
// Read from the database
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
String value = dataSnapshot.getValue(String.class);
Log.d(TAG, "Value is: " + value);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
Checkout their doc here:
https://firebase.google.com/docs/database/android/start/
i am trying to make a app for android in eclipse. where i different fragments with webviews in it. but i want to show a progress bar when webview in loading but i could not getting it how to do it i checked many tutorials but failed to do so. let me most activity code here.
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.app.Fragment;
import android.annotation.SuppressLint;
//import android.graphics.Bitmap;
//import android.widget.ProgressBar;
//import android.app.ProgressDialog;
//import android.app.Activity;
#SuppressLint("SetJavaScriptEnabled")
public class AdminTab1 extends Fragment {
private WebView webView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
View rootView = inflater.inflate(R.layout.admintab1, container, false);
webView = (WebView) rootView.findViewById(R.id.webView1);
webView.setWebViewClient(new WebViewClient());
webView.setScrollbarFadingEnabled(false);
webView.setHorizontalScrollBarEnabled(false);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setUserAgentString("AndroidWebView");
webView.clearCache(true);
webView.loadUrl("http://ww.google.com");
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.mainmenu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item1:
webView.reload();
break;
case R.id.item2:
webView.goBack();
break;
default:
break;
}
return true;
}
}
You should try this
public class About27Fragment extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.about_27, container, false);
final WebView webView = (WebView) rootView.findViewById(R.id.webView_about27);
final ProgressDialog dialog = ProgressDialog.show(getActivity(), "", "Please wait, Loading Page...", true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon){
dialog.show();
}
#Override
public void onPageFinished(WebView view, String url){
dialog.dismiss();
String webUrl = webView.getUrl();
}
});
webView.loadUrl("https://www.google.com.mx");
return rootView;
}
}
WebViewClient has a lot of callback. You should subclass it and override onPageStarted to show and onPageFinished to dismiss it, for instance. Take a look to the doc, here
private class MyWebClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url,
// here show the dialog
}
public void onPageFinished(WebView view, String url) {
// here dismiss it
}
}
and in onCreateView use it like
webView.setWebViewClient(new MyWebClient());
oncreate
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.web_view);
web_view = (WebView) findViewById(R.id.web_view);
pd = new ProgressDialog(Activity.this);
pd.setMessage("Please wait Loading...");
pd.show();
web_view.setWebViewClient(new MyWebViewClient());
web_view.loadUrl("ur site name");
}
WebViewClient
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
if (!pd.isShowing()) {
pd.show();
}
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
System.out.println("on finish");
if (pd.isShowing()) {
pd.dismiss();
}
}
In this way you can implement Progress Dialog in webview.
Try this to get progress in percentage
myWebView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
// Activities and WebViews measure progress with different
// scales
//Updaate progress bar here with progress int
}
});