1. Are you ready for the Galaxy S20? Here is everything we know so far!

How to send Loginactivity to main activity

Discussion in 'Android Development' started by Crazyglitch45, Sep 19, 2018.

  1. Crazyglitch45

    Crazyglitch45 Lurker
    Thread Starter

    I am currently a high school student, this year we took a challenge in designing an app for the Congressional App Challenge utilizing android studio. The situation that I'm having is I can't to get to the next activity from the Loginactivity. This below is my code



    Code (Text):
    1. package com.example.crazy.myapplication
    2.  
    3. import android.animation.Animator
    4. import android.animation.AnimatorListenerAdapter
    5. import android.annotation.TargetApi
    6. import android.content.pm.PackageManager
    7. import android.support.design.widget.Snackbar
    8. import android.support.v7.app.AppCompatActivity
    9. import android.app.LoaderManager.LoaderCallbacks
    10. import android.content.CursorLoader
    11. import android.content.Loader
    12. import android.database.Cursor
    13. import android.net.Uri
    14. import android.os.AsyncTask
    15. import android.os.Build
    16. import android.os.Bundle
    17. import android.provider.ContactsContract
    18. import android.text.TextUtils
    19. import android.view.View
    20. import android.view.inputmethod.EditorInfo
    21. import android.widget.ArrayAdapter
    22. import android.widget.TextView
    23.  
    24. import java.util.ArrayList
    25. import android.Manifest.permission.READ_CONTACTS
    26.  
    27. import kotlinx.android.synthetic.main.activity_login.*
    28.  
    29. /**
    30. * A login screen that offers login via email/password.
    31. */
    32. class LoginActivity : AppCompatActivity(), LoaderCallbacks<Cursor> {
    33.     /**
    34.      * Keep track of the login task to ensure we can cancel it if requested.
    35.      */
    36.     private var mAuthTask: UserLoginTask? = null
    37.  
    38.     override fun onCreate(savedInstanceState: Bundle?) {
    39.         super.onCreate(savedInstanceState)
    40.         setContentView(R.layout.activity_login)
    41.         // Set up the login form.
    42.         populateAutoComplete()
    43.         password.setOnEditorActionListener(TextView.OnEditorActionListener { _, id, _ ->
    44.             if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
    45.                 attemptLogin()
    46.                 return@OnEditorActionListener true
    47.             }
    48.             true
    49.  
    50.         })
    51.  
    52.         email_sign_in_button.setOnClickListener { attemptLogin() }
    53.     }
    54.  
    55.     private fun populateAutoComplete() {
    56.         if (!mayRequestContacts()) {
    57.             return
    58.         }
    59.  
    60.         loaderManager.initLoader(0, null, this)
    61.     }
    62.  
    63.     private fun mayRequestContacts(): Boolean {
    64.         if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
    65.             return true
    66.         }
    67.         if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
    68.             return true
    69.         }
    70.         if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
    71.             Snackbar.make(email, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
    72.                     .setAction(android.R.string.ok,
    73.                             { requestPermissions(arrayOf(READ_CONTACTS), REQUEST_READ_CONTACTS) })
    74.         } else {
    75.             requestPermissions(arrayOf(READ_CONTACTS), REQUEST_READ_CONTACTS)
    76.         }
    77.         return false
    78.     }
    79.  
    80.     /**
    81.      * Callback received when a permissions request has been completed.
    82.      */
    83.     override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>,
    84.                                             grantResults: IntArray) {
    85.         if (requestCode == REQUEST_READ_CONTACTS) {
    86.             if (grantResults.size == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
    87.                 populateAutoComplete()
    88.             }
    89.         }
    90.     }
    91.  
    92.  
    93.     /**
    94.      * Attempts to sign in or register the account specified by the login form.
    95.      * If there are form errors (invalid email, missing fields, etc.), the
    96.      * errors are presented and no actual login attempt is made.
    97.      */
    98.     private fun attemptLogin() {
    99.         if (mAuthTask != null) {
    100.             return
    101.         }
    102.  
    103.         // Reset errors.
    104.         email.error = null
    105.         password.error = null
    106.  
    107.         // Store values at the time of the login attempt.
    108.         val emailStr = email.text.toString()
    109.         val passwordStr = password.text.toString()
    110.  
    111.         var cancel = false
    112.         var focusView: View? = null
    113.  
    114.         // Check for a valid password, if the user entered one.
    115.         if (!TextUtils.isEmpty(passwordStr) && !isPasswordValid(passwordStr)) {
    116.             password.error = getString(R.string.error_invalid_password)
    117.             focusView = password
    118.             cancel = true
    119.         }
    120.  
    121.         // Check for a valid email address.
    122.         if (TextUtils.isEmpty(emailStr)) {
    123.             email.error = getString(R.string.error_field_required)
    124.             focusView = email
    125.             cancel = true
    126.         } else if (!isEmailValid(emailStr)) {
    127.             email.error = getString(R.string.error_invalid_email)
    128.             focusView = email
    129.             cancel = true
    130.         }
    131.  
    132.         if (cancel) {
    133.             // There was an error; don't attempt login and focus the first
    134.             // form field with an error.
    135.             focusView?.requestFocus()
    136.         } else {
    137.             // Show a progress spinner, and kick off a background task to
    138.             // perform the user login attempt.
    139.             showProgress(true)
    140.             mAuthTask = UserLoginTask(emailStr, passwordStr)
    141.             mAuthTask!!.execute(null as Void?)
    142.         }
    143.     }
    144.  
    145.     private fun isEmailValid(email: String): Boolean {
    146.         //TODO: Replace this with your own logic
    147.         return email.contains("@")
    148.     }
    149.  
    150.     private fun isPasswordValid(password: String): Boolean {
    151.         //TODO: Replace this with your own logic
    152.         return password.length > 2
    153.     }
    154.  
    155.     /**
    156.      * Shows the progress UI and hides the login form.
    157.      */
    158.     @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    159.     private fun showProgress(show: Boolean) {
    160.         // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
    161.         // for very easy animations. If available, use these APIs to fade-in
    162.         // the progress spinner.
    163.         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
    164.             val shortAnimTime = resources.getInteger(android.R.integer.config_shortAnimTime).toLong()
    165.  
    166.             login_form.visibility = if (show) View.GONE else View.VISIBLE
    167.             login_form.animate()
    168.                     .setDuration(shortAnimTime)
    169.                     .alpha((if (show) 0 else 1).toFloat())
    170.                     .setListener(object : AnimatorListenerAdapter() {
    171.                         override fun onAnimationEnd(animation: Animator) {
    172.                             login_form.visibility = if (show) View.GONE else View.VISIBLE
    173.                         }
    174.                     })
    175.  
    176.             login_progress.visibility = if (show) View.VISIBLE else View.GONE
    177.             login_progress.animate()
    178.                     .setDuration(shortAnimTime)
    179.                     .alpha((if (show) 1 else 0).toFloat())
    180.                     .setListener(object : AnimatorListenerAdapter() {
    181.                         override fun onAnimationEnd(animation: Animator) {
    182.                             login_progress.visibility = if (show) View.VISIBLE else View.GONE
    183.                         }
    184.                     })
    185.         } else {
    186.             // The ViewPropertyAnimator APIs are not available, so simply show
    187.             // and hide the relevant UI components.
    188.             login_progress.visibility = if (show) View.VISIBLE else View.GONE
    189.             login_form.visibility = if (show) View.GONE else View.VISIBLE
    190.         }
    191.     }
    192.  
    193.     override fun onCreateLoader(i: Int, bundle: Bundle?): Loader<Cursor> {
    194.         return CursorLoader(this,
    195.                 // Retrieve data rows for the device user's 'profile' contact.
    196.                 Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
    197.                         ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
    198.  
    199.                 // Select only email addresses.
    200.                 ContactsContract.Contacts.Data.MIMETYPE + " = ?", arrayOf(ContactsContract.CommonDataKinds.Email
    201.                 .CONTENT_ITEM_TYPE),
    202.  
    203.                 // Show primary email addresses first. Note that there won't be
    204.                 // a primary email address if the user hasn't specified one.
    205.                 ContactsContract.Contacts.Data.IS_PRIMARY + " DESC")
    206.     }
    207.  
    208.     override fun onLoadFinished(cursorLoader: Loader<Cursor>, cursor: Cursor) {
    209.         val emails = ArrayList<String>()
    210.         cursor.moveToFirst()
    211.         while (!cursor.isAfterLast) {
    212.             emails.add(cursor.getString(ProfileQuery.ADDRESS))
    213.             cursor.moveToNext()
    214.         }
    215.  
    216.         addEmailsToAutoComplete(emails)
    217.     }
    218.  
    219.     override fun onLoaderReset(cursorLoader: Loader<Cursor>) {
    220.  
    221.     }
    222.  
    223.     private fun addEmailsToAutoComplete(emailAddressCollection: List<String>) {
    224.         //Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
    225.         val adapter = ArrayAdapter(this@LoginActivity,
    226.                 android.R.layout.simple_dropdown_item_1line, emailAddressCollection)
    227.  
    228.         email.setAdapter(adapter)
    229.     }
    230.  
    231.     object ProfileQuery {
    232.         val PROJECTION = arrayOf(
    233.                 ContactsContract.CommonDataKinds.Email.ADDRESS,
    234.                 ContactsContract.CommonDataKinds.Email.IS_PRIMARY)
    235.         val ADDRESS = 0
    236.         val IS_PRIMARY = 1
    237.     }
    238.  
    239.     /**
    240.      * Represents an asynchronous login/registration task used to authenticate
    241.      * the user.
    242.      */
    243.     inner class UserLoginTask internal constructor(private val mEmail: String, private val mPassword: String) : AsyncTask<Void, Void, Boolean>() {
    244.  
    245.         override fun doInBackground(vararg params: Void): Boolean? {
    246.             // TODO: attempt authentication against a network service.
    247.  
    248.             try {
    249.                 // Simulate network access.
    250.                 Thread.sleep(2000)
    251.             } catch (e: InterruptedException) {
    252.                 return false
    253.             }
    254.  
    255.             return DUMMY_CREDENTIALS
    256.                     .map { it.split(":") }
    257.                     .firstOrNull { it[0] == mEmail }
    258.                     ?.let {
    259.                         // Account exists, return true if the password matches.
    260.                         it[1] == mPassword
    261.                     }
    262.                     ?: true
    263.         }
    264.  
    265.         override fun onPostExecute(success: Boolean?) {
    266.             mAuthTask = null
    267.             showProgress(true)
    268.  
    269.             if (success!!) {
    270.                 finish()
    271.             } else {
    272.                 password.error = getString(R.string.error_incorrect_password)
    273.                 password.requestFocus()
    274.             }
    275.         }
    276.  
    277.         override fun onCancelled() {
    278.             mAuthTask = null
    279.             showProgress(false)
    280.         }
    281.     }
    282.  
    283.     companion object {
    284.  
    285.         /**
    286.          * Id to identity READ_CONTACTS permission request.
    287.          */
    288.         private val REQUEST_READ_CONTACTS = 0
    289.  
    290.         /**
    291.          * A dummy authentication store containing known user names and passwords.
    292.          * TODO: remove after connecting to a real authentication system.
    293.          */
    294.         private val DUMMY_CREDENTIALS = arrayOf("foo@example.com:hello", "bar@example.com:world")
    295.     }
    296. }
    297.  
     

    Attached Files:



  2. wseng92

    wseng92 Android Enthusiast

    Any exceptions ?
     
  3. Deleted User

    Deleted User Guest

    Is your question that you don't know how to start an Activity?
     
  4. Crazyglitch45

    Crazyglitch45 Lurker
    Thread Starter

    Sort of since I'm trying to get to the next activity from the login activity
     
  5. Deleted User

    Deleted User Guest

    Basically you have to create an Intent, and start the Activity, which would look something like this in Kotlin:

    Code (Text):
    1.  
    2. val intent = Intent(this, TaskDescriptionActivity::class.java)
    3. startActivityForResult(intent, ADD_TASK_REQUEST)
    4.  
     
  6. Crazyglitch45

    Crazyglitch45 Lurker
    Thread Starter

    Alright I did something similar but now I dealing with 2 errors is there a way that can be fix

    Code (Text):
    1. **
    2. * A login screen that offers login via email/password.
    3. */
    4. class LoginActivity : AppCompatActivity(), LoaderCallbacks<Cursor> {
    5.     /**
    6.      * Keep track of the login task to ensure we can cancel it if requested.
    7.      */
    8.     private var mAuthTask: UserLoginTask? = null
    9.  
    10.     override fun onCreate(savedInstanceState: Bundle?) {
    11.         super.onCreate(savedInstanceState)
    12.         setContentView(R.layout.activity_login)
    13.         // Set up the login form.
    14.         populateAutoComplete()
    15.         password.setOnEditorActionListener(TextView.OnEditorActionListener { _, id, _ ->
    16.             val b = true
    17.             if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
    18.                 attemptLogin()
    19.                 return@OnEditorActionListener b
    20.             }
    21.             val b1 = b
    22.              intent  = onNewIntent(LoginActivity.equals(MainActivity.class);
    23.  
    24.  
    25.         })
    26.  
    27.         email_sign_in_button.setOnClickListener { attemptLogin() }
    28.     }
    29.  
     
  7. Deleted User

    Deleted User Guest

    What are the errors?
     
  8. Crazyglitch45

    Crazyglitch45 Lurker
    Thread Starter

    This error
     

    Attached Files:

  9. Deleted User

    Deleted User Guest

    And what line does that error occur on?
     
  10. Crazyglitch45

    Crazyglitch45 Lurker
    Thread Starter

  11. Deleted User

    Deleted User Guest

    What's at line 54? It's a blank line in the original code fragment you've shown, and in the other one, there are only 28 lines.
     
  12. Crazyglitch45

    Crazyglitch45 Lurker
    Thread Starter

    Here the updated code



    Code (Text):
    1. package com.example.crazy.myapplication
    2.  
    3. import android.animation.Animator
    4. import android.animation.AnimatorListenerAdapter
    5. import android.annotation.TargetApi
    6. import android.content.pm.PackageManager
    7. import android.support.design.widget.Snackbar
    8. import android.support.v7.app.AppCompatActivity
    9. import android.app.LoaderManager.LoaderCallbacks
    10. import android.content.CursorLoader
    11. import android.content.Loader
    12. import android.database.Cursor
    13. import android.net.Uri
    14. import android.os.AsyncTask
    15. import android.os.Build
    16. import android.os.Bundle
    17. import android.provider.ContactsContract
    18. import android.text.TextUtils
    19. import android.view.View
    20. import android.view.inputmethod.EditorInfo
    21. import android.widget.ArrayAdapter
    22. import android.widget.TextView
    23.  
    24. import java.util.ArrayList
    25. import android.Manifest.permission.READ_CONTACTS
    26. import android.annotation.SuppressLint
    27. import android.content.Intent
    28. import android.widget.Toast
    29. import com.example.crazy.myapplication.R.layout.activity_main
    30.  
    31. import kotlinx.android.synthetic.main.activity_login.*
    32.  
    33. /**
    34. * A login screen that offers login via email/password.
    35. */
    36. class LoginActivity : AppCompatActivity(), LoaderCallbacks<Cursor> {
    37.     /**
    38.      * Keep track of the login task to ensure we can cancel it if requested.
    39.      */
    40.     private var mAuthTask: UserLoginTask? = null
    41.  
    42.     override fun onCreate(savedInstanceState: Bundle?) {
    43.         super.onCreate(savedInstanceState)
    44.         setContentView(R.layout.activity_login)
    45.         // Set up the login form.
    46.         populateAutoComplete()
    47.         password.setOnEditorActionListener(TextView.OnEditorActionListener { _, id, _ ->
    48.             val b = true
    49.             if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
    50.                 attemptLogin()
    51.                 return@OnEditorActionListener b
    52.             }
    53.             val b1 = b
    54.              intent  = onNewIntent(LoginActivity.equals(MainActivity.class)
    55.  
    56.  
    57.         })
    58.  
    59.         email_sign_in_button.setOnClickListener { attemptLogin() }
    60.     }
    61.  
    62.     private fun populateAutoComplete() {
    63.         if (!mayRequestContacts()) {
    64.             return
    65.         }
    66.  
     
Loading...

Share This Page

Loading...