一次使用共享首选项登录?

时间:2015-12-24 14:50:23

标签: android login sharedpreferences

这可能是重复的问题,但我仍然无法找到解决方案,因为我是新的使用共享偏好登录活动我的要求它不应该显示登录页面,除非我们注销我怎么能这样做到目前为止我有什么尝试过

主要活动:

package first.service.precision.servicefirst;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
  //  public EditText password, userName;
    Button login, resister;
    ProgressBar progressbar;

public static String s1,s2;
    TextView tv;
    public static final String pref="login";
    String TAG = "Fails";
    String url = "http://172.16.7.203/sfAppServices/SF_UserLogin.svc";
    private ModelLogin Result;
    SharedPreferences sharedPreferences;
   private SharedPreferences sharedpreferences;
  //  public static final String MyPREFERENCES = "MyPrefs" ;
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedPreferences shared=getSharedPreferences(pref,0);
        Boolean logins=shared.getBoolean("do",false);

        if(logins){
            Intent intent = new Intent(getApplicationContext(), Main2Activity.class);
            startActivity(intent);
        }


        setContentView(R.layout.activity_main);
   final EditText     userName = (EditText) findViewById(R.id.txtEmployeeCode);
        final EditText      password = (EditText) findViewById(R.id.password);


     login = (Button) findViewById(R.id.btnsignin);
        userName.setBackgroundResource(R.drawable.colorfoucs);
        ConnectivityManager cn = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo nf = cn.getActiveNetworkInfo();
        if (nf != null && nf.isConnected() == true) {
            Toast.makeText(this, "Network Available", Toast.LENGTH_LONG).show();
        }
        else
        {
            showAlertDialog(MainActivity.this, "No Network", "Please Check Your Network Connectivity", true);
        }
        //}

        final ConnectionDetector cd = new ConnectionDetector(getApplicationContext());

        login.setOnClickListener(new View.OnClickListener()
        {

            public void onClick(View v) {
              //  sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
                progressbar = (ProgressBar) findViewById(R.id.progressBar);
                progressbar.setVisibility(View.VISIBLE);
                s1 = userName.getText().toString();
                s2 = password.getText().toString();
         SharedPreferences     sharedPreferences=getSharedPreferences(pref, 0);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putBoolean("do",true);
                 editor.putString("yog",s1);
                editor.putString("pass",s2);
                editor.commit();

                if (s1.equals("")) {
                    userName.setError("Enter Employee Code");
                }
                if (s2.equals("")) {
                    password.setError("Enter Password");

                }
                Intent intent = new Intent(getApplicationContext(), Main2Activity.class);
                Toast.makeText(MainActivity.this, "Welcome_"  +""+  s1, Toast.LENGTH_SHORT).show();
                startActivity(intent);
/*                RestAdapter adapter = new RestAdapter.Builder().setEndpoint(url).build();
                RetrofitRest retro = adapter.create(RetrofitRest.class);
                retro.getResult(s1, s2, new Callback<ModelLogin>() {
                    @Override
                    public void success(ModelLogin modelLogin, Response response) {
                        if (modelLogin.getResult().equals(1)||modelLogin.getModuleID().equals(1)) {


                            progressbar.setVisibility(View.INVISIBLE);
                        }
                    }

                    @Override
                    public void failure(RetrofitError error) {
                        progressbar.setVisibility(View.INVISIBLE);

                        Toast.makeText(MainActivity.this, "Login Fails", LENGTH_SHORT).show();
                    }
                });*/


            }

        });

      //  if(sharedpreferences.contains(s1)) {
          //


    }















    public void showAlertDialog(Context context, String title, String message, Boolean status) {
        AlertDialog alertDialog = new AlertDialog.Builder(context).create();

        // Setting Dialog Title
        alertDialog.setTitle(title);

        // Setting Dialog Message
        alertDialog.setMessage(message);

        // Setting alert dialog icon


        // Setting OK Button
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

}















    public void showAlertDialog(Context context, String title, String message, Boolean status) {
        AlertDialog alertDialog = new AlertDialog.Builder(context).create();

        // Setting Dialog Title
        alertDialog.setTitle(title);

        // Setting Dialog Message
        alertDialog.setMessage(message);

        // Setting alert dialog icon


        // Setting OK Button
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

}

它只是行为不端,就像它第一次从第二次重定向到新的登录屏幕进入主屏幕。然后知道在哪里做错了如果有人找到我的答案的解决方案将会非常有用

4 个答案:

答案 0 :(得分:3)

尝试在没有布局的情况下制作启动器活动,然后在此处进行pref检查并开始下一个活动。

  • 启动器活动(如果凭据存在) - &gt; MainActivity

  • 启动器活动(如果凭据不存在) - &gt; LoginActivity

