【问题标题】:Shared preferences logging system in androidandroid中的共享偏好记录系统
【发布时间】:2016-04-20 17:35:19
【问题描述】:

我在 stackoverflow 中进行了搜索,但找不到类似的内容。我想制作一个像注册和登录这样的日志系统。但是单击登录时,以下代码不起作用。 if 逻辑中可能存在错误。请帮忙”。

MainActivity.java

package com.example.asifsabir.sharedpref;


import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {
    EditText ed1,ed2;
    Button b1,b2,b3;
    public static final String MyPREFERENCES = "MyPrefs" ;
    public static final String email = "emailKey";
    public static final String password = "passwordKey";
    public static final String safety = "safetyKey";
    SharedPreferences sharedpreferences;
    SharedPreferences sharedpreferences2;
       //
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ed1=(EditText)findViewById(R.id.editText1);
        ed2=(EditText)findViewById(R.id.editText2);

        b1=(Button)findViewById(R.id.button);
        b2=(Button)findViewById(R.id.button2);
        b3=(Button)findViewById(R.id.button3);
        sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String email  = ed1.getText().toString();
                String password  = ed2.getText().toString();

                 if(sharedpreferences.getString(password,"").equals(password))
                    Toast.makeText(MainActivity.this, "Logged on Successful", Toast.LENGTH_SHORT).show();

            }
        });
        b2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String email  = ed1.getText().toString();
                String password  = ed2.getText().toString();
                SharedPreferences.Editor editor = sharedpreferences.edit();


                editor.putString(email,email);
                editor.putString(password,password);
                editor.commit();
                Toast.makeText(MainActivity.this,"Thanks! Signed up",Toast.LENGTH_LONG).show();
            }
        });

    }



}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Shared Preference \n     login system"
        android:id="@+id/textView1"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:textSize="35dp" />


    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editText1"
        android:layout_below="@+id/textView1"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:hint="email id: " />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editText2"
        android:layout_below="@+id/editText1"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:hint="password: " />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Login"
        android:id="@+id/button"
        android:layout_below="@+id/editText2"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Sign Up"
        android:id="@+id/button2"
        android:layout_below="@+id/button"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="forgot password?"
        android:id="@+id/button3"
        android:layout_below="@+id/button2"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp" />

</RelativeLayout>

【问题讨论】:

  • 另一个问题是:我使用电子邮件注册:asif 和密码:12345 以及电子邮件:david 密码:555 但我可以使用电子邮件登录:asif 和密码:555;如何解决?
  • 那么,您的问题是电子邮件和密码的任何组合都会让您登录,对吗?
  • 您正在使用本地和全局变量作为具有相同名称的电子邮件和密码,而不是将 de globals 更改为 emailKey、passwordKey 和这里:sharedpreferences.getString(password,"").equals(password)),更改为 sharedpreferences.getString(passwordKey,"").equals(password))
  • 对我的回答做了一点修改。告诉我进展如何。
  • 看看这个。我按你说的试过了,但它不起作用。 @danilo silva

标签: java android sharedpreferences


【解决方案1】:

我觉得你对SharedPref的理解有问题。它存储键值对。如果您使用相同的密钥来存储所有电子邮件,您仍然需要一种方法来关联用户名和密码。实现这一目标的一种方法可能是执行以下操作:

String email = ed1.getText().toString();
String password = ed2.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();

editor.putString(email, password);
editor.commit();

那么,检索就像...一样简单

String email = ed1.getText().toString();
String password = ed2.getText().toString();
if(sharedpreferences.getString(email,"").equals(password))
    ** LOG USER IN **

另一种方法是使用相同的密钥存储所有电子邮件,并使用相同的密钥存储所有密码。在这里,您需要做一些事情来确保电子邮件和密码相互连接。一种方法是在密码末尾附加电子邮件,然后保存。

String email = ed1.getText().toString();
String password = ed2.getText().toString();

password += email;

SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(this.email,email);
editor.putString(this.password,password);
editor.commit();

您现在需要使用 [getStringSet],而不是使用 getString(..)

编辑

更改这两个字段的名称也是一个好主意。

public static final String email = "emailKey";          // to emailKey
public static final String password = "passwordKey";    // to passwordKey

这将避免与EditText 框的内容混淆。

【讨论】:

  • 所以如果我在登录时输入一个随机的用户名和一个空白密码,无论注册我都可以连接吗? ;)
  • @Doomsknight 哈哈。我期待有人能抓住它。我只是专注于展示如何做到这一点,而不是方法的有效性。无论如何,将电子邮件和密码存储为明文并不是一个好主意。但是,是的。您的观点是 OP 在实施过程中应牢记的。
  • :p 觉得我应该提高是为了让你和 OP 都知道。 +1 以获得良好的整体答案。
  • @Doomsknight 欣赏它,伙计。如果您想进行任何更改/修改,请随时进行。
【解决方案2】:

//LoginActivity.java

public class LoginActivity extends Activity {
        /*Componentes gráficos*/
        Button btnLogin;
        TextView txtOmitir;
        EditText etUser, etPass;

