add Webview start url to sharedpreference for webview
I'm still learning Java. I'm trying to get use SharedPreferences to set the url in my WebView, so that I can set the page that is displayed the next time the app starts up. And trying to set/change the value using a menu.
Here is what I have so far:
public class test extends Activity {
public static final String PREFS_NAME = "SharedPreferences";
public static final String PREF_STRING = "http://www.google.com";
private SharedPreferences mPrefs;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPrefs = getSharedPreferences(PREFS_NAME, 0);
webview = new WebView(this) {
};
webChromeClient = new WebChromeClient() {
};
webview.setWebChromeClient(webChromeClient);
webview.setWebViewClient(webViewClient);
setContentView(webview);
/** Load the Browser Settings */
webview.loadUrl(PREF_STRING);
SharedPreferences settings = getSharedPreferences("StartPage", 0);
settings.getString("PREF_STRING", "http://www.google.com");
}
/** Begin Globals */
public WebView webview;
public WebChromeClient webChromeClient;
public WebViewClient webViewClient;
/*** define menu options */
private static final int MENU_PAGE1 = 1;
private static final int MENU_PAGE2 = 2;
/*** menu items */
public boolean onCr开发者_开发百科eateOptionsMenu(Menu menu) {
menu.add(0, MENU_PAGE1, 0, "Set page 1 to show when app is started");
menu.add(0, MENU_PAGE2, 0, "Set page 2 to show when app is started");
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_PAGE1:
Editor e = mPrefs.edit();
e.putString(PREF_STRING, "http://www.yahoo.com");
e.commit();
Toast.makeText(this, "Page 1 is set!", Toast.LENGTH_SHORT).show();
return true;
}
switch (item.getItemId()) {
case MENU_PAGE2:
Editor e = mPrefs.edit();
e.putString(PREF_STRING, "http://www.ask.com");
e.commit();
Toast.makeText(this, "Page 2 is set!", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
}
So close yet, so far... Any hints or ideas?
Try this:
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mPrefs = getSharedPreferences(PREFS_NAME, 0);
webview = new WebView(this) {
};
webChromeClient = new WebChromeClient() {
};
webview.setWebChromeClient(webChromeClient);
webview.setWebViewClient(webViewClient);
setContentView(webview);
/* Load the last saved preference. */
webview.loadUrl(mPrefs.getString(PREF_STRING, "http://www.google.com"));
}
精彩评论