需要一些与SharedPreferences相关的项目建议

时间:2017-07-11 00:51:56

标签: java android android-sharedpreferences

我想记录用户并保存登录的用户名,并将其作为Toa​​st或TextView显示在MainActivity中。

以下是我目前的代码:

Session.java

public class Session {
    SharedPreferences sharepref;
    SharedPreferences.Editor editor;
    Context context;

    public Session(Context context){
        this.context = context;
        sharepref = context.getSharedPreferences("mypref", Context.MODE_PRIVATE);
        editor = sharepref.edit();
        editor.commit();
    }

    public void setLoggedin(boolean loggedin){

        editor.putBoolean("loggedInmode",loggedin);
        editor.commit();
    }

    public boolean loggedin(){
        return sharepref.getBoolean("loggedInmode", false);
    }
}

LoginActivity.java

public class LoginActivity extends AppCompatActivity{
    //private Button login, register;
    private EditText etUser, etPass;
    private DatabaseHelper dbHelper;
    private Session session;
    private static final String SALT = "50C7BC9D21";

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

        dbHelper = new DatabaseHelper(this);
        session = new Session(this);
        etUser = (EditText)findViewById(R.id.etUsername);
        etPass = (EditText)findViewById(R.id.etPassword);
        //login = (Button)findViewById(R.id.btnLogin);
        //register = (Button)findViewById(R.id.btnRegister);
        //login.setOnClickListener(this);
        //register.setOnClickListener(this);

        if(session.loggedin()){
            startActivity(new Intent(LoginActivity.this,MainActivity.class));
            finish();
        }
    }

    /*
    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.btnLogin:
                login();
                break;
            case R.id.btnRegister:
                //register();
                startActivity(new Intent(LoginActivity.this,RegisterActivity.class));
                break;
            default:

        }
    }*/

    /**
     * METHOD THAT WILL BE EXECUTED ONCE THE EXIT BUTTON IS CLICKED
     * ITS SOLO PURPOSE IS TO TERMINATE THE APPLICATION.
     * */
    public void exitApp(View v){
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(1);
    }

    /**
     * METHOD THAT WILL BE EXECUTED ONCE THE REGISTER BUTTON IS CLICKED
     * ITS SOLO PURPOSE IS TO TAKE THE USER TO THE REGISTER WINDOW.
     * */
    public void newUser(View v){
        startActivity(new Intent(LoginActivity.this,RegisterActivity.class));
    }

    /**
     * METHOD THAT WILL BE EXECUTED ONCE THE LOGIN BUTTON IS CLICKED
     * ITS SOLO PURPOSE IT TO COMPARE THE INFORMATION ENTERED IN THE EDITTEXT BOXES
     * AND SEE IF ITS EQUAL WITH THE INFORMATION STORED IN THE DATABASE.
     * */
    public void loginUser(View v){
        String user = etUser.getText().toString();
        String pass = etPass.getText().toString();

        String passwordToHash = pass;
        String generatedPassword = null;
        String finalpw = null;
        try {
            // Create MessageDigest instance for MD5
            MessageDigest md = MessageDigest.getInstance("SHA1");
            //Add password bytes to digest
            md.update(passwordToHash.getBytes());
            //Get the hash's bytes
            byte[] bytes = md.digest();
            //This bytes[] has bytes in decimal format;
            //Convert it to hexadecimal format
            StringBuilder sb = new StringBuilder();
            for(int i=0; i< bytes.length ;i++)
            {
                sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
            }
            //Get complete hashed password in hex format
            generatedPassword = sb.toString();
            finalpw = generatedPassword + SALT;
            Toast.makeText(this, finalpw, Toast.LENGTH_SHORT).show();
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        System.out.println(generatedPassword);

        //THIS WAS FIXED AROUND BECAUSE THE OTHER WAY FETCHING AND EQUALLING WITH DB AN USER COULD PASS BY WITHOUT REGESTERING.
        if(dbHelper.getUser(user,finalpw)){
            session.setLoggedin(true);
            startActivity(new Intent(LoginActivity.this, MainActivity.class));
            finish();
        }else{
            Toast.makeText(getApplicationContext(), R.string.wrong_info,Toast.LENGTH_SHORT).show();
        }
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_CODE_ADD_CONTACT = 1;
    private Session session;
    //private TaskAdapter taskAdapter;

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        session = new Session(this);
        if (!session.loggedin()) {

            logout();
        }

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_ADD_CONTACT) {
            if (resultCode == RESULT_OK) {

            }
        }

    }

    public void logout() {
        session.setLoggedin(false);
        finish();
        startActivity(new Intent(MainActivity.this, LoginActivity.class));
    }


    @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_logout) {
            logout();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

}

重复想要记录用户登录信息。具体来说,我想保存登录的用户名,并将其作为Toa​​st或TextView显示在MainActivity中。

对于我所阅读的内容,我尝试使用intent.putextra并使用bundle,它将在首次安装时运行但之后会使应用程序崩溃,所以我尝试使用sharedpreference并创建了一个会话。

我在这里有点受阻。如何在会话中保存每个不同的用户,然后在MainActivity中显示其用户名?

很抱歉,如果我的第一篇帖子出错了。

1 个答案:

答案 0 :(得分:0)

您可以制作另一个可以放入SharedPref的参数。例如,在你的set loggin中:

#1067 - Invalid default value for 'registered_at'

在获取用户名的主要活动中,您可以制作另一种方法:

public void setLoggedin(boolean loggedin, String username){

    editor.putBoolean("loggedInmode",loggedin);
    editor.putString("username",username);
    editor.commit();
}

您可以使用public boolean getUsername(){ return sharepref.getString("username", ""); }

进行调用