2017-03-14 44 views
1

我知道在android中有n个示例用于共享首选项,但是我想要使用JSON在共享首选项和数据库中注册和存储信息。然后从JSON中获取数据并使用这些凭据登录。如果用户已经登录了打开的主要活动,请进入初始屏幕,然后打开登录活动。请通过我的详细代码:我想在共享首选项中存储注册和登录信息android

RegisterActivity:

public class RegisterActivity extends AppCompatActivity implements ServerRequests.Registereponse { 

    private EditText password, phone, email; 
    public static EditText name; 
    ServerRequests serverRequests; 
    JSONParser jsonParser; 
    private Button registerButton; 
    TextView alreadyMember; 
    Editor editor; 
    UserSession session; 

    SharedPreferences sharedPreferences; 
    public static final String MyPREFERENCES = "MyPrefs"; 
    public static final String Name1 = "nameKey"; 
    public static final String Phone1 = "phoneKey"; 
    public static final String Email1 = "emailKey"; 
    public static final String Password1 = "passwordKey"; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_register); 

     jsonParser = new JSONParser(); 
     serverRequests = new ServerRequests(getApplicationContext()); 
     serverRequests.setRegistereponse(this); 


     alreadyMember = (TextView) findViewById(R.id.alreadyMember); 

     name = (EditText) findViewById(R.id.FName); 
     phone = (EditText) findViewById(R.id.PhoneNum); 
     email = (EditText) findViewById(R.id.mail); 
     password = (EditText) findViewById(R.id.password); 
     registerButton = (Button) findViewById(R.id.email_sign_in_button); 

     sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); 

     registerButton.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       CharSequence temp_emailID = email.getText().toString(); 
       if (name.getText().toString().length() == 0) { 
        name.setError("Please enter your name"); 
        name.requestFocus(); 

       } else if (phone.getText().toString().length() == 0) { 
        phone.setError("Please enter your phone number"); 
        phone.requestFocus(); 

       } else if (!isValidEmail(temp_emailID)) { 
        email.setError("Please enter valid email"); 
        email.requestFocus(); 

       } else if (password.getText().toString().length() == 0) { 
        password.setError("Please enter password"); 
        password.requestFocus(); 

       } else { 


        try { 
         String Name = name.getText().toString(); 
         String Email = email.getText().toString(); 
         String Password = password.getText().toString(); 
         String Phone = phone.getText().toString(); 

         JSONObject obj = jsonParser.makeRegisterJson(Name, Email, Password, Long.parseLong(Phone)); 
         Log.e("final Json", obj.toString()); 
         serverRequests.register(obj); 


         SharedPreferences.Editor editor = sharedPreferences.edit(); 

         editor.putString(Name1, Name); 
         editor.putString(Email1, Email); 
         editor.putString(Password1, Password); 
         editor.putString(Phone1, Phone); 
         editor.commit(); 
         // Toast.makeText(RegisterActivity.this, "Registered Successfully!", Toast.LENGTH_LONG).show(); 


        } catch (Exception e) { 

        } 
       } 

       // startActivity(new Intent(RegisterActivity.this, LoginActivity.class)); 

      } 
     }); 

     alreadyMember.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 

       startActivity(new Intent(RegisterActivity.this, LoginActivity.class)); 
       finish(); 
      } 
     }); 

    } 


    @Override 
    public void onRegsiterReposne(JSONObject object) { 
     Toast.makeText(RegisterActivity.this, "hiii" + object.toString(), Toast.LENGTH_SHORT).show(); 

    } 

    public final static boolean isValidEmail(CharSequence target) { 
     if (TextUtils.isEmpty(target)) { 
      return false; 
     } else { 
      return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches(); 
     } 
    } 

} 

LoginActivity:

public class LoginActivity extends AppCompatActivity implements ServerRequests.Loginreponse { 

    private static final String PREFER_NAME = "Reg"; 

    private Button email_sign_in_button; 
    private EditText email, password; 
    private TextView notMember, forgotPass; 

