登录按钮需要点击两次才能登录

时间:2021-05-27 12:25:24

标签: java android android-studio authentication

我正在 android studio 上制作一个考勤应用程序,但是每当我尝试使用正确的凭据登录时,我都需要在登录按钮上单击两次才能前进到下一个活动。我尝试了 Asynctasks 因为它的后台线程,在相同的结果之后我只是恢复了

所以,一开始点击什么都没有发生,但只要等待对话框消失,如果我在一两秒钟内点击,然后它就会移动到下一个活动。

在服务器验证登录存在且正确后,单击登录会从服务器获取一些数据。当接收到数据时,新活动应该开始,因为接收到的数据将显示在下一个活动中。 (我有一个列表,检查它是否有数据然后向前移动)

登录活动代码:

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    //sign up and login button
    private Button btnSignUp;
    private Button btnLogin;
    private ProgressDialog progressDialog;
    private RequestQueue Queue;

    //data URL
    private String extractStudentDataURL = "https://asuiot12.000webhostapp.com/checkLoginCredentials.php";
    private String extractEnrolmentsDataURL = "https://asuiot12.000webhostapp.com/retrieveEnrolledCoursesData.php";

    //editText
    private EditText editTextEmail, editTextPassword;
    private ConstraintLayout login;

    //string variables
    public static String inputEmail;
    private String inputPassword;

    //array list to store enrolled courses data
    public static LinkedList<Courses> enrolledCoursesData = new LinkedList();

    //static variable
    public static StudentData studentData;

    //shared preferences to maintain the login status of the user...
    public static SharedPreferences sp;

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

        login = findViewById(R.id.login_activity);
        login.setBackgroundColor(Color.WHITE);

        btnSignUp = findViewById(R.id.button_sign_up);
        btnLogin = findViewById(R.id.button_login);

        // sp = getSharedPreferences("login", MODE_PRIVATE);

        editTextEmail = findViewById(R.id.editText_RA_emailAddress);
        editTextPassword = findViewById(R.id.editText_RA_password);

        //login button listener
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                inputEmail = editTextEmail.getText().toString();
                inputPassword = editTextPassword.getText().toString();

                if (inputEmail.isEmpty()) {
                    editTextEmail.setError("Email Required");
                    editTextEmail.requestFocus();
                } else if (inputPassword.isEmpty()) {
                    editTextPassword.setError("Password Required");
                    editTextPassword.requestFocus();
                } else {
                            enrolledCoursesData.clear();
                            ExtractData();
                  }
            }
        });
        //signUp button listener
        btnSignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, RegistrationActivity.class);
                startActivityForResult(intent, 1);
            }
        });
    }

    //retrieving data from the server and checking the login credentials
    private void ExtractData() {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, extractStudentDataURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONArray array = new JSONArray(response);
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject data = array.getJSONObject(i);
                        int success = data.getInt("success");
                        if (success == 1) {
                            Long CNIC = data.getLong("CNIC");
                            String name = data.getString("Full_Name");
                            String fss = data.getString("FSS");
                            String regNo = data.getString("Reg_No");
                            String batch = data.getString("Batch");
                            String department = data.getString("Department");
                            int semester = data.getInt("Semester");
                            Long mobileNo = data.getLong("Mobile_No");
                            String nationality = data.getString("Nationality");
                            String MACAddress = data.getString("MAC_Address");
                            String homeAddress = data.getString("Home_Address");
                            String email = data.getString("Email");
                            String loginPassword = data.getString("Login_Password");
                            String photo = data.getString("Photo");

                            studentData = new StudentData(new BigInteger(String.valueOf(CNIC)), new BigInteger(String.valueOf(mobileNo))
                                    , semester, name, fss, regNo, batch, department, nationality,
                                    MACAddress, homeAddress, email, loginPassword, photo);

                            Toast.makeText(MainActivity.this, "Plz wait....", Toast.LENGTH_LONG).show();

                            // to get data of courses in which student is enrolled
                            extractDataOfEnrolments(email);

                            if (!enrolledCoursesData.isEmpty()) {
                                Intent intent = new Intent(MainActivity.this, CoursesActivity.class);
                                Bundle bundle = new Bundle();
                                bundle.putSerializable("list", enrolledCoursesData);
                                intent.putExtras(bundle);
                                startActivity(intent);
                            }

                        } else if (success == 0) {
                            Toast.makeText(MainActivity.this, "Incorrect username or password",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                } catch (Exception e) {


                }
            }
        },
                new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this, "Error " + error, Toast.LENGTH_SHORT).show();
            }
        }) {
            public Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("email", editTextEmail.getText().toString().trim());
                params.put("password", editTextPassword.getText().toString().trim());
                return params;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

    //retrieving data of enrolments from server
    private void extractDataOfEnrolments(final String email) {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, extractEnrolmentsDataURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONArray array = new JSONArray(response);
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject data = array.getJSONObject(i);
                        String courseCode = data.getString("Course_Code");
                        String courseName = data.getString("Course_Name");

                        Courses courses = new Courses(courseCode, courseName);
                        enrolledCoursesData.add(courses);
                    }

                } catch (Exception e) {

                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this, "Error " + error, Toast.LENGTH_SHORT).show();
            }
        }) {
            public Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("email", email);
                return params;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }
}

如果需要布局代码或服务器端 PHP 代码来更好地理解问题,请务必提问。

1 个答案:

答案 0 :(得分:0)

您对线程的工作方式有误解。

在您的 ExtractData 方法及其 onResponse 处理程序中,您调用 extractDataOfEnrolments(),它本身是异步的:

// to get data of courses in which student is enrolled
extractDataOfEnrolments(email);

// the list hasn't been filled yet, will be empty!!!
if (!enrolledCoursesData.isEmpty()) {
}

然后您立即检查 enrolledCoursesData 列表,如果不为空则启动 CoursesActivityextractDataOfEnrolments() 有一个尚未完成的异步回调 (onResponse()),因此列表将为空。

您可以考虑将 startActivity 代码移至 extractDataOfEnrolments(),例如:

@Override
public void onResponse(String response) {
try {
  JSONArray array = new JSONArray(response);
  for (int i = 0; i < array.length(); i++) {
     JSONObject data = array.getJSONObject(i);
     String courseCode = data.getString("Course_Code");
     String courseName = data.getString("Course_Name");
     Courses courses = new Courses(courseCode, courseName);
     enrolledCoursesData.add(courses);
  }

  // now your list is populated, so now Ok to startActivity
  if (!enrolledCoursesData.isEmpty()) {
     Intent intent = new Intent(MainActivity.this, CoursesActivity.class);
     Bundle bundle = new Bundle();
     bundle.putSerializable("list", enrolledCoursesData);
     intent.putExtras(bundle);
     startActivity(intent);
  }

} catch (Exception e) {

}