Почему по-прежнему можно перейти на следующую страницу, если нажать кнопку «ОК» на alerttdialog? - PullRequest
0 голосов
/ 24 сентября 2019

Мои проблемы:

1.У меня ошибка в onPostExecute

enter image description here

2.Я не хочу, чтобы пользователь все еще мог войти без учетной записи.

3.Я думаю, что мое утверждение if else неверно, но кто-нибудь, пожалуйста, внесите некоторые коррективы в мой код на onPostExecute

Ниже: Background.java для соединения с базой данных в xampp

public class Background extends AsyncTask<String,Void,String> {

Context context;
AlertDialog alertDialog;
Activity activity;

Background(Context ctx) {
    context = ctx;
}

@Override
protected String doInBackground(String... params)
{
    String type = params[0];
    String login_url = "http://172.20.10.4/LoginLab3.php";
    String reg_url = "http://172.20.10.4/RegisterLab3.php";
    if (type.equals("login")) {
        try {
            String username = params[1];
            String password = params[2];
            URL url = new URL(login_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8") + "&"
                    + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "ISO-8859-1"));
            String result = "";
            String line = "";
            while ((line = bufferedReader.readLine()) != null)
            {
                result += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;
        }
        catch (MalformedURLException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
    else if(type.equals("register"))
    {
        try {
            String name = params[1];
            String surname = params[2];
            String age = params[3];
            String username = params[4];
            String password = params[5];
            URL url = new URL(reg_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("name","UTF-8")+"="+URLEncoder.encode(name,"UTF-8")+"&"
                    +URLEncoder.encode("surname","UTF-8")+"="+URLEncoder.encode(surname,"UTF-8")+"&"
                    +URLEncoder.encode("age","UTF-8")+"="+URLEncoder.encode(age,"UTF-8")+"&"
                    +URLEncoder.encode("username","UTF-8")+"="+URLEncoder.encode(username,"UTF-8")+"&"
                    +URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"ISO-8859-1"));
            String result="";
            String line="";
            while((line = bufferedReader.readLine())!= null)
            {
                result += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;
        }
        catch (MalformedURLException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
    return null;
}

@Override
protected void onPreExecute()
{
    alertDialog = new AlertDialog.Builder(context).create();
    alertDialog.setTitle("Login Status");
}

@Override
protected void onPostExecute(final String result)
{
    final AlertDialog.Builder dialog = new AlertDialog.Builder(context);
    dialog.setTitle("Login Status");
    dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener()
    {
        @Override
        public void onClick(DialogInterface dialogInterface, int i)
        {
            Boolean isError = false;
            final EditText Password = myPasswordView.findViewById(R.id.etPassword);
            String password = Password.getText().toString().trim();
            Boolean isError = true;

            if (password.equals("")) {
                Intent intent = new Intent(context, Welcome.class);
                context.startActivity(intent);
                ((Activity) context).finish();
                isError = false;
                Password.setError(null);
            }
            if(!isError)
                dialog.dismiss();
        }
    });
    dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            dialogInterface.cancel();
        }
    });
    dialog.create().show();
}

@Override
protected void onProgressUpdate(Void... values)
{
    super.onProgressUpdate(values);
}
}

Ниже: Login.java

public class Login extends AppCompatActivity
{
EditText username, password;

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

    username = findViewById(R.id.etUsername);
    password = findViewById(R.id.etPassword);
}

public void OnLog(View view)
{
    String Username = username.getText().toString();
    String Password = password.getText().toString();
    String type = "login";

    if(Username.equals("") || Password.equals(""))
    {
        Toast.makeText(getApplicationContext(), "Please fill the Username and Password!", Toast.LENGTH_LONG).show();
    }
    else {

        Background bg = new Background(this);
        bg.execute(type, Username, Password);
    }
}

public void OnReg(View view) {
    startActivity(new Intent(getApplicationContext(), Register.class));
}
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...