2013-02-01 550 views
0

我想在我的應用程序中用戶SharedPrefs,我只是想從一個單獨的設置活動中檢索電子郵件地址和密碼。我已經實現共享首選項

package com.overclockerz.webtest; 

import android.app.Activity; 
import android.content.SharedPreferences; 
import android.os.Bundle; 
import android.widget.EditText; 

public class SettingScreen extends Activity { 
    static EditText username; 
    static EditText password; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.setting_screen); 
    username = (EditText) findViewById(R.id.username); 
    password = (EditText) findViewById(R.id.password); 

    SharedPreferences settings = 
      getSharedPreferences("APP_PREFS", MODE_PRIVATE); 
    SharedPreferences.Editor prefEditor = settings.edit(); 
    prefEditor.putString("Username", username.getText().toString()); 
    prefEditor.putString("Password", username.getText().toString()); 
    prefEditor.commit();   

} 

} 

我試圖檢索與 包com.overclockerz.webtest;

import org.apache.http.util.EncodingUtils; 

import android.annotation.SuppressLint; 
import android.app.Activity; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import android.os.Bundle; 
import android.preference.PreferenceManager; 
import android.view.KeyEvent; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.webkit.CookieManager; 
import android.webkit.WebSettings; 
import android.webkit.WebSettings.LayoutAlgorithm; 
import android.webkit.WebView; 
import android.webkit.WebViewClient; 
import android.widget.AdapterView; 
import android.widget.AdapterView.OnItemSelectedListener; 
import android.widget.ArrayAdapter; 
import android.widget.Spinner; 
import android.widget.Toast; 

public class MainActivity extends Activity implements OnItemSelectedListener, 
     OnClickListener { 
String query = "fldUsername=" + username + "&fldPassword=" + password + "&ut=3"; 
String username = prefs.getString("Username"); 
String password = getText(R.id.password).toString(); 

    @SuppressLint("SetJavaScriptEnabled") 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); 
     // then you use 
     prefs.getBoolean("keystring", true); 
     //there are also methods to put strings,float, longs, ints 





     WebView myWebView = (WebView) findViewById(R.id.webview); 
     WebSettings webSettings = myWebView.getSettings(); 
     webSettings.setJavaScriptEnabled(true); 
     webSettings.setUserAgentString("SMUK"); 
     //myWebView.setInitialScale(100); 
     //myWebView.setPadding(0, 0, 0, 0); 
     CookieManager.getInstance().setAcceptCookie(true); 

     // webSettings.setUseWideViewPort(true); 
     webSettings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN); 
     myWebView.setWebViewClient(new WebViewClient()); 
     myWebView.postUrl("http://test.schoolmilkuk.co.uk/parents-login", 
       EncodingUtils.getBytes(query,"BASE64")); 
     Toast.makeText(getApplicationContext(), query, Toast.LENGTH_LONG) 
     .show(); 
     Spinner spinner = (Spinner) findViewById(R.id.menu_spinner); 
     // Create an ArrayAdapter using the string array and a default spinner 
     // layout 
     ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
       this, R.array.spinner_links, 
       android.R.layout.simple_spinner_item); 
     // Specify the layout to use when the list of choices appears 
     adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
     // Apply the adapter to the spinner 
     spinner.setAdapter(adapter); 

     spinner.setOnItemSelectedListener(this); 
    } 

    @Override 
    public boolean onKeyDown(int keyCode, KeyEvent event) { 
     WebView myWebView = (WebView) findViewById(R.id.webview); 
     // Check if the key event was the Back button and if there's history 
     if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) { 
      myWebView.goBack(); 
      return true; 
     } 
     // If it wasn't the Back key or there's no web page history, bubble up 
     // to the default 
     // system behavior (probably exit the activity) 
     return super.onKeyDown(keyCode, event); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.activity_main, menu); 
     return true; 

    } 

    @Override 
    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, 
      long arg3) { 
     WebView myWebView = (WebView) findViewById(R.id.webview); 
     switch (arg2) { 
     case 0: 
      myWebView.postUrl("http://test.schoolmilkuk.co.uk/parents-login", 
        EncodingUtils.getBytes(query,"BASE64")); 
      myWebView.loadUrl("http://test.schoolmilkuk.co.uk/parent-home"); 
      break; 
     case 1: 
      myWebView.postUrl("http://test.schoolmilkuk.co.uk/parents-login", 
        EncodingUtils.getBytes(query,"BASE64")); 
      myWebView 
        .loadUrl("http://test.schoolmilkuk.co.uk/parent-change-pass"); 
      break; 
     case 2: 
      myWebView.postUrl("http://test.schoolmilkuk.co.uk/parents-login", 
        EncodingUtils.getBytes(query,"BASE64")); 
      myWebView 
        .loadUrl("http://test.schoolmilkuk.co.uk/parent-add-child"); 
      break; 
     case 3: 
      myWebView.postUrl("http://test.schoolmilkuk.co.uk/parents-login", 
        EncodingUtils.getBytes(query,"BASE64")); 
      myWebView 
        .loadUrl("http://test.schoolmilkuk.co.uk/parent-children-list"); 
      break; 
     case 4: 
      myWebView.postUrl("http://test.schoolmilkuk.co.uk/parents-login", 
        EncodingUtils.getBytes(query,"BASE64")); 
      myWebView.loadUrl("http://test.schoolmilkuk.co.uk/parent-order"); 
      break; 
     case 5: 
      myWebView.clearCache(true); 
      Toast.makeText(getApplicationContext(), "Cache Cleared :)", 
        Toast.LENGTH_LONG).show(); 
      break; 
     default: 
      myWebView.loadUrl("http://test.schoolmilkuk.co.uk/parent-home"); 
      break; 
     } 
    } 

    @Override 
    public void onNothingSelected(AdapterView<?> arg0) { 
     // TODO Auto-generated method stub 

    } 

    @Override 
    public void onClick(View v) { 
     // TODO Auto-generated method stub 

    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     switch (item.getItemId()) { 
     case R.id.settings_menu: 
      startActivity(new Intent(this, SettingScreen.class)); 
      return true; 
     default: 
      return super.onOptionsItemSelected(item); 
     } 
    } 

} 