        /*Variables globales*/
        int value, valueLogin, servicesLogin;
        Intent intent;
        String favoriteService;
        String username, password;
        private SharedPreferences.Editor editor;
        private SharedPreferences prefs;

        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.layoutlogin);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);


            prefs = getSharedPreferences("MisPreferencias", Context.MODE_PRIVATE);
            editor = prefs.edit();

            Bundle num = getIntent().getExtras();

            if (num != null) {
                servicesLogin = num.getInt("serviceslogin");
            }
            favoriteService = prefs.getString("valueService", "");


            etUser = (EditText) findViewById(R.id.etUser);
            etPass = (EditText) findViewById(R.id.etPass);


            btnLogin = (Button) findViewById(R.id.btnLogin);
            txtOmitir = (TextView) findViewById(R.id.txtOmitir);

        }

        public void btnClickLogin(View view) {
            username = etUser.getText().toString();
            password = etPass.getText().toString();

            if (username.equals("") || password.equals("")) {
                Toast.makeText(this, "Introduzca sus llaves",
                        Toast.LENGTH_SHORT).show();
                return;
            } else {

                intent = new Intent();
                editor.putString("username", username);
                editor.putString("password", password);
                editor.commit();


                    intent.setClass(LoginActivity.this, HomeActivity.class);
                    startActivity(intent);

                Toast.makeText(this, "Log-In Completado..",
                        Toast.LENGTH_SHORT).show();

            }
        }//btnClick




    public void btnClickOmitir(View view) {

            intent = new Intent();

            editor.putString("username", "");
            editor.putString("password", "");
            editor.commit();
            intent.setClass(LoginActivity.this, HomeActivity.class);
            startActivity(intent);
        }
    }//class

//layoutlogin.xml:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:layout_gravity="center_horizontal|center_vertical">

        <ImageView
            android:layout_marginTop="10dp"
            android:layout_width="180dp"
            android:layout_height="180dp"
            android:id="@+id/imgLogin"
            android:src="@drawable/ic_launcher"
            android:layout_gravity="center_horizontal" />

        <EditText
            android:layout_width="300dp"
            android:layout_height="wrap_content"
            android:id="@+id/etUser"
            android:hint="username"
            android:maxLength="16"
            android:singleLine="true"
            android:textAlignment="center"
            android:layout_marginTop="10dp"
            android:layout_gravity="center_horizontal"
            android:focusableInTouchMode="true"
            android:text="root" />

        <EditText
            android:layout_width="300dp"
            android:layout_height="wrap_content"
            android:id="@+id/etPass"
            android:singleLine="true"
            android:hint="password"
            android:textAlignment="center"
            android:layout_marginTop="10dp"
            android:layout_gravity="center_horizontal"
            android:inputType="textPassword"
            android:focusableInTouchMode="true"
            android:text="masterkey" />

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Recordar"
            android:id="@+id/checkBox"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="15dp" />

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="10dp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:text="Empleado"
                android:id="@+id/textView13"
                android:layout_gravity="center_vertical"
                android:layout_marginRight="5dp" />

            <Switch
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/switch1"
                android:layout_gravity="center_horizontal"
                android:checked="true" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:text="Alumno"
                android:id="@+id/textView"
                android:layout_gravity="center_vertical"
                android:layout_marginLeft="10dp" />

        </LinearLayout>

        <LinearLayout
            android:gravity="center"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="5dp">

            <Button
                android:layout_width="300dp"
                android:layout_height="wrap_content"
                android:text="Log in"
                android:onClick="btnClickLogin"
                android:id="@+id/btnLogin"
                android:layout_gravity="center"
                android:layout_marginTop="8dp"
                android:layout_weight="1" />

            <Button

                android:layout_width="300dp"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:text="OMITIR"
                android:onClick="btnClickOmitir"
                android:id="@+id/txtOmitir"
                android:textColor="#1619ef"
                android:layout_gravity="center"
                android:layout_marginTop="5dp"
                android:layout_weight=".5"
                android:background="#00000000"
                android:singleLine="true" />
        </LinearLayout>

    </LinearLayout>
</ScrollView>

//你可以检查一下

prefs = getSharedPreferences("MisPreferencias",    Context.MODE_PRIVATE);
String email = ed1.getText().toString();    
String password = ed2.getText().toString();

                               passwordLogin=prefs.getString("password","");
                               userLogin = prefs.getString("username", "");

                               editor = prefs.edit();

                               if (userLogin.equals(email) &&     passwordLogin.equals(password )) {
                               //do something     //Login succesfull
                               }

【讨论】:

  • 为什么这确实有效?您甚至没有标记任何更改!人们应该穿过代码墙吗?
  • 不,这没有帮助,我想检查登录输入是否与之前注册的密码组合一致。 @克里斯托弗马林
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-17
  • 2019-06-20
  • 1970-01-01
  • 2012-10-24
  • 2019-12-04
  • 1970-01-01
相关资源
最近更新 更多