我正在使用共享首选项来存储用户数据,并且在我的开始屏幕中,我想检查用户名是否已经登录,当用户仍未注销时,它将重定向到UserView.java应用程序启动,否则它将转到LoginActivity.java
我使用这些教程作为参考: Android Hive Tutorial Shared Pref,和 Android example tutorial Shared Pref ..
但是当我退出我的活动而没有退出时,下次我打开我的应用程序时它的状态会被注销(就像会话已经结束,虽然我还没有从我的应用程序注销),
我应该怎么做才能解决这个问题,所以每当我退出我的应用程序(没有注销)时,我的数据仍然存在于共享的pref中,并且会重定向到UserView.java,我的代码是否犯了错误?< / p>
这些是我的代码:
userSessionManager.java
package com.thesis.teamizer;
import java.util.HashMap;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class userSessionManager {
// Shared Preferences Reference
SharedPreferences CurrentSession;
// Editor Reference for Editing Shared Preferences
Editor editor;
// Context Reference
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharef Preferences Name
public static String PrefName = "MyUsername";
// All Shared Preferences Keys
private static final String IS_USER_LOGIN = "IsUserLoggedIn";
// User name (make variable public to access from outside)
public static final String KEY_USERNAME = "username";
// Constructor
public userSessionManager(Context context) {
this._context = context;
CurrentSession = _context.getSharedPreferences(PrefName, PRIVATE_MODE);
editor = CurrentSession.edit();
}
public void createUserLogin(String username) {
// User has already login
editor.putBoolean(IS_USER_LOGIN, true);
// Storing username in pref
editor.putString(KEY_USERNAME, username);
// Editor ready to execute the previous codes
editor.commit();
}
public boolean checkLogin() {
// Check login status. If the user is not logged in
if (!this.isUserLoggedIn()) {
return true;
}
return false;
}
// Read session using hashmap
public HashMap<String, String> getUserDetails() {
// Use hashmap to store user credentials
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_USERNAME, CurrentSession.getString(KEY_USERNAME, null));
// return user
return user;
}
public void logOut() {
// clearing all data from Shared pref
editor.remove(KEY_USERNAME);
editor.clear();
editor.commit();
}
// Will check if the user is Login or not by getting the boolean of
// IS_USER_LOGIN from CurrentSession(pref)
private boolean isUserLoggedIn() {
// TODO Auto-generated method stub
return CurrentSession.getBoolean(IS_USER_LOGIN, false);
}
}
LoginActivity.java
package com.thesis.teamizer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends Activity implements View.OnClickListener {
private EditText etUsername;
private EditText etPassword;
private Button bLogin, bRegis, bAdmin;
userSessionManager session;
String loginUrl;
JSONParser jsonParser = new JSONParser();
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private ProgressDialog pDialog;
String Username;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login_screen);
Declaration();
bLogin.setOnClickListener(this);
bRegis.setOnClickListener(this);
bAdmin.setOnClickListener(this);
if (session.checkLogin()) {
Intent intent = new Intent("com.thesis.teamizer.USERVIEW");
finish();
startActivity(intent);
}
}
private void Declaration() {
// TODO Auto-generated method stub
etUsername = (EditText) findViewById(R.id.etLoginUsername);
etPassword = (EditText) findViewById(R.id.etLoginPassword);
bLogin = (Button) findViewById(R.id.bLogin);
bRegis = (Button) findViewById(R.id.bRegister);
bAdmin = (Button) findViewById(R.id.bAdminadmin);
session = new userSessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
Username = user.get(userSessionManager.KEY_USERNAME);
myIP ip = new myIP();
String myIp = ip.getIp();
String thisPhp = "doLogin.php";
loginUrl = myIp + thisPhp;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bLogin:
new AttemptLogin().execute();
break;
case R.id.bRegister:
Intent i = new Intent("com.thesis.teamizer.REGISTRATIONACTIVITY");
startActivity(i);
break;
}
class AttemptLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(loginUrl, "POST",
params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
String currentLoginUsername = username;
session.createUserLogin(currentLoginUsername);
Intent intent = new Intent("com.thesis.teamizer.USERVIEW");
finish();
startActivity(intent);
String sukses = "Sukses login";
return sukses;
} else if (success == 0) {
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
Toast.makeText(getApplicationContext(), file_url,
Toast.LENGTH_SHORT).show();
}
}
}
UserView.java
package com.thesis.teamizer;
import java.util.HashMap;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class UserView extends Activity implements View.OnClickListener {
public Button createGr, viewGr, createAn, viewAn, notification, logout,
calendar, createEvent, myEvent, createTask, myTask;
public String Username;
userSessionManager session;
Intent i;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.user_view);
sessionAndDeclaration();
createGr.setOnClickListener(this);
viewGr.setOnClickListener(this);
createAn.setOnClickListener(this);
viewAn.setOnClickListener(this);
notification.setOnClickListener(this);
logout.setOnClickListener(this);
createEvent.setOnClickListener(this);
calendar.setOnClickListener(this);
myEvent.setOnClickListener(this);
createTask.setOnClickListener(this);
myTask.setOnClickListener(this);
}
private void sessionAndDeclaration() {
// TODO Auto-generated method stub
session = new userSessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
// get name
Username = user.get(userSessionManager.KEY_USERNAME);
TextView a = (TextView) findViewById(R.id.tvUserVUsername);
a.setText(Username);
createGr = (Button) findViewById(R.id.bCreateGroup);
viewGr = (Button) findViewById(R.id.bViewMyGroup);
createAn = (Button) findViewById(R.id.bCreateAnnouncement);
viewAn = (Button) findViewById(R.id.bViewMyAnnouncement);
notification = (Button) findViewById(R.id.bNotification);
logout = (Button) findViewById(R.id.bDoLogout);
calendar = (Button) findViewById(R.id.bGoToMyCalendar);
createEvent = (Button) findViewById(R.id.bCreateEvent);
myEvent = (Button) findViewById(R.id.bGoToMyEvent);
createTask = (Button) findViewById(R.id.bGoToCreateTask);
myTask = (Button) findViewById(R.id.bGoToMyTask);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bCreateGroup:
i = new Intent("com.thesis.teamizer.CREATEGROUPACTIVITY");
startActivity(i);
break;
case R.id.bViewMyGroup:
i = new Intent("com.thesis.teamizer.MYGROUPACTIVITY");
startActivity(i);
break;
case R.id.bCreateAnnouncement:
i = new Intent("com.thesis.teamizer.CREATEANNOUNCEMENTACTIVITY");
startActivity(i);
break;
case R.id.bViewMyAnnouncement:
i = new Intent("com.thesis.teamizer.VIEWALLANNOUNCEMENT");
startActivity(i);
break;
case R.id.bNotification:
i = new Intent("com.thesis.teamizer.NOTIFICATION");
startActivity(i);
break;
case R.id.bDoLogout:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to Logout?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
finish();
session.logOut();
Intent i = new Intent(
"com.thesis.teamizer.LOGINACTIVITY");
// 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
startActivity(i);
finish();
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
break;
case R.id.bGoToMyCalendar:
i = new Intent("com.thesis.teamizer.VIEWCALENDAR");
startActivity(i);
break;
case R.id.bCreateEvent:
i = new Intent("com.thesis.teamizer.CREATEEVENT");
startActivity(i);
break;
case R.id.bGoToMyEvent:
i = new Intent("com.thesis.teamizer.MYEVENT");
startActivity(i);
break;
case R.id.bGoToCreateTask:
i= new Intent("com.thesis.teamizer.CREATETASK");
startActivity(i);
break;
case R.id.bGoToMyTask:
i = new Intent("com.thesis.teamizer.MYTASK");
startActivity(i);
break;
}
}
}