    UserSession session; 
    private SharedPreferences sharedPreferences; 

    ServerRequests serverRequests; 
    JSONParser jsonParser; 


    @Override 
    protected void onCreate(@Nullable Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_login); 

     jsonParser = new JSONParser(); 
     serverRequests = new ServerRequests(getApplicationContext()); 
     serverRequests.setLoginreponse(this); 

     notMember = (TextView) findViewById(R.id.notMember); 
     forgotPass = (TextView) findViewById(R.id.forgotPass); 

     notMember.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 

       startActivity(new Intent(LoginActivity.this, RegisterActivity.class)); 
       finish(); 
      } 
     }); 

     forgotPass.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 

       startActivity(new Intent(LoginActivity.this, ForgotPassword.class)); 

      } 
     }); 


     // get Email, Password input text 
     email = (EditText) findViewById(R.id.email); 
     password = (EditText) findViewById(R.id.pass); 


     // User Login button 
     email_sign_in_button = (Button) findViewById(R.id.login); 

     sharedPreferences = getSharedPreferences(PREFER_NAME, MODE_PRIVATE); 


     // Login button click event 
     email_sign_in_button.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View view) { 

       try { 
        String Email = email.getText().toString(); 
        String Password = password.getText().toString(); 

        JSONObject obj = jsonParser.makeLoginJson(Email, Password); 
        Log.e("final Json", obj.toString()); 
        serverRequests.login(obj); 


       } catch (Exception e) { 

       } 

       // startActivity(new Intent(LoginActivity.this, MainActivity.class)); 
       // finish(); 

      } 
     }); 
    } 

    @Override 
    public void onLoginReposne(JSONObject object) { 

     Toast.makeText(LoginActivity.this, "helloo" + object.toString(), Toast.LENGTH_SHORT).show(); 


     if (object.toString().contains("true")) { 

      Toast.makeText(LoginActivity.this, "Logged in..", Toast.LENGTH_SHORT).show(); 
      startActivity(new Intent(LoginActivity.this, MainActivity.class)); 
      finish(); 

     } 


    } 
} 

闪屏:

public class SplashScreen extends Activity { 

    Thread splashTread; 
    SharedPreferences preferences; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_splash_screen); 
     StartAnimations(); 
    } 

    public void onAttachedToWindow() { 
     super.onAttachedToWindow(); 
     Window window = getWindow(); 
     window.setFormat(PixelFormat.RGBA_8888); 
    } 

    private void StartAnimations() { 
     Animation anim = AnimationUtils.loadAnimation(this, R.anim.alpha); 
     anim.reset(); 
     LinearLayout l = (LinearLayout) findViewById(R.id.lin_lay); 
     l.clearAnimation(); 
     l.startAnimation(anim); 

     anim = AnimationUtils.loadAnimation(this, R.anim.translate); 
     anim.reset(); 

     ImageView iv = (ImageView) findViewById(R.id.splashImage); 
     iv.clearAnimation(); 
     iv.startAnimation(anim); 

    /* TextView tv = (TextView) findViewById(R.id.splashText); 
     tv.clearAnimation(); 
     tv.startAnimation(anim);*/ 


     splashTread = new Thread() { 
      @Override 
      public void run() { 
       try { 
        int waited = 0; 
        // Splash screen pause time 
        while (waited < 3500) { 
         sleep(100); 
         waited += 100; 
        } 

        startNextScreen(); 


       } catch (InterruptedException e) { 
        // do nothing 
       } finally { 
        SplashScreen.this.finish(); 
       } 

      } 
     }; 
     splashTread.start(); 

    } 

    private void startNextScreen() { 
     preferences = getSharedPreferences("TrainingApp", MODE_PRIVATE); 
     String userLoginStatus = preferences.getString("userLoginStatus", "no"); 
     if (userLoginStatus.equals("no")) { 
      Intent intent = new Intent(SplashScreen.this, 
        LoginActivity.class); 
      intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); 
      startActivity(intent); 
      SplashScreen.this.finish(); 
     } else { 
      Intent intent = new Intent(SplashScreen.this, 
        MainActivity.class); 
      intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); 
      startActivity(intent); 
      SplashScreen.this.finish(); 
     } 

    } 

} 

