Capture the data provided by Intent - java

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?

Related

Removed AdMob from source code, but it's still showing an empty space at bottom in app Android Studio

I have removed AdMob from my source code of Android Studio, but still, it's showing an empty space at the bottom in the app.
It's always occupying an empty space at the bottom. I do not know how to make that bottom space disappear completely and show a normal preview of the app without ads.
How can I do this?
Here is the code.
Mainactivity.java
package com.dshgh.webview;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.dshgh.webview.Fragments.WebViewFragment;
public class MainActivity extends AppCompatActivity {
private BroadcastReceiver mRegistrationBroadcastReceiver;
boolean doubleBackToExitPressedOnce = false;
private FirebaseAnalytics mFirebaseAnalytics;
RelativeLayout rel_layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
//ButterKnife.bind(this);
rel_layout = (RelativeLayout)findViewById(R.id.rel_layout);
// Obtain the FirebaseAnalytics instance.
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
Bundle bundle = new Bundle();
WebViewFragment webViewFragment = new WebViewFragment();
bundle.putString("url", Config.homeUrl);
webViewFragment.setArguments(bundle);
loadFragment(webViewFragment, false, "webViewFragment");
try {
Intent intent = getIntent();
String message = intent.getStringExtra("message");
String url = intent.getStringExtra("url");
Log.d("notification Data", message + url);
if (url.length() > 0) {
bundle.putString("url", url);
webViewFragment.setArguments(bundle);
loadFragment(webViewFragment, false, "webViewFragment");
}
}
catch (Exception e) {
Log.d("error notification data", e.toString());
}
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
displayFirebaseRegId();
}
private void displayFirebaseRegId() {
SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
String regId = pref.getString("regId", null);
Log.e("FCM", "Firebase reg id: " + regId);
if (!TextUtils.isEmpty(regId)) {
//txtRegId.setText("Firebase Reg Id: " + regId);
}
else
Log.d("Firebase", "Firebase Reg Id is not received yet!");
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
super.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onBackPressed() {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("webViewFragment");
if(fragment != null && fragment instanceof WebViewFragment) {
if(((WebViewFragment) fragment).onBackPressed()) {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
// Toast.makeText(this, "Press back once more to exit", Toast.LENGTH_SHORT).show();
Snackbar snackbar = Snackbar
.make(rel_layout, "Press back once more to exit", Snackbar.LENGTH_LONG);
snackbar.setActionTextColor(Color.RED);
View snackbarView = snackbar.getView();
snackbarView.setBackgroundColor(Color.DKGRAY);
TextView textView = (TextView) snackbarView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
}
}
public void loadFragment(Fragment fragment, Boolean bool) {
loadFragment(fragment, bool, null);
}
public void loadFragment(Fragment fragment, Boolean bool, String TAG) {
showAds();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if(TAG == null) {
transaction.replace(R.id.frameLayout, fragment);
}else {
transaction.replace(R.id.frameLayout, fragment, TAG);
}
if (bool)
transaction.addToBackStack(null);
transaction.commit();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("webViewFragment");
if(fragment != null && fragment instanceof WebViewFragment) {
((WebViewFragment)fragment).onActivityResult(requestCode, resultCode, intent);
}
super.onActivityResult(requestCode, resultCode, intent);
}
public void hideAds() {
}
public void showAds() {
}
}
I think you forgot to remove <com.google.android.gms.ads.AdView......./> from your XML page.
Please remove it.

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

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

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/

How to open URL in an Activity (instead of a new browser)?

Can anyone please help me check my code to see why it cannot be
launched in the app itself but directs me to a browser? ): Thanks!!
MAIN ACTIVITY.JAVA
package com.intelligami.androidwebviewapp;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ShareActionProvider;
public class MainActivity extends Activity {
private WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl("http://intelligami.com/submitqn");
mWebView.setWebViewClient(new com.intelligami.androidwebviewapp.MyAppWebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
//hide loading image
findViewById(R.id.progressBar1).setVisibility(View.GONE);
//show webview
findViewById(R.id.activity_main_webview).setVisibility(View.VISIBLE);
}});
}
private class MyWebViewClient extends MyAppWebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
private ShareActionProvider mShareActionProvider;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
/** Inflating the current activity's menu with res/menu/items.xml */
getMenuInflater().inflate(R.menu.menu_main, menu);
/** Getting the actionprovider associated with the menu item whose id is share */
mShareActionProvider = (ShareActionProvider) menu.findItem(R.id.share).getActionProvider();
/** Setting a share intent */
mShareActionProvider.setShareIntent(getDefaultShareIntent());
return super.onCreateOptionsMenu(menu);
}
/** Returns a share intent */
private Intent getDefaultShareIntent(){
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "Convert Website to Android Application");
intent.putExtra(Intent.EXTRA_TEXT," Vist www.AndroidWebViewApp.com if you Want to Convert your Website or Blog to Android Application");
return intent;
}
}
MY APP VIEW CLIENT. JAVA
package com.intelligami.androidwebviewapp;
import android.content.Intent;
import android.net.Uri;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MyAppWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(Uri.parse(url).getHost().endsWith("intelligami.com/submitqn")) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
}
}
Where is the error? :D
It keeps opening up in the browser.
In the following line:
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
you're asking Android to open a URL using the intent constant ACTION_VIEW - so it defaults to the external browser.
Here a full example (taken from here) that shows how to open the url using a WebViewClient:
package com.paresh.webviewclientdemo;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
/*
* Demo of creating an application to open any URL inside the application and clicking on any link from that URl
should not open Native browser but that URL should open in the same screen.
*/
public class WebViewClientDemoActivity extends Activity {
/** Called when the activity is first created. */
WebView web;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
web = (WebView) findViewById(R.id.webview01);
web.setWebViewClient(new myWebClient());
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl("http://www.google.com");
}
public class myWebClient 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 view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
}
// To handle "Back" key press event for WebView to go back to previous screen.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) {
web.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}

Categories

Resources