StartActivity.java

public class StartActivity extends AppCompatActivity {

private static final String PREF_LOGIN = "LOGIN_PREF";
private static final String KEY_CREDENTIALS = "LOGIN_CREDENTIALS";


@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    SharedPreferences preferences = getSharedPreferences(PREF_LOGIN, MODE_PRIVATE);

    Intent intent = null;
    if(preferences.contains(KEY_CREDENTIALS)){              //if user is currently logged in;
        intent = new Intent(this, MainActivity.class);
    }else {                                                 //if user is not yet logged in;
        intent = new Intent(this, LoginActivity.class);
    }
    startActivity(intent);
}

}

LoginActivity.java

public class LoginActivity extends AppCompatActivity {

public static final String PREF_LOGIN = "LOGIN_PREF";
public static final String KEY_CREDENTIALS = "LOGIN_CREDENTIALS";

private Button loginButton;

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

    //...

    loginButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            //call login api...


            //on your sucess callback; we save the credentials...
            /*
            SharedPreferences.Editor editor = getSharedPreferences(PREF_LOGIN, MODE_PRIVATE).edit();
            editor.putString(KEY_CREDENTIALS, "DUMMY CREDENTIALS");
            editor.commit();
            */

            //on your failure callback; we clear the credentials...

            /*
            SharedPreferences.Editor editor = getSharedPreferences(PREF_LOGIN, MODE_PRIVATE).edit();
            editor.clear();
            editor.commit();
            */
        }


    });
}

}

答案 1 :(得分:1)

您可以尝试以下代码:

您可以使用如下所示的布尔变量并检查它是否解决了您的问题:

login.setOnClickListener中的

具有以下代码:

 SharedPreferences sharedPreferences = getSharedPreferences("MyLogin.txt", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putBoolean("FirstLogin", true);
                editor.commit();

并在onCreate中有以下代码:

SharedPreferences sharedPreferences = getSharedPreferences("MyLogin.txt", Context.MODE_PRIVATE);
         Boolean loginCheck = sharedPreferences.getBoolean("FirstLogin", false);
              if (loginCheck){

                  intent = new Intent(getApplicationContext(), Main2Activity.class);
                   startActivity(intent);
              }

答案 2 :(得分:0)

使用共享首选项,您可以使用任何键作为标志来检查其首次登录。例如,如果你拿一个键,则logged_in是一个键,那么在开始时将其设置为false或null。当用户第一次登录时,将其设置为某个值,如true或您想要的键值。下次检查此标志是否为true或您先前设置的值和id是否已设置,无需登录。

//相同的代码段:

SharedPreferences pref= getSharedPreferences(MODE_PRIVATE);
Editor editor= pref.edit();
editor.putBoolean("some key" ,false);
//Now when user logs in :
editor.put("some key", true);
//Now for the next login:
if(pref.getBoolean("some key")==true){

// Do not ask for login
}else{
//Ask for login
}

答案 3 :(得分:0)

  

oncreate就是这样,假设欢迎屏幕是你的发射器活动

private static final String PREF_LOGIN = "LOGIN_PREF";
private static final String USER_EMAIL = "EMAIL_ADDRESS";
private static final String USER_PASSWORD = "PASSWORD";
SharedPreferences preferences = getSharedPreferences(PREF_LOGIN, MODE_PRIVATE);
           Intent intent = null; 
            if(preferences.contains(USER_EMAIL)&&preferences.contains(USER_PASSWORD)){              
                    intent = new Intent(WelcomeScreen.this,MainMenu.class);//if login
                }else {                                             
                    intent = new Intent(WelcomeScreen.this,LoginScreen.class);//if not login
                }
                startActivity(intent);
                WelcomeScreen.this.finish()
  

现在登录您的登录活动

@Override
        public void onResponse(String response) {//supose response from server
            if(response.contains("sucess")) {

                SharedPreferences.Editor editor = getSharedPreferences(PREF_LOGIN, MODE_PRIVATE).edit();
                editor.putString(USER_EMAIL,email);
                editor.putString(USER_PASSWORD,passworde);
                editor.commit();

             startActivity(new Intent(LoginScreen.this,MainMenu.class));
            }
        }
  

现在如果用户想要注销,则表单共享首选项

    @Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id=item.getItemId();
    if(id==R.id.logout)
    {

        SharedPreferences.Editor editor = getSharedPreferences("LOGIN_PREF",getApplicationContext().MODE_PRIVATE).edit();
        editor.clear();
        editor.commit();



                if (editor.commit()) {
                    Toast.makeText(getApplicationContext(), "Logout Successfully", Toast.LENGTH_LONG).show();

                    startActivity(new Intent(MainMenu.this, LoginScreen.class));//open login activity on successful logout 
                }

    }
    return true;
}