JSONParser类:

public class JSONParser { 

    //----------For Register 

    public JSONObject makeRegisterJson(String name, String email, String password, long phone) throws JSONException { 

     JSONObject object = new JSONObject(); 

     object.put("name", name); 
     object.put("email", email); 
     object.put("password", password); 
     object.put("phone", phone); 
     // if its in array------ 
     /*JSONObject finalObject=new JSONObject(); 
     finalObject.put("request",object); 
     return finalObject;*/ 
     return object; 
    } 

    //--------For Login-------------------------------------------------------- 

    public JSONObject makeLoginJson(String Name, String password) throws JSONException { 

     JSONObject object = new JSONObject(); 

     object.put("userName", Name); 
     object.put("password", password); 
     /*JSONObject finalObject=new JSONObject(); 
     finalObject.put("request",object); 
     return finalObject;*/ 
     return object; 
    } 
} 

ServerRequests类:

// ---------------- for register------------------------------------------------------------------------------ 

    public void setRegistereponse(Registereponse registereponse) { 
     this.registereponse = registereponse; 
    } 

    private Registereponse registereponse; 

    public interface Registereponse { 
     void onRegsiterReposne(JSONObject object); 
    } 

    public void register(JSONObject jsonObject) { 


     JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Services.REGISTER_URL, jsonObject, 
       new Response.Listener<JSONObject>() { 
        @Override 
        public void onResponse(JSONObject response) { 
         try { 
          Log.e("Json response", "" + response); 
          boolean b = response.getBoolean("success"); 

          if (registereponse != null) { 
           registereponse.onRegsiterReposne(response); 

          } 

         } catch (Exception e) { 
          e.printStackTrace(); 
         } 
        } 

       }, 
       new Response.ErrorListener() { 
        @Override 
        public void onErrorResponse(VolleyError error) { 
         Log.e("Error ", "" + error); 
        } 
       } 
     ); 

     queue.add(jsonObjectRequest); 
    } 


    // --------------For Login --------------------------------------------------------------------------- 

    public void setLoginreponse(Loginreponse loginreponse) { 
     this.loginreponse = loginreponse; 
    } 

    private Loginreponse loginreponse; 

    public interface Loginreponse { 
     void onLoginReposne(JSONObject object); 
    } 

    public void login(JSONObject jsonObject) { 


     JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Services.LOGIN_URL, jsonObject, 
       new Response.Listener<JSONObject>() { 
        @Override 
        public void onResponse(JSONObject response) { 
         try { 
          Log.e("Json response", "" + response); 
          boolean b = response.getBoolean("success"); 

          if (loginreponse != null) { 
           loginreponse.onLoginReposne(response); 

          } 

         } catch (Exception e) { 
          e.printStackTrace(); 
         } 
        } 

       }, 
       new Response.ErrorListener() { 
        @Override 
        public void onErrorResponse(VolleyError error) { 
         Log.e("Error ", "" + error); 
        } 
       } 
     ); 

     queue.add(jsonObjectRequest); 
    } 

UserSession类:

public class UserSession { 
    // Shared Preferences reference 
    SharedPreferences pref; 

    // Editor reference for Shared preferences 
    Editor editor; 

    // Context 
    Context _context; 

    // Shared preferences mode 
    int PRIVATE_MODE = 0; 

    // Shared preferences file name 
    public static final String PREFER_NAME = "Reg"; 

    // All Shared Preferences Keys 
    public static final String IS_USER_LOGIN = "IsUserLoggedIn"; 

    // User name (make variable public to access from outside) 
    public static final String KEY_NAME = "Name"; 

    // Email address (make variable public to access from outside) 
    public static final String KEY_EMAIL = "Email"; 

