Android используя один backgroundWorker для входа в систему, регистрации и забыл пароль - PullRequest
0 голосов
/ 20 марта 2020

На экране входа в мое приложение также есть пароль и параметры регистрации. Я использовал приведенный здесь код введите описание ссылки здесь , чтобы создать свой фоновый рабочий стол для входа. Используя switch-case, я расширил это, чтобы включить в него регистр и ForgotPassword. Часть кода входа в систему работает правильно, и после входа я могу перейти на страницу приветствия.

Часть кода регистрации вводит данные в базу данных и возвращает ответ. Когда я использую alertDialog, он показывает ответ. Однако, когда я пытаюсь показать сообщение как тост или перенаправить пользователя на loginPage, оно не работает.

Ниже приведен код:

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

    Context context;
    AlertDialog alertDialog;
    SQLiteDatabase sqLiteDatabase;
    SQLiteHelper sqLiteHelper;

    SaveSharedPreference ssp = new SaveSharedPreference();

    BackgroundWorker(Context ctx) {
        context = ctx;
    }

    @Override
    protected String doInBackground(String... params) {
        String type = params[0];

//        String login_url = "http://192.168.0.102/syncsqlite/doLogin.php";
//        String register_url = "http://192.168.0.102/syncsqlite/doRegister.php";
//        String uploadData_url = "http://192.168.0.102/syncsqlite/uploadProjectData.php";

            String login_url = "https://test.ai/syncsqlite/doLogin.php";
            String register_url = "https://test.ai/syncsqlite/doRegister.php";
            String uploadData_url = "https://test.ai/syncsqlite/uploadProjectData.php";
            String forgotPassword_url = "https://test.ai/syncsqlite/forgotPassword.php";

            switch (type) {
                case "login":
                    try {
                        String user_name = 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("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"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();
                    }
                    break;
                case "register":
                    try {
                        String user_name = params[1];
                        String password = params[2];
                        String emailid = params[3];
                        String mobileno = params[4];

                        URL url = new URL(register_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("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8")+"&"
                                +URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8")+"&"
                                +URLEncoder.encode("emailid","UTF-8")+"="+URLEncoder.encode(emailid,"UTF-8")+"&"
                                +URLEncoder.encode("mobileno","UTF-8")+"="+URLEncoder.encode(mobileno,"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();
                    }
                    break;
            }

        return null;
    } //end of doInBackground



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

    }

    class LoginResponse {
        String response;
        String name;
    }

    @Override
    protected void onPostExecute(String result) {
//        alertDialog.setMessage(result);  **This is working**
//        alertDialog.show();

           Gson gson = new Gson();
           LoginResponse response = gson.fromJson(result, LoginResponse.class);
           String status = response.response;
           String name = response.name;

           switch (status) {
               case "Success!":
                   Toast.makeText(context, "Login Successful!", Toast.LENGTH_SHORT).show();
                   Intent goToWelcomePage = new Intent(context, welcome.class);
                   Bundle usrname = new Bundle();
                   usrname.putString("username", name);
                   goToWelcomePage.putExtras(usrname);
                   ssp.setUserName(context, name );
                   context.startActivity(goToWelcomePage);
                   break;
               case "Login failed":
                   Toast.makeText( context, status, Toast.LENGTH_SHORT ).show();
                   break;
               case "User Created": **This is not working**
                   Toast.makeText( context, "User Created.  Login now!", Toast.LENGTH_SHORT ).show();
//                   Intent goToMainActivity = new Intent(context, MainActivity.class);
//                   context.startActivity( goToMainActivity );
                   break;
           }

    }

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

}

Я получаю только пустой ответ. Нет ошибок Все, что я вижу, это

2020-03-20 10:37:06.937 1356-1377/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 30647071 , only wrote 30646800
2020-03-20 10:37:07.134 1356-1377/? W/audio_hw_generic: Hardware backing HAL too slow, could only write 0 of 720 frames
2020-03-20 10:37:10.163 1356-1378/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 30954482 , only wrote 30801600

Эти сообщения я получаю даже иначе.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...