登录功能:共享首选项

时间:2020-06-14 13:34:49

标签: android android-studio kotlin sharedpreferences

package com.example.myapplication

import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.icu.util.VersionInfo
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.renderscript.Sampler
import android.text.LoginFilter
import android.util.Log
import android.view.View
import android.widget.*
import kotlinx.android.synthetic.main.activity_main.*
import java.util.concurrent.LinkedBlockingDeque

class MainActivity : AppCompatActivity() {






    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val username = findViewById<EditText>(R.id.ET1).toString()
        val password = findViewById<EditText>(R.id.ET2).toString()

        val username1 = getSharedPreferences("username", Context.MODE_PRIVATE)
        username1.edit().putString("username","").apply()
        val password1 = getSharedPreferences("password", Context.MODE_PRIVATE)
        password1.edit().putString("password", "").apply()
        val rememberme = findViewById<CheckBox>(R.id.checkBox)
        val loginbutton = findViewById<Button>(R.id.LoginButton)
        val register = findViewById<TextView>(R.id.textView2)




        if(username.equals("admin")){

            val a = username1.getString(username,"").toString()
            Log.i("Usernmae is ", a)
            loginbutton.setOnClickListener {
                val intent = Intent(this, ListActivity::class.java)
                startActivity(intent)
            }

        }
        else{
            Toast.makeText(this,"Invalid Credentials",Toast.LENGTH_SHORT).show()
        }
        rememberme.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) {
                val pf = getSharedPreferences("checkbox", Context.MODE_PRIVATE)
                val ed = pf.edit()
                ed.putString("remember", "True")
                ed.apply()
                Toast.makeText(this, "Checked", Toast.LENGTH_LONG).show()

            } else if (!isChecked) {
                val pf = getSharedPreferences("checkbox", Context.MODE_PRIVATE)
                val ed = pf.edit()
                ed.putString("remember", "False")
                ed.apply()
                Toast.makeText(this, "Unchecked", Toast.LENGTH_LONG).show()
            }
        }

        /*register.setOnClickListener {
            val intent =Intent(this, Registration:: class.java)
            startActivity(intent)
        }*/
    }


    }












        /*val pf = getSharedPreferences("checkbox", Context.MODE_PRIVATE)
        val checkbox = pf.getString("remember", "")




        }*/



        /*

            }

        }
    }*/

我正在尝试向我的应用添加登录功能。

用户可以注册的地方,他/她的数据仅保留在他们的设备上。他们选中“记住我”按钮后,就不必每次都登录。

但是,该代码不会读取代码的“ if”部分,而是始终显示“ else”部分中的消息

请帮助我。

0 个答案:

没有答案