I have a webview as the main activity and I want refresh the webview from the “Preference” (listview) that is from another activity. Is it possible to do that? I don’t want to have the “refresh” button on the apps menu.
But the activity will crash after i pressed “refresh” on my preference activity , i assume that is “R.id.web_engine” , that is from the MainActivity layout , that causes the crash (look at the code below).
How can I perform a webview action from the external activity ?
Example :
In my MainActivity will have
//Webview
final WebView engine = (WebView) findViewById(R.id.web_engine);
engine.loadUrl("file:///android_asset/www/index.html");
engine.getSettings().setJavaScriptEnabled(true);
and Preferences
//Get the custom preference
Preference refreshPref = (Preference) findPreference("refreshPref");
refreshPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
Toast.makeText(getBaseContext(),
"Loading...",Toast.LENGTH_SHORT).show();
WebView engine = (WebView) findViewById(R.id.web_engine);
engine.loadUrl("javascript:window.location.reload();");
return true;
}
});
I agree with Rahul Choudhary. Your webview is only visible from your main activity. You have to pass it a message that it should refresh next time it is visible.
The right place for this code is on the main activity onResume() method.
You can use intents to launch it again (it will be recreated and loose its history) or use SharedPreferences that are accessible by both activities.
EDIT: added some code below.
MainActivity
and Preferences