how to get title onPageFinished() (webview)? - java

i have a problem. i am using WebView Object in my project. in MainActivity.java code side i use webbBrowser.setWebViewClient(new ViewBrowser());
there is second class having name ViewBrowser.java this file is extended with WebViewClient.
by using this Client service in this java file there are 2 functions Overrode
1 - shouldOverrideUrlLoading(WebView view, String url)
2 - onPageFinished(WebView view, String url)
in onPageFinished() i have used view.getTitle(); i want to set this title to TextView on my MainActivity class. can any body help me for this.
this is my MainActivity.java class:
public class MainActivity extends Activity implements OnClickListener {
Button bttnSearch;
EditText txttInput;
TextView txttView;
WebView webbBrowser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
bttnSearch = (Button) findViewById(R.id.btnGo);
txttInput = (EditText) findViewById(R.id.txtInput);
txttView = (TextView) findViewById(R.id.txtView);
webbBrowser = (WebView) findViewById(R.id.broWebView);
webbBrowser.setWebViewClient(new ViewBrowser());
webbBrowser.getSettings().setLoadsImagesAutomatically(true);
webbBrowser.getSettings().setJavaScriptEnabled(true);
webbBrowser.getSettings().setLoadWithOverviewMode(true);
webbBrowser.getSettings().setUseWideViewPort(true);
webbBrowser.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webbBrowser.setScrollbarFadingEnabled(true);
webbBrowser.loadUrl("http:/www.google.com");
bttnSearch.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String urlText;
urlText = txttInput.getText().toString();
switch(v.getId()){
case R.id.btnGo:
InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
webbBrowser.loadUrl(urlText);
break;
}
} }
this is my ViewBrowser.java:
public class QaziViewBrowser extends WebViewClient {
//private Toast txttView;
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return super.shouldOverrideUrlLoading(view, url);
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
// i want to get Title text of the web page and set to txttView
}
}

in you activity on create register the broadcast like this
registerReceiver(updateText, new IntentFilter("UPDATE_TEXT"));
onDestroy unregister
unregisterReceiver(updateText);
make a broadcast reciever
BroadcastReceiver updateText = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "onReceive()");
// check if intent is not null and other verification if needed
TextView.setText(intent.getStringExtra("title"));
}
};
in your webview class what u have to do is fire boradcast putting the title in intent
Intent intentToBroadcast = new Intent("UPDATE_TEXT");
intentToBroadcast.putExtra(title, webview.getTitle());
mContext.sendBroadcast(intentToBroadcast);
i haven't test run this code but this is the logic that will work, hope it helps.

Its quite simple.
In the callback onPageFinished you can get the title of the page loaded.
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
// i want to get Title text of the web page and set to txttView
String title = view.getTitle();
// Use title where ever and which ever way you want.
}

You can use Jsoup library(Download link : http://jsoup.org/).
and onPageFinished() method use below code
onPageFinished(WebView view, String url){
new ContentDownloader(url).execute();
}
private class ContentDownloader extends AsyncTask<Void, Void, Void>
{
Document document;
String url;
public ContentDownloader(String p_url)
{
url = p_url;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
m_progressDialog = ProgressDialog.show(MainActivity.this, "Wait", "Content Downloading..");
}
#Override
protected Void doInBackground(Void... params)
{
try
{
document = Jsoup.connect(url).post();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
if(document != null) {
m_tvTitle.setText(m_document.title());
}
m_progressDialog.dismiss();
}

Related

Loading created by ProgressDialog wouldn't stop , how to hide progressbar when page is loaded

I'm new to Java and was trying to create a web-view app. The loading widget was created using Progress Dialog but it wouldn't stop. I don't know what is wrong. Please help.
public class MainActivity extends AppCompatActivity {
private WebView mywebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ProgressDialog pd = ProgressDialog.show(this, "", "Loading...",true);
mywebView = (WebView) findViewById(R.id.webview);
mywebView.getSettings().setJavaScriptEnabled(true);
mywebView.getSettings().setSupportZoom(true);
mywebView.getSettings().setBuiltInZoomControls(true);
mywebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
if(pd!=null && pd.isShowing())
{
pd.dismiss();
}
}
});
mywebView.loadUrl("https://google.com");
mywebView.setWebViewClient(new WvClient());
}
private class WvClient extends WebViewClient
{
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError er) {
handler.proceed();
}
}
#Override
public void onBackPressed() {
if(mywebView.canGoBack())
{
mywebView.goBack();
}
else
{
super.onBackPressed();
}
}
}
You have declared setWebViewClient twice , ie after load url you again
declared the setWebViewClient with your custom client , correct answer is
public class MainActivity extends AppCompatActivity {
private WebView mywebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ProgressDialog pd = ProgressDialog.show(this, "", "Loading...",true);
mywebView = (WebView) findViewById(R.id.webview);
mywebView.getSettings().setJavaScriptEnabled(true);
mywebView.getSettings().setSupportZoom(true);
mywebView.getSettings().setBuiltInZoomControls(true);
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
pd.show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if(pd!=null && pd.isShowing())
{
pd.dismiss();
}
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
if(pd!=null && pd.isShowing())
{
pd.dismiss();
}
}
});
mywebView.loadUrl("https://google.com");
}
#Override
public void onBackPressed() {
if(mywebView.canGoBack())
{
mywebView.goBack();
}
else
{
super.onBackPressed();
}
}
}
Place a breakpoint in
onPageFinished
and see if the listener actually get called?