字符串username = prefs.getString(「用戶名」,「用戶名」),因爲它是不使用的變量用戶集,因爲您提供「用戶名」沒有意義?我非常困惑。

隨着黑帶的建議(其中的一切都非常讚賞)後,我修改了代碼,我看到一個空指針異常?

package com.overclockerz.webtest; 

import android.app.Activity; 
import android.content.SharedPreferences; 
import android.os.Bundle; 
import android.widget.EditText; 

public class SettingScreen extends Activity { 
    static EditText username; 
    static EditText password; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     // TODO Auto-generated method stub 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.setting_screen); 
     username = (EditText) findViewById(R.id.username); 
     password = (EditText) findViewById(R.id.password); 

     SharedPreferences settings = 
       getSharedPreferences("APP_PREFS", MODE_PRIVATE); 
     SharedPreferences.Editor prefEditor = settings.edit(); 
     prefEditor.putString("Username", username.getText().toString()); 
     prefEditor.putString("Password", username.getText().toString()); 
     prefEditor.commit();   

    } 

} 

package com.overclockerz.webtest; 

import org.apache.http.util.EncodingUtils; 

import android.annotation.SuppressLint; 
import android.app.Activity; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import android.os.Bundle; 
import android.preference.PreferenceManager; 
import android.view.KeyEvent; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.webkit.CookieManager; 
import android.webkit.WebSettings; 
import android.webkit.WebSettings.LayoutAlgorithm; 
import android.webkit.WebView; 
import android.webkit.WebViewClient; 
import android.widget.AdapterView; 
import android.widget.AdapterView.OnItemSelectedListener; 
import android.widget.ArrayAdapter; 
import android.widget.Spinner; 
import android.widget.Toast; 

public class MainActivity extends Activity implements OnItemSelectedListener, 
     OnClickListener { 
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); 
String username = prefs.getString("Username", "default"); 
String password = prefs.getString("Password", "default"); 

