Java 登录会话共享首选项
我能够使用共享偏好。我可以从共享首选项文件夹中存储和检索数据。但我无法在注销时将共享首选项设置为null。请指导我如何在登录中维护会话 LoginActivity.Java:- 我正在处理登录表单。。比较电子邮件id和密码后,数据存储在共享首选项中。我也可以检索数据。但如何维持会话Java 登录会话共享首选项,java,php,android,session,Java,Php,Android,Session,我能够使用共享偏好。我可以从共享首选项文件夹中存储和检索数据。但我无法在注销时将共享首选项设置为null。请指导我如何在登录中维护会话 LoginActivity.Java:- 我正在处理登录表单。。比较电子邮件id和密码后,数据存储在共享首选项中。我也可以检索数据。但如何维持会话 package com.kezinking.nupur.kezinking; import android.animation.ObjectAnimator; import android.app.Progress
package com.kezinking.nupur.kezinking;
import android.animation.ObjectAnimator;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Space;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import static android.R.attr.password;
/**
* Created by Nupur on 8/2/2016.
*/
public class LoginActivity extends AppCompatActivity {
public static final String MY_JSON = "MY_JSON";
private static final String JSON_URL = "http://kezinking.com/AndroidLogin";
EditText input_email, input_password;
Button btn_login, btnContactUs, btnWorkhr, btnDeltime, btnMoneyBack;
TextView link_signup, textViewJSON, txtcheck,value;
private static Boolean flag = false;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
public static final String Phone = "phoneKey";
public static final String emailkey = "emailKey";
public static final String UserId = "user_id";
SharedPreferences sharedpreferences;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btn_login = (Button) findViewById(R.id.btn_login);
link_signup = (TextView) findViewById(R.id.link_signup);
input_email = (EditText) findViewById(R.id.input_email);
input_password = (EditText) findViewById(R.id.input_password);
textViewJSON = (TextView) findViewById(R.id.textViewJSON);
// value=(TextView)findViewById(R.id.value);
txtcheck = (TextView) findViewById(R.id.txtcheck);
value = (TextView) findViewById(R.id.value);
//shared preference folder
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
//onClick Event on login Button
btn_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
login();
}
});
link_signup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(LoginActivity.this, SignupActivity.class);
startActivity(intent);
LoginActivity.this.getIntent();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void login() {
if (!validate()) {
onLoginFailed();
return;
} else {
getJSON(JSON_URL);
}
}
public void getJSON(String url) {
class GetJSON extends AsyncTask<String, Void, String> {
ProgressDialog loading;
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(LoginActivity.this, "Please Wait...", null, true, true);
}
@Override
protected String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
//String result=null;
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
textViewJSON.setText(s);
String jsonString = textViewJSON.getText().toString();
String email = input_email.getText().toString();
String password = input_password.getText().toString();
/** md5(password); // Enrcypting the given password **/
// final String myResult = (email) + (password);
// String value = (String.valueOf(email + password));
// System.out.println(value);
// String value=(input_email.getText().toString()+input_password.getText().toString());
//String input_email = "";
//String input_password = "";
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray result = jsonObject.getJSONArray("result");
//System.out.println("result " + result);
//iterate through json array and check if id is same with your search
//System.out.println("length " + result.length());
for (int i = 0; i < result.length(); i++) {
// System.out.println(i);
JSONObject item = result.getJSONObject(i);
String Email = item.getString("email");
String Password = item.getString("password");
//System.out.println("Email from json "+ Email);
//System.out.println("Password from json " + Password);
if (Email.equals(email) && Password.equals(password)) {
//System.out.println("Email from json"+ Email);
// System.out.println("Password from json" + Password);
String username=item.getString("username");
String userid=item.getString("user_id");
String phone_number=item.getString("con_no");
String emailSaved = item.getString("email");
// System.out.println("Email from json "+ Email);
// System.out.println("Password from json " + Password);
// System.out.println("username from json " + username);
// System.out.println("userid from json " + userid);
// System.out.println("phone_number from json " + phone_number);
SharedPreferences.Editor editor = sharedpreferences.edit();
// Store data in shared preference
editor.putString(Name, username);
editor.putString(Phone, phone_number);
editor.putString(UserId,userid);
editor.putString(emailkey, emailSaved);
editor.commit();
flag=true;
// Retrieve data from shared Preference folder
SharedPreferences prefs = getSharedPreferences(MyPREFERENCES, MODE_PRIVATE);
String show_name = prefs.getString("Name", username); // getting data-name from shared preference
String show_email=prefs.getString("emailkey", emailSaved); // retrieving data from shared preference folder
// Checking the values are coming correct from shared preference folder or not
System.out.println("Shared_preference-email " + show_email);
System.out.println("Shared_preference-username " + show_name);
// value.setText(restoredText);
onLoginSuccess();
break;
}
}
if(!flag){
onLoginFailed();
}
} catch (JSONException e) {
e.printStackTrace();
}
//here you can show the result
Log.v(this.getClass().getSimpleName(), "email = " + email);
Log.v(this.getClass().getSimpleName(), "password = " + password);
}
}
GetJSON gj = new GetJSON();
gj.execute(url);
}
/** private String md5(String password) {
MessageDigest digest;
try {
digest = MessageDigest.getInstance("MD5");
digest.reset();
digest.update(password.getBytes());
byte[] a = digest.digest();
int len = a.length;
StringBuilder sb = new StringBuilder(len << 1);
for (int i = 0; i < len; i++) {
sb.append(Character.forDigit((a[i] & 0xf0) >> 4, 16));
sb.append(Character.forDigit(a[i] & 0x0f, 16));
}
return sb.toString();
} catch (NoSuchAlgorithmException e)
{ e.printStackTrace(); }
System.out.print(password);
return password;
} **/
@Override
public void onBackPressed() {
// disable going back to the MainActivity
moveTaskToBack(true);
}
public void onLoginSuccess() {
btn_login.setEnabled(true);
if(sharedpreferences!=null){
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
LoginActivity.this.getIntent();
}
else
{
Toast.makeText(getBaseContext(), "Shared preference is null", Toast.LENGTH_LONG).show();
}
// finish();
}
public void onLoginFailed() {
Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show();
// btn_login.setEnabled(true);
}
public boolean validate() {
boolean valid = true;
String email = input_email.getText().toString();
String password = input_password.getText().toString();
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
input_email.setError("enter a valid email address");
valid = false;
} else {
input_email.setError(null);
}
if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
input_password.setError("between 4 and 10 alphanumeric characters");
valid = false;
} else {
input_password.setError(null);
}
return valid;
}
}
但这是行不通的。
请指导我如何维护登录会话。提前谢谢。希望我的问题也能帮助其他人。在您的共享首选项中存储一个布尔值当您成功登录时,以及下次发送登录活动意图之前,将其设置为true。检查布尔值是否为true或false。如果为true,跳过登录屏幕,否则显示登录屏幕。如果您的应用程序中有注销选项,则将布尔值设置为false,并再次将其保存在共享首选项中。您可以如下所示初始化共享首选项:
if(pref.getBoolean("isLogin", false)){
// Condtion gets true if you are login
}else{
// Condtion gets false if you are not login
}
假设您正在LoginActivity中将登录首选项设置为true
当您获得以下登录设置首选项时:
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
editor.putBoolean("isLogin",true);
editoe.commit();
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
editor.putBoolean("isLogin",false);
editoe.commit();
您正在LogoutActiviy中设置注销首选项。
无论何时您获得注销设置首选项,如下所示:
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
editor.putBoolean("isLogin",true);
editoe.commit();
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
editor.putBoolean("isLogin",false);
editoe.commit();
并检查您的第一页用户是否登录或不符合以下要求:
if(pref.getBoolean("isLogin", false)){
// Condtion gets true if you are login
}else{
// Condtion gets false if you are not login
}
希望它能帮助你
有关更多参考信息,您还可以参考以下链接:
您只需要在编辑器类对象上调用这两个方法
editor.clear();
editor.commit();
如果需要进一步帮助,您可以回复。祝你好运。我想在MainActivity.Java类中使用共享首选项变量。在我的MainActivity中,对于我的注销按钮,我想使用:-else if(id==R.id.nav_logout){SharedPreferences.Editor=SharedPreferences.edit();Editor.putBoolean(“isLogin”,false);Editor.commit();Intent Intent=new Intent(MainActivity.this,LoginActivity.class);startActivity(Intent);MainActivity.this.getIntent();}但它在使用SharedReference时出错。我如何在其他java类中使用它?您需要使用与登录时初始化相同的密钥初始化首选项。查看我的编辑