Using getUrl() variable in outer/upper class

String url = "http://xxxx.com/login.php?UID=";
String uid = portal.mysharedvars.getString("uid");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_personel_activity);
/*if(newurl.toLowerCase().contains("index.php")) {
I want to do somethings here
}
*/
WebView siteview = (WebView) findViewById(R.id.personel_webview);
siteview.setWebViewClient(new MywebViewClient());
final String link = url+uid;
siteview.loadUrl(link);
}
private class MywebViewClient extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
// do your stuff here
String newurl = view.getUrl();
Toast.makeText(login_personel_webview.this, newurl, Toast.LENGTH_LONG).show();
}
as you see above, I've a link variable in my webview activity with onPageFinished public. I would like to use that variable in starred line with an if statement. How could I get used that variable there?
EDIT: ofc the link will not be static as declared at start. Tats just login page. than will be many pages.
Try do this through callback
String url = "http://xxxx.com/login.php?UID=";
String uid = portal.mysharedvars.getString("uid");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView siteview = (WebView) findViewById(R.id.personel_webview);
siteview.setWebViewClient(new MywebViewClient(new Callback() {
#Override
public void onPageUrl(String url) {
if (url.toLowerCase().contains("index.php")) {
//Do what you want here
}
}
}));
final String link = url+uid;
siteview.loadUrl(link);
}
private class MywebViewClient extends WebViewClient {
Callback callback;
public MywebViewClient(Callback callback) {
this.callback = callback;
}
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
// do your stuff here
String newurl = view.getUrl();
callback.onPageUrl(newurl);
Toast.makeText(login_personel_webview.this, newurl, Toast.LENGTH_LONG).show();
}
}
public interface Callback {
void onPageUrl(String url);
}

onBackPressed() crashes my webview app

I am new to android development, I have tried to override onBackPress() to implement webView.GoBack(). But on pressing back key my apps getting crashed. Here is my MainActivity.java code. Am I doing something wrong ??
public class MainActivity extends AppCompatActivity {
private WebView webview;
/** Called when the activity is first created. */
public void onBackPressed (){
if (webview.isFocused() && webview.canGoBack()) {
webview.goBack();
}
else {
super.onBackPressed();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView view = (WebView) findViewById(R.id.webView);
view.getSettings().setJavaScriptEnabled(true);
view.setWebViewClient(new MyCustomWebViewClient());
view.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
view.loadUrl("http://url");
}
private class MyCustomWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
//hide loading image
findViewById(R.id.imageLoading1).setVisibility(View.GONE);
//show webview
findViewById(R.id.webView).setVisibility(View.VISIBLE);
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
if (view.canGoBack()) {
view.goBack();
} else {
view.loadUrl("file:///android_asset/index.html");
}
Toast.makeText(getBaseContext(), description, Toast.LENGTH_LONG).show();
}
}
}
Just because your webView is null. You are not referencing it anywhere. Modified your code.
public class MainActivity extends AppCompatActivity {
private WebView view;
/** Called when the activity is first created. */
public void onBackPressed (){
if (view.isFocused() && view.canGoBack()) {
view.goBack();
}
else {
super.onBackPressed();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view = (WebView) findViewById(R.id.webView);
view.getSettings().setJavaScriptEnabled(true);
view.setWebViewClient(new MyCustomWebViewClient());
view.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
view.loadUrl("http://url");
}
private class MyCustomWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
//hide loading image
findViewById(R.id.imageLoading1).setVisibility(View.GONE);
//show webview
findViewById(R.id.webView).setVisibility(View.VISIBLE);
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
if (view.canGoBack()) {
view.goBack();
} else {
view.loadUrl("file:///android_asset/index.html");
}
Toast.makeText(getBaseContext(), description, Toast.LENGTH_LONG).show();
}
}
}
In onCreate you have:
WebView view = (WebView) findViewById(R.id.webView);
The WebView you have defined at the top has not been initialized, and is the one being used by the onBackPressed method, to fix this all you need to do is remove WebView before initializing the variable in onCreate:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view = (WebView) findViewById(R.id.webView);
view.getSettings().setJavaScriptEnabled(true);
view.setWebViewClient(new MyCustomWebViewClient());
view.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
view.loadUrl("http://url");
}
Actually you can not do directly inside the fragment. The onBackPressed can be overridden in the FragmentActivity. What you can do is:
1.Override the onBackPressed inside the activity.
2.When the onBackPressed is called, check if the instance of the current fragment is the instance showing the webview.
3.If it is, ask the fragment if the webview can go back.
4.If it is not, call the super or whatever you need
#Override
public void onBackPressed() {
Fragment webview = getSupportFragmentManager().findFragmentByTag("webview");
if (webview instanceof MyWebViewFragment) {
boolean goback = ((MyWebViewFragment)webview).canGoBack();
if (!goback)
super.onBackPressed();
}
}

