2016-04-20 3 views
-3

Я искал в stackoverflow, и я не мог найти ничего подобного. Я хочу создать систему регистрации, такую ​​как регистрация и логин. Но следующий код не работает при нажатии Login. Вероятно, ошибка в логике if. пожалуйста помоги'.Система регистрации общих настроек в android

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> 
+0

Еще одна проблема: я зарегистрировался по электронной почте: asif и пароль: 12345, а также по электронной почте: david pasword: 555, но я могу войти с помощью электронной почты: asif и password: 555, как это можно решить? –

+0

Итак, ваша проблема в том, что любая комбинация электронной почты и паролей регистрирует вас, правильно? –

+0

Вы используете локальные и глобальные переменные для электронной почты и паролей с тем же именем, вместо этого измените глобальные значения на emailKey, passwordKeyand здесь: sharedpreferences.getString (пароль, ""). Equals (password)), измените на sharedpreferences.getString (passwordKey , ""). равен (пароль)) –

ответ

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(); 

Вместо использования getString(..) теперь нужно будет использовать [getStringSet].

Редактировать.

Было бы также полезно изменить имена этих двух полей.

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

Это позволит избежать путаницы с содержанием EditText коробки.

+0

Итак, если я ввожу случайное имя пользователя и пустой пароль при входе в систему, я могу подключиться независимо от регистрации? ;) – Doomsknight

+0

Большое спасибо. Теперь ясно. –

+0

@Doomsknight Ха-ха. Я ожидал, что кто-то поймает это. Я просто сосредоточился на том, чтобы показать, как это можно сделать, а не действительность метода. Хранение писем и паролей в виде открытого текста в любом случае не является хорошей идеей. Но да. Ваша точка - это то, что OP должен иметь в виду во время реализации. –

0

//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 
           } 
+0

и почему именно это работает?вы даже не заметили никаких изменений! люди должны пройти через стену кода? –

+0

Нет, это не помогает, я хотел проверить, был ли вход для входа в соответствии с комбинацией паролей, что было зарегистрировано ранее. @Cristofer Marin –

Смежные вопросы