String query = "fldUsername=" + username + "&fldPassword=" + password + "&ut=3"; 
    @SuppressLint("SetJavaScriptEnabled") 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 



     WebView myWebView = (WebView) findViewById(R.id.webview); 
     WebSettings webSettings = myWebView.getSettings(); 
     webSettings.setJavaScriptEnabled(true); 
     webSettings.setUserAgentString("SMUK"); 
     //myWebView.setInitialScale(100); 
     //myWebView.setPadding(0, 0, 0, 0); 
     CookieManager.getInstance().setAcceptCookie(true); 

     // webSettings.setUseWideViewPort(true); 
     webSettings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN); 
     myWebView.setWebViewClient(new WebViewClient()); 
     myWebView.postUrl("http://test.schoolmilkuk.co.uk/parents-login", 
       EncodingUtils.getBytes(query,"BASE64")); 
     Toast.makeText(getApplicationContext(), query, Toast.LENGTH_LONG) 
     .show(); 
     Spinner spinner = (Spinner) findViewById(R.id.menu_spinner); 
     // Create an ArrayAdapter using the string array and a default spinner 
     // layout 
     ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
       this, R.array.spinner_links, 
       android.R.layout.simple_spinner_item); 
     // Specify the layout to use when the list of choices appears 
     adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
     // Apply the adapter to the spinner 
     spinner.setAdapter(adapter); 

     spinner.setOnItemSelectedListener(this); 
    } 

    @Override 
    public boolean onKeyDown(int keyCode, KeyEvent event) { 
     WebView myWebView = (WebView) findViewById(R.id.webview); 
     // Check if the key event was the Back button and if there's history 
     if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) { 
      myWebView.goBack(); 
      return true; 
     } 
     // If it wasn't the Back key or there's no web page history, bubble up 
     // to the default 
     // system behavior (probably exit the activity) 
     return super.onKeyDown(keyCode, event); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.activity_main, menu); 
     return true; 

    } 

    @Override 
    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, 
      long arg3) { 
     WebView myWebView = (WebView) findViewById(R.id.webview); 
     switch (arg2) { 
     case 0: 
      myWebView.postUrl("http://test.schoolmilkuk.co.uk/parents-login", 
        EncodingUtils.getBytes(query,"BASE64")); 
      myWebView.loadUrl("http://test.schoolmilkuk.co.uk/parent-home"); 
      break; 
     case 1: 
      myWebView.postUrl("http://test.schoolmilkuk.co.uk/parents-login", 
        EncodingUtils.getBytes(query,"BASE64")); 
      myWebView 
        .loadUrl("http://test.schoolmilkuk.co.uk/parent-change-pass"); 
      break; 
     case 2: 
      myWebView.postUrl("http://test.schoolmilkuk.co.uk/parents-login", 
        EncodingUtils.getBytes(query,"BASE64")); 
      myWebView 
        .loadUrl("http://test.schoolmilkuk.co.uk/parent-add-child"); 
      break; 
     case 3: 
      myWebView.postUrl("http://test.schoolmilkuk.co.uk/parents-login", 
        EncodingUtils.getBytes(query,"BASE64")); 
      myWebView 
        .loadUrl("http://test.schoolmilkuk.co.uk/parent-children-list"); 
      break; 
     case 4: 
      myWebView.postUrl("http://test.schoolmilkuk.co.uk/parents-login", 
        EncodingUtils.getBytes(query,"BASE64")); 
      myWebView.loadUrl("http://test.schoolmilkuk.co.uk/parent-order"); 
      break; 
     case 5: 
      myWebView.clearCache(true); 
      Toast.makeText(getApplicationContext(), "Cache Cleared :)", 
        Toast.LENGTH_LONG).show(); 
      break; 
     default: 
      myWebView.loadUrl("http://test.schoolmilkuk.co.uk/parent-home"); 
      break; 
     } 
    } 

    @Override 
    public void onNothingSelected(AdapterView<?> arg0) { 
     // TODO Auto-generated method stub 

    } 

    @Override 
    public void onClick(View v) { 
     // TODO Auto-generated method stub 

    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     switch (item.getItemId()) { 
     case R.id.settings_menu: 
      startActivity(new Intent(this, SettingScreen.class)); 
      return true; 
     default: 
      return super.onOptionsItemSelected(item); 
     } 
    } 

} 
+0

看到這個http://stackoverflow.com/questions/13263855/how-to-retain-the-global-variebles-when-application-is -upgraded到新版本的I/13263998#13263998 –

回答

2

PreferenceManager.getDefaultSharedPreferences

SharedPreferences settings = 
      getSharedPreferences("APP_PREFS", MODE_PRIVATE); 

返回不同的事情。

前者將使用默認文件名(類似於您的pakage名稱),後者將需要一個名稱。所以不要感到困惑。 getString()的第二個參數是默認值。例如,您可以使用它來檢查一些調味品是否符合要求。

1

重讀文檔getString。只有在首選項中沒有值時,它纔會返回defValue。您可以通過null作爲第二個參數。如果你得到null這意味着沒有設置用戶名。
此外,您應該將用戶名保存到某個操作的首選項,而不是onCreate。例如。創建按鈕「確定」,並在onClick中保存該用戶名。

0

如果您需要多個共享首選項,請在其中添加一些名稱。

SharedPreferences sp = getApplication().getSharedPreferences("someName", Context.MODE_PRIVATE); 

如果你只需要一個再

SharedPrefrences sp = PreferenceManager.getDefaultSharedPreferences(this);