Java - WebView What event handles (watches) URL changes - Android

The app does a login to a web application using WebView. Once in the webview, the webview appears to handle everything for you as it should based on the user's clicks. However I need to review on each event if the URL changes to a specific logout URL.
How can I return the user to the app itself when the user logs out on the web application within the webview? I do not want the webview to stay as the active view.
I have tried WebViewClient.shouldOverrideUrlLoading and View.OnTouchListsner.
The class I tried to implement public but it didn't allow me.
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;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
}
}
Here's the code before I want to call the method to check the URL;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText phone = (EditText) findViewById(R.id.phone1);
final EditText login = (EditText) findViewById(R.id.uname);
final EditText pass = (EditText) findViewById(R.id.password);
phone.requestFocus();
final Context context = this;
submit = (Button)findViewById(R.id.submit);
sbutton = (Button)findViewById(R.id.loginCred);
chcred = (CheckBox) findViewById(R.id.cBox);
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textstring(phone, login, pass);
encPhone = URLEncoder.encode(Phone);
encLogin = URLEncoder.encode(Login);
encPass = URLEncoder.encode(Pass);
if (chcred.isChecked()) {
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
prefwrite(editor);
}
pushurl();
clear(phone, login, pass);
}
});
WebViewClient() //Right here is where I want to call it
This can help you:
https://developer.android.com/reference/android/webkit/WebViewClient.html#onPageStarted(android.webkit.WebView, java.lang.String, android.graphics.Bitmap)
The event does not notify you when the url changes, but does when the page starts to load, at that point you only need to verify the current url.
Try This
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView webview, String url) {
Uri uri = Uri.parse(url);
if (uri.getScheme().contains("google") || uri.getScheme().contains("tel")) {
try {
Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
if (intent.resolveActivity(getPackageManager()) != null)
startActivity(intent);
return true;
} catch (URISyntaxException use) {
Log.e("TAG", use.getMessage());
}
} else {
webview.loadUrl(url);
Log.e("url", url);
}
return true;
}
#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);
}
#Override
public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
super.doUpdateVisitedHistory(view, url, isReload);
String currentUrl=view.getUrl();
}
});
webView.loadUrl(url);
here webView is my WebView and url is the url which I am using in my webview.
If you want to make some changes with the change in url,then go for
#Override
public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
super.doUpdateVisitedHistory(view, url, isReload);
String currentUrl=view.getUrl();
}
you will get the url updation in this call.

create AsyncTask for Android

Can I know how to create AsyncTask for Android from all of these? I would like to remove the buttons and let all of these run in the background then redirect to the MainPage.java after clicking Logout.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
Button btnDelete = (Button)findViewById(R.id.delete);
Button btnSignUp = (Button)findViewById(R.id.btnSignUp);
Button btnLogin = (Button)findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getApplicationContext(),HomePage.class);
startActivity(intent);
}
});
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this,SignUp.class);
startActivity(intent);
}
});
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
cDB.resetTables();
mDB.resetTables();
db.resetTables();
pDB.resetTables();
}
});
}
here is one AsyncTask Example. This will show a peogress dialog while executing the task.
private class LoginProcessing extends AsyncTask<Object, Void, Void> {
private LoginCredentials myLoginCredentials;
private ProgressDialog progressDialog;
public LoginProcessing(LoginCredentials Credentials) {
super();
myLoginCredentials=Credentials;
}
protected void onPreExecute (){
progressDialog = ProgressDialog.show(context, "", "Please Wait...",true);
}
#Override
protected Void doInBackground(Object... arg0) {
// TODO Auto-generated method stub
//Code to do the process in background
return null;
}
protected void onPostExecute(Void result){
progressDialog.dismiss();
//Your code after the process
}
}
You can call this Task as,
new LoginProcessing(loginCredentials).execute();
In this Example loginCredentials is the parameter I am passing to the AsyncTask. You can change it to your own parameter.

Categories