您好我正在按照本教程在我的应用http://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/
中添加会话但是我的应用程序有点不同,在我的应用程序中我有按照本教程的edittext登录页面,但我在导航抽屉中给出了注销选项,所以我试图添加会话,但它不是allwing。
public class LoginPage extends Activity implements OnClickListener{
private Button btn;
private EditText user;
private EditText pass;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
// Session Manager Class
SessionManager session;
// Progress Dialog
private ProgressDialog pDialog;
//JSON parser class
JSONParser jsonParser = new JSONParser();
private Button btn1;
private String userid;
private static final String LOGIN_URL = "http://mywebsite.com/webservice/applogin";
private static final String TAG_SUCCESS = "status";
private static final String TAG_LOGIN = "login";
private static String TAG_USERID="user_login_id";
private static final String TAG_SESSION="session";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login_page);
// Session Manager
session = new SessionManager(getApplicationContext());
user=(EditText)findViewById(R.id.loginmailid);
pass=(EditText)findViewById(R.id.loginpwd);
Toast.makeText(getApplicationContext(), "User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG).show();
btn=(Button)findViewById(R.id.login);
btn1=(Button)findViewById(R.id.btnreg);
btn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.login:
new AttemptLogin().execute();
session.createLoginSession("Android Hive", "anroidhive@gmail.com");
break;
case R.id.btnreg:
Intent i = new Intent(this, RegistrationForm.class);
startActivity(i);
break;
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
boolean failure = false;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginPage.this);
pDialog.setMessage("Login..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@SuppressWarnings("unused")
@Override
protected String doInBackground(String...args) {
//Check for success tag
//int success;
Looper.prepare();
String username = user.getText().toString();
String password = pass.getText().toString();
try {
//Building Parameters
//http://gujjumatch.com/webservice/applogin?email=chirag9151@gmail.com&password=123456&version=apps
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", username));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("version", "apps"));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest (
LOGIN_URL, "POST", params);
//check your log for json response
Log.d("Login attempt", json.toString());
JSONObject jobj = new JSONObject(json.toString());
final String msg = jobj.getString("msg");
TAG_USERID = jobj.getString("user_login_id");
System.out.println("MSG : " + msg);
runOnUiThread(new Runnable()
{
@Override
public void run()
{
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
});
return json.getString(TAG_SUCCESS);
//http://gujjumatch.com/login?version=apps&email=GM847903@param.in&password=123456
//JSONArray arr = json.getJSONArray("login");
//System.out.println(arr.toString());
//JSONObject arr1 = new JSONObject(json);
//String ss=arr1.getString("status");
//System.out.println(ss);
//System.out.println(arr1.getString("status"));
//String date = jObj.getString("status");
}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();
if(file_url.equals("success")) {
// Log.d("Login Successful!", json.toString());
Intent i = new Intent(LoginPage.this, MainActivity.class);
Bundle b=new Bundle();
i.putExtra("id", TAG_USERID);
startActivity(i);
}else{
//Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_LONG).show();
}
}}
我正在使用本教程中的导航抽屉http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/
答案 0 :(得分:0)
我对你的代码进行了一些修改,我在下面得到了这个代码,它对我来说很好用
LoginActivity代码:
public class LoginActivity extends Activity {
ProgressDialog pDialog;
SharedPreferences settings;
// constant for user preference
public static final String LOGN_PREF = "LoginPrefs";
private Button btnLog;
CheckBox checkBox;
private EditText etUSerName;
private EditText etPasswd;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
etUSerName = (EditText) findViewById(R.id.editTextUserName);
etPasswd = (EditText) findViewById(R.id.editTextPassword);
btnLog = (Button) findViewById(R.id.buttonEntrar);
checkBox = (CheckBox)findViewById(R.id.checkBox1);
// Recovering user info
settings = getSharedPreferences(LOGN_PREF, 0);
// Checking if has user info recorded
if(settings.getString("USERNAME", "")!=null && settings.getString("PASWORD", "")!=null) {
etUSerName.setText(settings.getString("USERNAME", ""));
etPasswd.setText(settings.getString("PASWORD", ""));
}
}
//Method to login
public void login(View v){
if(v.getId()==R.id.buttonLogin){
/**
*Calling your AsyncTask passing username and Password as parameters
*/
new AttemptLogin().execute(new String[]{etUSerName.getText().toString(), etPasswd.getText().toString()});
}
}
/**Save user info when checkbox is checked*/
public void itemClicked(View v) {
if(checkBox.isChecked()){
// Calling StartSession method
startSession();
}
}
//Method to save info during user session
public void startSession(){
//settings = getSharedPreferences(LOGN_PREF, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("USERNAME", etUSerName.getText().toString());
editor.putString("PASWORD", etPasswd.getText().toString());
editor.commit();
}
class AttemptLogin extends AsyncTask<String, String, String> {
boolean failure = false;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Login..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@SuppressWarnings("unused")
@Override
protected String doInBackground(String...args) {
//Check for success tag
//int success;
Looper.prepare();
try {
//Building Parameters
//http://gujjumatch.com/webservice/applogin?email=chirag9151@gmail.com&password=123456&version=apps
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", args[0]));
params.add(new BasicNameValuePair("password", args[1]));
params.add(new BasicNameValuePair("version", "apps"));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest (
LOGIN_URL, "POST", params);
//check your log for json response
Log.d("Login attempt", json.toString());
JSONObject jobj = new JSONObject(json.toString());
final String msg = jobj.getString("msg");
TAG_USERID = jobj.getString("user_login_id");
System.out.println("MSG : " + msg);
runOnUiThread(new Runnable()
{
@Override
public void run()
{
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
});
return json.getString(TAG_SUCCESS);
//http://gujjumatch.com/login?version=apps&email=GM847903@param.in&password=123456
//JSONArray arr = json.getJSONArray("login");
//System.out.println(arr.toString());
//JSONObject arr1 = new JSONObject(json);
//String ss=arr1.getString("status");
//System.out.println(ss);
//System.out.println(arr1.getString("status"));
//String date = jObj.getString("status");
}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();
if(file_url.equals("success")) {
/** In case the user dont check remember option*/
if(!checkBox.isChecked()){
startSession();
}
// Log.d("Login Successful!", json.toString());
Intent i = new Intent(getApplicationContext(), MainActivity.class);
Bundle b=new Bundle();
/**i.putExtra("id", TAG_USERID);*/
startActivity(i);
}else{
Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_LONG).show();
}
}}
}
LoginLayout:
<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=".LoginActivity">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerHorizontal="true"
android:layout_below="@+id/imageView">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="Name"
android:ems="10"
android:id="@+id/editTextUserName" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="senha"
android:ems="10"
android:id="@+id/editTextPassword"
android:layout_gravity="center_horizontal" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="48dp">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lembra-me"
android:id="@+id/checkBox1"
android:checked="false"
android:onClick="itemClicked"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:weightSum="1">
<Button
android:layout_width="164dp"
android:layout_height="wrap_content"
android:text="Entrar"
android:onClick="login"
android:id="@+id/buttonLogin" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Registre-se"
android:onClick="Registre_se"
android:id="@+id/buttonRegistre_se" />
</LinearLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#0099cc"
android:id="@+id/textViewProject"
android:layout_marginTop="19dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout><![CDATA[
Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button"
android:layout_gravity="center_horizontal" />
]]>
</LinearLayout>
以下是我的mainActivity代码,只需将此代码改编为mainActivity即可。您还可以使用在此tutorial上找到的drawerLayout。
MainActivity代码:
public class MainActivity extends Activity {
//Constant to get user info by shared preferences
SharedPreferences settings;
public static final String LOGN_PREF = "LoginPrefs";
// Field to setup drawerlayout
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] navMenuTitles;
private DrawerLayout mDrawerlayout;
private ListView mDrawerList;
public void onCreate(Bundle ic){
super.onCreate(ic);
setContentView(R.layout.mainlayout);
settings = getSharedPreferences(LOGN_PREF, 0);
//setting-up drawer menu
mTitle = mDrawerTitle = getTitle();
List<DrawerPrincipalIten> it = createItens();
ArrayAdapter<?> ad = new DrawerPrincipalAdapter(this, R.layout.tela_principal_item_drawer, it);
mDrawerlayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer_principal);
mDrawerList.setAdapter(ad);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Log.d(TAG, String.valueOf(position));
selectItem(position);
}
});
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerlayout,
R.drawable.ic_drawer, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
){
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
//calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
//calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerlayout.setDrawerListener(mDrawerToggle);
if (ic == null) {
}
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
}
public List<DrawerPrincipalIten> createItens(){
String nome = settings.getString("USERNAME", "");
List l = new ArrayList();
l.add( new DrawerPrincipalIten(nome, R.drawable.ic_action_person, false));
l.add( new DrawerPrincipalIten("Settings",R.drawable.ic_action_settings, false));
l.add( new DrawerPrincipalIten("Upload",R.drawable.ic_action_upload, false));
l.add( new DrawerPrincipalIten("Download",R.drawable.ic_action_download, false));
l.add( new DrawerPrincipalIten("Logout",R.drawable.ic_sair, false));
return l;
}
/*
* (non-Javadoc)
* @see android.app.Activity#onPostCreate(android.os.Bundle)
* Metodos para tratamento do botão toggle (Icone da App) para abrir menu lateral
*/
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle, if it returns
// true, then it has handled the app icon touch event
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
private void selectItem(int position) {
// Create a new fragment and specify the planet to show based on position
switch(position){
case 0 :
break;
case 1 :
break;
case 2:
break;
case 3:
break;
case 4:
// Open a dialog to ask if user want go out
logOffDialog();
break;
}
}
public void logOffDialog(){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setIcon(R.drawable.ic_sair);
alert.setTitle("Logout");
alert.setMessage("You realy whant go out?");
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
/** Calling method to end user session*/
endSection();
finish();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
alert.show();
}
public void endSection(){
SharedPreferences.Editor editor = settings.edit();
editor.clear();
editor.commit();
}
}
MainActivity布局:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</android.support.v4.view.ViewPager>
<!-- android:layout_width="240dp" -->
<ListView
android:id="@+id/left_drawer_principal"
android:layout_width="290dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:choiceMode="singleChoice"
android:divider="@android:color/transparent"
android:dividerHeight="0dp" />
</android.support.v4.widget.DrawerLayout>
我希望它可以帮助你