1

我正在使用 sharedpreference 来存储用户名。当我在我的活动中这样做时,它工作正常。但是当我传递给一个公共类(保存值)时,它会失败。你能指导我到我的代码需要更正的地方吗?提前致谢

public class Login extends Activity  implements OnClickListener{
String userId,password,userType,key="userId";  ;
EditText etName,etPassword,etUserType;
Button go; 
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.login);
    initialize();
}
private void initialize(){

    etUserType=(EditText) findViewById (R.id.etUserType);   
    etName=(EditText) findViewById (R.id.etName);
    etPassword=(EditText) findViewById (R.id.etPassword);    
    go = (Button) findViewById(R.id.bGo);
    go.setOnClickListener(this); 
}

@Override
public void onClick(View arg0) {
    // TODO Auto-generated method stub  
    userType=etUserType.getText().toString(); 
    userId=etName.getText().toString();
    password=etPassword.getText().toString();   

    if (userId.isEmpty() || password.isEmpty() ) { 
        Dialog d = new Dialog(this);
        d.setTitle("   Alert  ");
        TextView tv = new TextView(this);
        tv.setText("User Name and Password are mandatory");
        d.setContentView(tv);
        d.show();
    }else{


          StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
          StrictMode.setThreadPolicy(policy);
          try {
            List<UserType> userType = PosClient.getUserTypes();
            User user = PosClient.getUser(userId, userType.get(0)); 
            LastUser lastUser = new LastUser();
            lastUser.saveUser(key, Integer.toString(user.getUserId()));  ()); 

            if  (password.equals(user.getPassword())){ 
                Intent sendBack = new Intent();
                Bundle backpack = new Bundle();
                backpack.putString("command", "proceed");  
                backpack.putSerializable("user", user);
                sendBack.putExtras(backpack);  
                setResult(RESULT_OK, sendBack);
                finish();
            }else{
                Dialog d = new Dialog(this);
                d.setTitle("   Alert  ");
                TextView tv = new TextView(this);
                tv.setText("User Name / Password is invalid");
                d.setContentView(tv);
                d.show();
            }
          } catch (ClientProtocolException e1) { 
              e1.printStackTrace();
          } catch (IOException e1) { 
              e1.printStackTrace();
          }

    }
}



public class LastUser extends Activity{
SharedPreferences file;
public static String filename = "MySharedFile";

public  String checkUser(){  
    file = getSharedPreferences(filename,0);
    String userName = file.getString("waitername", "NOID"); 
    return userName;
} 

public void saveUser(String key,String value) {  
    filename = "MySharedFile";
    file = getSharedPreferences(filename,0);
    SharedPreferences.Editor editor = file.edit();
    editor.putString(key,value);
    editor.commit();
}

}

错误详情 :

12-27 12:27:41.448: E/AndroidRuntime(2983): FATAL EXCEPTION: main
12-27 12:27:41.448: E/AndroidRuntime(2983): java.lang.NullPointerException
12-27 12:27:41.448: E/AndroidRuntime(2983):     at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:153)
12-27 12:27:41.448: E/AndroidRuntime(2983):     at com.example.restaurent.LastUser.saveUser(LastUser.java:21)
12-27 12:27:41.448: E/AndroidRuntime(2983):     at com.example.restaurent.Login.onClick(Login.java:77)
12-27 12:27:41.448: E/AndroidRuntime(2983):     at android.view.View.performClick(View.java:3534)
12-27 12:27:41.448: E/AndroidRuntime(2983):     at android.view.View$PerformClick.run(View.java:14263)
12-27 12:27:41.448: E/AndroidRuntime(2983):     at android.os.Handler.handleCallback(Handler.java:605)
12-27 12:27:41.448: E/AndroidRuntime(2983):     at android.os.Handler.dispatchMessage(Handler.java:92)
12-27 12:27:41.448: E/AndroidRuntime(2983):     at android.os.Looper.loop(Looper.java:137)
12-27 12:27:41.448: E/AndroidRuntime(2983):     at android.app.ActivityThread.main(ActivityThread.java:4441)
12-27 12:27:41.448: E/AndroidRuntime(2983):     at java.lang.reflect.Method.invokeNative(Native Method)
12-27 12:27:41.448: E/AndroidRuntime(2983):     at java.lang.reflect.Method.invoke(Method.java:511)
12-27 12:27:41.448: E/AndroidRuntime(2983):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
12-27 12:27:41.448: E/AndroidRuntime(2983):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
12-27 12:27:41.448: E/AndroidRuntime(2983):     at dalvik.system.NativeStart.main(Native Method)
4

5 回答 5

0

使用以下代码将价值存储到共享偏好中并从共享偏好中获取价值,它将解决您的问题。

将价值存储到共享偏好中。

SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("Value", "Dipak Keshariya");
prefsEditor.commit();

从共享偏好中获取价值。

SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
String mValue = myPrefs.getString("Value");
于 2012-12-27T07:27:26.527 回答
0

这里

public class LastUser extends Activity{         //<<<<<<<<
SharedPreferences file;
public static String filename = "MySharedFile";
  // your code here
}

您正在尝试创建 Activity 类的实例以从其他 Activty 访问方法,这是不正确的方法。将您的代码更改为:

public class LastUser {
SharedPreferences file;
public static String filename = "MySharedFile";


public  String checkUser(Context context){  
    file = context.getSharedPreferences(filename,0);
    String userName = file.getString("waitername", "NOID"); 
    return userName;
} 

public void saveUser(String key,String value,Context context) {  
    filename = "MySharedFile";
    file = context.getSharedPreferences(filename,0);
    SharedPreferences.Editor editor = file.edit();
    editor.putString(key,value);
    editor.commit();
}

}

现在从 Activity 创建 SharedPreferences 只需将 Activity 上下文传递给方法:

 LastUser lastUser = new LastUser();
 lastUser.saveUser(key, Integer.toString(user.getUserId()),Login.this); 
于 2012-12-27T07:16:07.060 回答
0

您无法getSharedPreference()从尚未开始的活动中获取信息。我建议您将checkUser()saveUser()代码也放在登录活动中并完全删除 LastUser 活动。

您还错误地理解了 Activity 概念。Activity 不像任何其他 Java 类,它应该只处理 UI,因为支持对象使用 POJO。

于 2012-12-27T07:16:31.063 回答
0

请在您的代码中放置以下一个

 SharedPreferences file=null;
 file= PreferenceManager.getDefaultSharedPreferences(this);
于 2012-12-27T07:21:11.627 回答
0

用这个,

file = this.getSharedPreferences(filename,0);

代替,

file = getSharedPreferences(filename,0);

谢谢。

于 2012-12-27T07:21:15.223 回答