Hide a menu item when a specific URL is loaded in WebView - java

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();
}
}

Related

My web browser app not working on all android device

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.

share current url in webview from toolbar menu

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() .

Capture the data provided by Intent

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?

Firebase realtime Database

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/

Android Share Menu

I have an app in which I have a WebView where I display some websites.
I want create a Share button in Menu.I've tried a lot of code.
What should I write here ?
private void action_shareMenuItem(){
//??????????????? What should I write here ?
}
MainActivity.java
package com.kefelon.goldplak;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.ShareActionProvider;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class MainActivity extends ActionBarActivity {
WebView webview;
private ShareActionProvider mShareActionProvider;
ProgressBar loadingProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setSupportZoom(true);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("http://www.goldplak.com");
webview.setWebViewClient(new WebViewClient() {
});
loadingProgressBar=(ProgressBar)findViewById(R.id.progressbar_Horizontal);
webview.setWebChromeClient(new WebChromeClient() {
// this will be called on page loading progress
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
loadingProgressBar.setProgress(newProgress);
//loadingTitle.setProgress(newProgress);
// hide the progress bar if the loading is complete
if (newProgress == 100) {
loadingProgressBar.setVisibility(View.GONE);
} else{
loadingProgressBar.setVisibility(View.VISIBLE);
}
}
});
}
#Override
public void onBackPressed()
{
if(webview.canGoBack()){
webview.goBack();
}else{
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Çıkış")
.setMessage("Uygulamadan çıkmak istediğinize emin misiniz?")
.setPositiveButton("Evet", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("Hayır", null)
.show();
}
}
#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) {
super.onOptionsItemSelected(item);
switch(item.getItemId()) {
case R.id.action_about:
action_aboutMenuItem();
break;
case R.id.action_share:
action_shareMenuItem();
break;
case R.id.action_settings:
action_settingsMenuItem();
break;
}
return true;
}
private void action_aboutMenuItem(){
new AlertDialog.Builder(this)
.setTitle("Hakkımızda")
.setMessage("Gold Plak olarak müzik sektörü ile ilgili müşteri odaklı kişisel ve kurumsal hizmet veren, dinamik, güler yüzlü, yaratıcı kadromuzla müşterilerimizin beklentilerini karşılamak için kesintisiz hizmet vermekteyiz.\n" +
"\n" +
"Bu şekilde müşterilerimizin plak ve dj ekipmanlarından yararlanmalarını sağlayarak taleplerini karşılayabilmek. Hedefimiz, yeni çıkan tüm ürünleri sunmak, maksimum düzeyde müşteri memnuniyetini sağlamak..")
.setNeutralButton("Tamam", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
private void action_shareMenuItem(){
//??????????????? What should I write here ?
}
private void action_settingsMenuItem(){
new AlertDialog.Builder(this)
.setTitle("Versiyon")
.setMessage("Gold Plak v1.1")
.setNeutralButton("Tamam", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
}
You may need to create an xml file inside res>menu directory of your project for a share menu,
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/share"
android:icon="#drawable/ic_action_share" // share button icon.
android:showAsAction="always"
android:title="#string/action_share">
</item>
</menu>
In your java file,
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.desc_xml, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.share) {
shareNews();
}
return super.onOptionsItemSelected(item);
}
and here is the share news method,
private void shareNews() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Put Data Here");
startActivity(Intent.createChooser(shareIntent,getString("How do you want to share")));
}
This question has already been answer but anyway, this is a working solution :
in your fragment/activity:
private ShareActionProvider mShareActionProvider;
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
getActivity().getMenuInflater().inflate(R.menu.deal_detail, menu);
// Locate MenuItem with ShareActionProviderr
MenuItem item = menu.findItem(R.id.action_share);
// Fetch and store ShareActionProvider
mShareActionProvider = (ShareActionProvider) item.getActionProvider();
mShareActionProvider.setShareIntent(getShareIntent());
}
// Create the share intent
private Intent getShareIntent() {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "yoursubject");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "yourtext);
return sharingIntent;
}

Categories

Resources