0

I'm trying to get the current URL of the WebView on my main activity and display it as a TextView for the user in a custom DialogPreference. My difficulty right now is every time I call it, it get a null returned.

Here's my code for the custom DialogPreference:

public class CustomAlertPreference extends DialogPreference {

String currentURL = "HARDCODED TEST";
public CustomAlertPreference(Context context, AttributeSet attrs) {
    super(context, attrs);
    setDialogLayoutResource(R.layout.custom_alert_preference);
    setPositiveButtonText(android.R.string.ok);
    setNegativeButtonText(android.R.string.cancel);
}


@Override
protected void onBindDialogView(View view) {
    LayoutInflater layoutInflater = (LayoutInflater)  getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view2 = layoutInflater.inflate(R.layout.activity_main, null);
    WebView webview = (WebView)view2.findViewById(R.id.shopFloorView);
    currentURL = webview.getUrl();
    TextView txview = (TextView) view.findViewById(R.id.URLCurrent);
    txview.setText(currentURL);
}

@Override
public void onClick(DialogInterface dialog, int which) {
    if (which == DialogInterface.BUTTON_POSITIVE) {
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getContext());
        SharedPreferences.Editor editor = settings.edit();
        editor.putString("prefWMl", currentURL);
        editor.commit();
        Toast toast = Toast.makeText(getContext(), "URL changed to " + currentURL, Toast.LENGTH_SHORT);
        toast.show();
    }
}

Am I doing something wrong her to cause the WebView to return null? I have definitely let the page load entirely, so its not that.

Thanks in advance, -John

1 Answers1

0

Your WebView return null URL because it has not loaded yet.

Try adding a WebViewClient and overriding onPageFinished() to catch its URL correctly.

private String currentURL;

// ...

webview.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageFinished(WebView view, String url) {
        currentURL = url;
    }
});
webView.loadUrl("an URL");
shkschneider
  • 17,833
  • 13
  • 59
  • 112
  • I need to access the current URL on demand. (When the user opens my custom DialogPreference) – DeadlyJohny Jan 09 '15 at 17:53
  • Doesn't `currentURL` contains just that? – shkschneider Jan 12 '15 at 08:54
  • That's what its supposed to contain. Adding the function you suggested didn't seem to be called at any particular time. I must remind you that the customAlertPreference is inside a preference activity and the WebView is inside of my main activity. – DeadlyJohny Jan 12 '15 at 15:24