    // password 
    public static final String KEY_PASSWORD = "Password"; 

    public static final String KEY_PHONE = "PhoneNumber"; 

    public static final String KEY_QUALIFICATION = "Qualification"; 


    // Constructor 
    public UserSession(Context context) { 
     this._context = context; 
     pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE); 
     editor = pref.edit(); 
    } 

    //Create login session 
    public void createUserLoginSession(String uEmail, String uPassword) { 
     // Storing login value as TRUE 
     editor.putBoolean(IS_USER_LOGIN, true); 

     // Storing name in preferences 
     editor.putString(KEY_EMAIL, uEmail); 

     // Storing email in preferences 
     editor.putString(KEY_PASSWORD, uPassword); 

     // commit changes 
     editor.commit(); 
    } 

    /** 
    * Check login method will check user login status 
    * If false it will redirect user to login page 
    * Else do anything 
    */ 
    public boolean checkLogin() { 
     // Check login status 
     if (!this.isUserLoggedIn()) { 

      // user is not logged in redirect him to Login Activity 
      Intent i = new Intent(_context, LoginActivity.class); 

      // Closing all the Activities from stack 
      i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

      // Add new Flag to start new Activity 
      i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 

      // Staring Login Activity 
      _context.startActivity(i); 

      return true; 
     } 
     return false; 
    } 


    /** 
    * Get stored session data 
    */ 
    public HashMap<String, String> getUserDetails() { 

     //Use hashmap to store user credentials 
     HashMap<String, String> user = new HashMap<String, String>(); 

     // user name 
     user.put(KEY_NAME, pref.getString(KEY_NAME, null)); 

     // user email id 
     user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null)); 

     user.put(KEY_PASSWORD, pref.getString(KEY_PASSWORD, null)); 

     user.put(KEY_PHONE, pref.getString(KEY_PHONE, null)); 

     user.put(KEY_QUALIFICATION, pref.getString(KEY_QUALIFICATION, null)); 

     // return user 
     return user; 
    } 

    /** 
    * Clear session details 
    */ 
    public void logoutUser() { 

     // Clearing all user data from Shared Preferences 
     editor.clear(); 
     editor.commit(); 

     // After logout redirect user to MainActivity 
     Intent i = new Intent(_context, LoginActivity.class); 

     // Closing all the Activities 
     i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

     // Add new Flag to start new Activity 
     i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 

     // Staring Login Activity 
     _context.startActivity(i); 
    } 


    // Check for login 
    public boolean isUserLoggedIn() { 
     return pref.getBoolean(IS_USER_LOGIN, false); 
    } 
} 
+0

_I要存储注册和android_确定在共享偏好的登录信息,什么是你的问题在这里? – JonZarate

+0

@JonZarate我想使用共享首选项存储信息,并使用来自JSON的数据登录。如果用户已经登录去主要活动其他启动屏幕 – Sallu

+0

我知道你想要做什么,我不知道你在哪里遇到麻烦。 _it不工作_不是一个有效的问题。 – JonZarate

回答

3

在登录时全成把这个代码:

prefs = getSharedPreferences("logindetail", 0); 
         SharedPreferences.Editor edit = prefs.edit(); 
         edit.putString("userLoginStatus", "yes"); 
         edit.commit(); 

在注销利用这个时间:

prefs = getSharedPreferences("logindetail", 0); 
SharedPreferences.Editor edit = prefs.edit(); 
           edit.clear(); 
           edit.commit(); 

而此时如果用户登录或不使用下面的代码检查的时间:

Loginprefs = getApplicationContext().getSharedPreferences("logindetail", 0); 
      userLoginStatus = Loginprefs.getString("userLoginStatus", null); 
if(userLoginStatus.tostring().equals("yes")){ 
    //the user is login 
}else{ 
    //user is logout 
} 

希望这有助于你

+0

是的!它帮助,谢谢! – Sallu

+0

欢迎。高兴地帮助你:) :) –