How to refresh current Activity 1 time after load? My code refresh the activity, but in Loop.
This site have some examples, but most is after click button. Isn't my case.
My code is:
finish();startActivity(getIntent());
just do this way.
startActivity(getIntent());
finish();
public class MainActivity extends Activity {
String url;
//initializing WebView
private WebView mwebView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Div1().execute();
String tag = (String) getIntent().getSerializableExtra("tag");
Intent intent = getIntent();
url = "https://xxxxxxxx.com/profile/"+tag+"";
//WebView
mwebView = (WebView) findViewById(R.id.myWebView);
WebSettings webSettings = mwebView.getSettings();
webSettings.setJavaScriptEnabled(true);
//improve webView performance
mwebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
//mwebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
mwebView.getSettings().setAppCacheEnabled(false);
mwebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webSettings.setDomStorageEnabled(true);
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
webSettings.setUseWideViewPort(true);
webSettings.setSavePassword(true);
webSettings.setSaveFormData(true);
webSettings.setEnableSmoothTransition(true);
mwebView.loadUrl("https://xxxxxxxx.com/profile/"+tag+"");
//force links open in webview only
mwebView.setWebViewClient(new MyWebviewClient());
}
private class MyWebviewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if (Uri.parse(url).getHost().equals("xxxxxxxx.com/profile/\"+tag+\"")){
return false;
}
else {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}}
// Div1 AsyncTask
private class Div1 extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
return null;
}
#Override
protected void onPostExecute(String result) {
mwebView.loadUrl("javascript:(function(){"+
"l=document.getElementsByTagName('BUTTON')[1];"+
"e=document.createEvent('MouseEvent');"+
"e.initEvent('click',true, true);"+
"l.dispatchEvent(e);"+
"})()");
}
}
}
Button ok = (Button) findViewById(R.id.btnOK2);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(getIntent());
finish();
}
});
This is sample code I wrote:
public class MainActivity extends AppCompatActivity {
static boolean isInit = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(isInit) {
isInit = false;
startActivity(new Intent(this, MainActivity.class));
finish();
Log.d("Restart", "asdasda");
}
}
}
One thing I need to say is that if you start this activity from another activity, in every call you need set the isInit variable true like this:
MainActivity.isInit = true;
startActivity(new Intent(this, MainActivity.class));
Using "getIntent()" instead of "new Intent(this, MainActivity.class)" cause closing the application after logging "Restart" text.
I don't know whether it is what you want (I think this can not be any solution of any problem). I still think better is reload only views.
Related
Need some advice. I want to be able to redirect the user to a specific link in WebView. Example: we go to the first link and if it directs us to "google.com" then we will have to direct the user to "http://test.com". I made an implementation, put a redirect in shouldOverrideUrlLoading, however, after SplashScreen-loading image done its work, a white background appears and that's it. At the same time, if you remove the code for redirection, then after performing its work, the SplashScreen - loading image, the first link opens and the page from the Internet is displayed correctly. How do I redirect to other pages after opening the first one?
public class MainActivity extends AppCompatActivity {
private WebView webView;
private final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.loadUrl("http://test/start");
new TaskForRedirecting().execute();
}
public class TaskForRedirecting extends AsyncTask<Boolean, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(Boolean... booleans) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Log.d(TAG, "Start loading here");
WebViewClient webViewClient = new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains("google.com")) {
view.loadUrl("http://test1.com");
return false;
} else if (url.contains("yahoo.com")) {
view.loadUrl("http://test2.com");
return false;
} else {
}
return true;
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if (request.getUrl().toString() == "google.com") {
view.loadUrl("http://test1.com");
view.loadUrl(request.getUrl().toString());
return false;
} else if (request.getUrl().toString() == "yahoo.com") {
view.loadUrl("http://test2.com");
return false;
}
return true;
}
};
webView.setWebViewClient(webViewClient);
Log.d(TAG, "Do in background: APP is Working!!!");
}
});
return false;
}
#Override
protected void onPostExecute(Boolean success) {
success = false;
if (success) {
Toast toast = Toast.makeText(MainActivity.this, "App is under maintenance!", Toast.LENGTH_SHORT);
toast.show();
} else {
Toast toast = Toast.makeText(MainActivity.this, "Let's start to work!", Toast.LENGTH_SHORT);
toast.show();
}
Log.d(TAG, "upload - final! ");
}
}
}
public class SplashScreenActivity extends AppCompatActivity {
long Delay = 6000;
private final String TAG = "SplashScreenActivity";
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_splash_screen);
new SplashScreen().execute();
}
public class SplashScreen extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void...voids) {
Timer RunSplash = new Timer();
TimerTask ShowSplash = new TimerTask() {
#Override
public void run() {
finish();
Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class);
startActivity(intent);
}
};
RunSplash.schedule(ShowSplash, Delay);
Log.d(TAG, "ShowSplash - final! ");
return null;
}
}
}
Your implementation needs to change a bit, we don't need to set the webview client inside an AsyncTask, instead, we can set it directly but it should be set before we call loadurl.
I have removed the asynctask, and set the client in onCreate method before calling loadUrl.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
WebViewClient webViewClient = new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains("google.com")) {
view.loadUrl("http://test1.com");
return true;
} else if (url.contains("yahoo.com")) {
view.loadUrl("http://test2.com");
return true;
}
return false;
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if (request.getUrl().toString() == "google.com") {
view.loadUrl("http://test1.com");
return true;
} else if (request.getUrl().toString() == "yahoo.com") {
view.loadUrl("http://test2.com");
return true;
}
return false;
}
};
webView.setWebViewClient(webViewClient);
webView.loadUrl("http://test/start");
}
UPDATE
Please check out the shouldOverrideUrlLoading Doc, You should return true when you want to cancel the current load, so when you want to load a different URL, then return true else return false to continue the current load. Returning false means the URL which is being loaded to the webview will continue, your custom URL will not be loaded.
I am able to load the website properly in the app but it has a function which redirects users to whatsapp. The api works fine on mobile browser and on PC/laptop. But in the android app it loads for a second and then says webpage unavailable. What am I missing?
Image 1 stays only for a second.
After 1 second loading time :
Main Java Code:
public class MainActivity extends AppCompatActivity {
private WebView mywebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mywebView=(WebView) findViewById(R.id.webview);
mywebView.loadUrl("https://zzzz/");
WebSettings webSettings=mywebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mywebView.setWebViewClient(new WebViewClient());
}
#Override
public void onBackPressed(){
if(mywebView.canGoBack()) {
mywebView.goBack();
}
else{
super.onBackPressed();
}
}
}
Override this shouldOverrideUrlLoading and do this in it
Code
// Force links and redirects to open in the WebView instead of in a browser
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView wv, String url) {
if(url.startsWith("tel:") || url.startsWith("whatsapp:")) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
return true;
}
return false;
}
});
Your code should be like this
public class MainActivity extends AppCompatActivity {
private WebView mywebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mywebView=(WebView) findViewById(R.id.webview);
mywebView.loadUrl("https://naturesexpress.in/");
WebSettings webSettings=mywebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView wv, String url) {
if(url.startsWith("tel:") || url.startsWith("whatsapp:")) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
return true;
}
return false;
}
});
}
I have two ImageButton with two different url. When I click the image, it returns an white screen.I don't know what is the problem. Any edit or suggestions are welcome.
Thanks!
main activity
public class main extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
ImageButton amazon = (ImageButton)findViewById(R.id.imagebutton1);
ImageButton flipkart = (ImageButton)findViewById(R.id.imagebutton2);
amazon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(),"Amazon",Toast.LENGTH_LONG).show();// display the toast on home button click
Intent intent = new Intent(main.this, MainActivity.class);
intent.setData(Uri.parse("http://www.amazon.com"));
WebView webview = new WebView(main.this);
setContentView(webview);
startActivity(intent);
}
});
flipkart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(),"Flipkart",Toast.LENGTH_LONG).show();// display the toast on you tube button click
Intent intent = new Intent(main.this, MainActivity.class);
intent.setData(Uri.parse("http://www.flipkart.in"));
startActivity(intent);
}
});
}
my webview activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView htmlWebView = (WebView) findViewById(R.id.webView);
htmlWebView.setWebViewClient(new CustomWebViewClient());
WebSettings webSetting = htmlWebView.getSettings();
webSetting.setJavaScriptEnabled(true);
webSetting.setDisplayZoomControls(true);
htmlWebView.loadUrl("");
}
class CustomWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
Do you want to load Url in your app or want to open via External Browser. anaway I'm given the snipped code for the open the url in webview as given below in your application as:
WebView mynews;
ProgressBar pb;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newsreadscreen);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
pb= (ProgressBar) findViewById(R.id.progress_bar);
mynews= (WebView) findViewById(R.id.mynews);
mynews.getSettings().setJavaScriptEnabled(true);
mynews.getSettings().setDefaultFontSize(17);
mynews.getSettings().setDisplayZoomControls(true);
mynews.getSettings().setDomStorageEnabled(true);
mynews.getSettings().setLoadsImagesAutomatically(true);
mynews.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
pb.setVisibility(View.VISIBLE);
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
pb.setVisibility(View.GONE);
super.onPageFinished(view, url);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
pb.setVisibility(View.VISIBLE);
super.onPageStarted(view, url, favicon);
}
});
mynews.loadUrl("https://www.google.co.in");
this is the code I have Edited
amazon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(),"Amazon",Toast.LENGTH_LONG).show();// display the toast on home button click
Intent intent = new Intent(main.this, MainActivity.class);
intent.putExtra("url","http://www.amazon.com");
startActivity(intent);
}
});
get the value on the MainActivity.Class onCreateMethod like below
String url=getIntent().getStringExtra("url");
mynews.loadUrl(url);
I tried my best but it doesn't work for me. I want to open url other than http://google.com in default browser. What code should add inside, I seen android documentation and added the code but it doesn't work. Any suggestion is appreciated.
public class MainActivity extends Activity {
private WebView webview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
this.webview = (WebView) findViewById(R.id.activity_main_webview);
webview.loadUrl("http://google.com");
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webview.setWebViewClient(new WebViewClient()
{
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
}
}
You can try to this hope this can help you..
public class MainActivity extends AppCompatActivity {
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri uri = Uri.parse("http://gmail.com");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
}
}
try this snippet and make sure you have Internet permission in manifest file
public class MainActivity extends Activity {
private WebView webview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = (WebView) findViewById(R.id.activity_main_webview);
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
webview.loadUrl("http://google.com/");
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
String myAlternativeURL = "http://yahoo.com";
if (!url.equals(myAlternativeURL)) {
view.loadUrl(myAlternativeURL);
return true;
}
}
});
});
I have this code in my app:
public class Home extends Activity{
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
final ProgressDialog progressBar;
if(isOnline()){
WebView webView = (WebView) findViewById(R.id.home_web);
webView.setBackgroundColor(Color.parseColor(getString(R.color.colore_bg)));
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setPluginsEnabled(true);
webView.setWebViewClient(new MyWebViewClient());
progressBar = ProgressDialog.show(this,getString(R.string.caricamento),getString(R.string.attendere));
webView.setWebViewClient(new WebViewClient(){
public void onPageFinished(WebView view, String url) {
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
});
webView.loadUrl("http://www.mysite.com/android.php");
}else{
Toast.makeText(this,getString(R.string.no_connessione),Toast.LENGTH_LONG).show();
}
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
System.out.println("here");
if (Uri.parse(url).getHost().equals("mysite.com")) {
// This is my web site, so do not override; let my WebView load the page
return false;
}
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
public boolean isOnline(){
ConnectivityManager cm=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if(ni==null){
return false;
}
return ni.isConnected();
}
}
The shouldOverrideUrlLoading doesn't work, neither print the system.out, it seems to be never called. How can I repair this? I need to open all the link (except the main page www.mysite.com/iphone.php) in the default browser
You've set the WebViewClient twice, thus replacing the first one (shouldOverrideUrlLoading) with the second one (onPageFinished). Combine the two for it to work:
public class Home extends Activity{
private ProgressDialog progressBar;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
if(isOnline()){
progressBar = ProgressDialog.show(this,getString(R.string.caricamento),getString(R.string.attendere));
WebView webView = (WebView) findViewById(R.id.home_web);
webView.setBackgroundColor(Color.parseColor(getString(R.color.colore_bg)));
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setPluginsEnabled(true);
webView.setWebViewClient(new MyWebViewClient());
webView.loadUrl("http://www.mysite.com/android.php");
}else{
Toast.makeText(this,getString(R.string.no_connessione),Toast.LENGTH_LONG).show();
}
}
private class MyWebViewClient extends WebViewClient {
#Override
public void onPageFinished(WebView view, String url) {
if (progressBar != null && progressBar.isShowing()) {
progressBar.dismiss();
}
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
System.out.println("here");
if (Uri.parse(url).getHost().equals("mysite.com")) {
// This is my web site, so do not override; let my WebView load the page
return false;
}
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
}
(Please ignore the bad formatting :p)