使用SharedPreferences存储用户密码

时间:2013-02-20 12:19:37

标签: android passwords sharedpreferences

所以我需要我的简单应用才能拥有密码。默认密码为“admin”,如果用户愿意,用户可以更改密码。但我在改变部分时遇到了问题。我不知道为什么,但我为此做的活动总是强制关闭。这是我第一次使用SharedPreferences。我不知道我是否正确使用过它。请帮我。这是我的代码:

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class ChangePass extends Activity {

    @SuppressLint("CommitPrefEdits")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.change_pass);

        final SharedPreferences settings = ChangePass.this.getSharedPreferences("pass", 0);
        final SharedPreferences.Editor editor = settings.edit();

        final EditText CurPass;
        final EditText NewPass1;
        final EditText NewPass2;
        Button BtnSubmit;
        final TextView errorMsg;

        CurPass = (EditText)this.findViewById(R.id.curPW);
        NewPass1 = (EditText)this.findViewById(R.id.newPW1);
        NewPass2 = (EditText)this.findViewById(R.id.newPW2);
        BtnSubmit = (Button)this.findViewById(R.id.btnSubmit);
        errorMsg = (Button)this.findViewById(R.id.errorTxt);

        BtnSubmit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                String current = CurPass.getText().toString().trim();
                String new1 = NewPass1.getText().toString().trim();
                String new2 = NewPass2.getText().toString().trim();

                String CurrentPW = settings.getString("Password", "admin");

                if (CurrentPW.equals(current)) {
                    if (new1.equals(new2)) {

                          editor.putString("Password", new1).apply();


                            Toast.makeText(getApplicationContext(), "Password successfully changed!",
                            Toast.LENGTH_LONG).show();
                            CurPass.setText("");
                            NewPass1.setText("");
                            NewPass2.setText("");
                    }
                    else {
                        errorMsg.setText("ERROR: Passwords did not match.");
                    }
                }
                else {
                    errorMsg.setText("ERROR: Wrong password.");
                }    
            }
        });
    }

XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/new_bg_pass" >

    <EditText
        android:id="@+id/curPW"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="144dp"
        android:ems="10"
        android:inputType="textPassword" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/newPW1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/curPW"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="57dp"
        android:ems="10"
        android:inputType="textPassword" />

    <TextView
        android:id="@+id/TextView01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/newPW1"
        android:layout_alignLeft="@+id/textView1"
        android:text="New Password:"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/newPW2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/newPW1"
        android:layout_below="@+id/newPW1"
        android:layout_marginTop="35dp"
        android:ems="10"
        android:inputType="textPassword" />

    <TextView
        android:id="@+id/TextView02"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/newPW2"
        android:layout_alignLeft="@+id/TextView01"
        android:text="Retype New Password:"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/newPW1"
        android:layout_marginRight="57dp"
        android:layout_toLeftOf="@+id/curPW"
        android:text="Current Password:"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <Button
        android:id="@+id/btnSubmit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/newPW2"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="40dp"
        android:text="Submit" />

    <TextView
        android:id="@+id/errorTxt"
        android:layout_width="400dp"
        android:layout_height="wrap_content"
        android:layout_above="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="34dp"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#FF0000" />

</RelativeLayout>

这是来自LogCat:

02-20 12:28:58.156: E/AndroidRuntime(338): FATAL EXCEPTION: main
02-20 12:28:58.156: E/AndroidRuntime(338): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.login/com.login.ChangePass}: java.lang.ClassCastException: android.widget.TextView
02-20 12:28:58.156: E/AndroidRuntime(338):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
02-20 12:28:58.156: E/AndroidRuntime(338):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
02-20 12:28:58.156: E/AndroidRuntime(338):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
02-20 12:28:58.156: E/AndroidRuntime(338):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
02-20 12:28:58.156: E/AndroidRuntime(338):  at android.os.Handler.dispatchMessage(Handler.java:99)
02-20 12:28:58.156: E/AndroidRuntime(338):  at android.os.Looper.loop(Looper.java:123)
02-20 12:28:58.156: E/AndroidRuntime(338):  at android.app.ActivityThread.main(ActivityThread.java:3683)
02-20 12:28:58.156: E/AndroidRuntime(338):  at java.lang.reflect.Method.invokeNative(Native Method)
02-20 12:28:58.156: E/AndroidRuntime(338):  at java.lang.reflect.Method.invoke(Method.java:507)
02-20 12:28:58.156: E/AndroidRuntime(338):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-20 12:28:58.156: E/AndroidRuntime(338):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-20 12:28:58.156: E/AndroidRuntime(338):  at dalvik.system.NativeStart.main(Native Method)
02-20 12:28:58.156: E/AndroidRuntime(338): Caused by: java.lang.ClassCastException: android.widget.TextView
02-20 12:28:58.156: E/AndroidRuntime(338):  at com.login.ChangePass.onCreate(ChangePass.java:35)
02-20 12:28:58.156: E/AndroidRuntime(338):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-20 12:28:58.156: E/AndroidRuntime(338):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
02-20 12:28:58.156: E/AndroidRuntime(338):  ... 11 more

2 个答案:

答案 0 :(得分:1)

您已将TextView定义为

    final TextView errorMsg;

你正试图把它投入按钮:

         errorMsg = (Button)this.findViewById(R.id.errorTxt);

此外你应该按如下方式进行投射:

         errorMsg = (TextView)this.findViewById(R.id.errorTxt);

<强>编辑:

创建共享偏好:

     SharedPreferences sp=getSharedPreferences("Login", 0);
     SharedPreferences.Editor Ed=sp.edit();
     Ed.putString("Psw",Value);   
     Ed.commit();

从共享偏好中获取价值:

     SharedPreferences sp1=this.getSharedPreferences("Login",null);
     String pass = sp1.getString("Psw", null);

更新共享首选项值:

    if (pass.equals(current)) {
          Ed.putString("Psw", new1);
          Ed.commit();     
      } 

答案 1 :(得分:0)

清单可能有一些问题,看起来应该更像:

<activity android:name=".start" android:label="@string/app_name">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
<activity android:name= ".Main">
</activity>