Firebase realtime Database - java

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/

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?

Swipe to refresh webview fragment doesnt load url

I have a webview fragment in my MainActivity. I am trying to add Swipetoview inside it. But when I load the fragment it doesn't load the url.
My fragment:
// Inflate the layout for this fragment
View vDriver=inflater.inflate(R.layout.fragment_drivers, container, false);
mWebView = vDriver.findViewById(R.id.drivers_webview);
mWebView.loadUrl("https://ahmetbarpa-grand-prix.firebaseapp.com/drivers.html");
// Enable Javascript
//WebSettings webSettings = mWebView.getSettings();
//webSettings.setJavaScriptEnabled(true);
// Force links and redirects to open in the WebView instead of in a browser
mWebView.setWebViewClient(new WebViewClient());
swipeLayout = vDriver.findViewById(R.id.fragment_drivers);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mWebView.reload();
new Handler().postDelayed(new Runnable() {
#Override public void run() {
swipeLayout.setRefreshing(false);
}
}, 5000);
}
});
return vDriver;
My fragment layout:
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragment_drivers"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Drivers">
<WebView
android:id="#+id/drivers_webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</android.support.v4.widget.SwipeRefreshLayout>
I tried different things and this is the last code I tried. What am I doing wrong?
Thanks for your time in advance.
EDIT: MainActivity
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.squareup.picasso.Picasso;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, HomeFragment.OnFragmentNavListener,Drivers.OnDriverNavigationListener {
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private GoogleApiClient mGoogleApiClient;
private static final int RC_SIGN_IN = 0 ;
private SignInButton btn_signin;
private TextView nameText;
private TextView emailText;
private ImageView imgProfilePic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
HomeFragment fragment = new HomeFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View navHeader1 = navigationView.getHeaderView(0);
btn_signin = navHeader1.findViewById(R.id.signin_btn);
View navHeader3 = navigationView.getHeaderView(0);
nameText = navHeader3.findViewById(R.id.name);
View navHeader4 = navigationView.getHeaderView(0);
emailText = navHeader4.findViewById(R.id.email);
View navHeader5 = navigationView.getHeaderView(0);
imgProfilePic = navHeader5.findViewById(R.id.imgProfilePic);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
})
.addApi(Auth.GOOGLE_SIGN_IN_API, gso).build();
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null){
btn_signin.setVisibility(View.GONE);
if(user.getDisplayName() != null) {
nameText.setText(user.getDisplayName());
nameText.setVisibility(View.VISIBLE);
}
emailText.setText(user.getEmail());
emailText.setVisibility(View.VISIBLE);
imgProfilePic.setVisibility(View.VISIBLE);
Picasso.get().load(user.getPhotoUrl())
.into(imgProfilePic);
NavigationView navigationView2 = findViewById(R.id.nav_view);
Menu menu = navigationView2.getMenu();
MenuItem target = menu.findItem(R.id.nav_send);
target.setVisible(false);
MenuItem target2 = menu.findItem(R.id.nav_send2);
target2.setVisible(true);
}
else {
nameText.setVisibility(View.GONE);
emailText.setVisibility(View.GONE);
btn_signin.setVisibility(View.VISIBLE);
NavigationView navigationView2 = findViewById(R.id.nav_view);
Menu menu = navigationView2.getMenu();
MenuItem target = menu.findItem(R.id.nav_send);
target.setVisible(true);
MenuItem target2 = menu.findItem(R.id.nav_send2);
target2.setVisible(false);
imgProfilePic.setVisibility(View.GONE);
}
}
};
btn_signin.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
signIn();
}
});
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
private void signIn () {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
} else {
// deneme
}
}
}
#Override
public void onStop() {
super.onStop();
if(mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Authentication failed.", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(final MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
signIn();
} else if (id == R.id.nav_send2) {
FirebaseAuth.getInstance().signOut();
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
Toast.makeText(getApplicationContext(), "Çıkış yaptınız.", Toast.LENGTH_SHORT).show();
}
});
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onFragmentNav(int position) {
Fragment navFragment = null;
switch (position) {
case 0:
navFragment = new HomeFragment();
break;
case 1:
navFragment = new Drivers();
break;
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.fragment_container, navFragment)
.addToBackStack(null)
.commit();
}
#Override
public void onDriverNavigation(int asd) {
}
}
HomeFragment.java
package com.ahmetbarpa.grandprix;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class HomeFragment extends Fragment {
private OnFragmentNavListener mListener;
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v1 =inflater.inflate(R.layout.fragment_home, container, false);
Button profile= v1.findViewById(R.id.button1);
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
onButtonSelected(1);
}
});
Button education= v1.findViewById(R.id.button2);
education.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
Toast.makeText(getContext(),"Takımlar ve arabalar",Toast.LENGTH_SHORT).show();
}
});
Button health= v1.findViewById(R.id.button3);
health.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
Toast.makeText(getContext(),"Pistler",Toast.LENGTH_SHORT).show();
}
});
Button goals= v1.findViewById(R.id.button4);
goals.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
Toast.makeText(getContext(),"Sıralama",Toast.LENGTH_SHORT).show();
}
});
Button finance= v1.findViewById(R.id.button5);
finance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
Toast.makeText(getContext(),"Grand Prix Tarihi",Toast.LENGTH_SHORT).show();
}
});
Button comfort= v1.findViewById(R.id.button6);
comfort.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
Toast.makeText(getContext(),"GP kart oyunu",Toast.LENGTH_SHORT).show();
}
});
return v1;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonSelected(int position) {
if (mListener != null) {
mListener.onFragmentNav(position);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentNavListener) {
mListener = (OnFragmentNavListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentNav");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentNavListener {
void onFragmentNav(int position);
}
}
Instead of reload()
mWebView.loadUrl("https://ahmetbarpa-grand-prix.firebaseapp.com/drivers.html");
Try it..
If this is not the way you want, the second method is:
make a new class as:
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
then, Instead of this:
mWebView.setWebViewClient(new WebViewClient());
write this:
mWebView.setWebViewClient(new MyBrowser());
Hopefully your problem will be solved

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

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

Categories

Resources