Android Mysql Connection - Error with POST Method

Asked

Viewed 198 times

0

Good night! I am developing a simple interface in Android Studio to login and register users. I followed the steps of a tutorial on youtube and almost everything works perfectly, I’m just having trouble trying to log in.

Code of the button Login:

 mBtnLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            ConnectivityManager connMgr = (ConnectivityManager)
                    getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

            if(networkInfo != null && networkInfo.isConnected()){

                String login = mEdtLogin.getText().toString();
                String senha = mEdtPass.getText().toString();

                if(login.isEmpty() || senha.isEmpty()){
                    Toast.makeText(getApplicationContext(), "Login e senha devem ser preenchidos",Toast.LENGTH_LONG).show();
                }else{
                    url = "meusite.com/login.php"; // Onde me refiro ao arquivo de conexão por PHP!
                    parametro = "login="+ login +"&senha="+ senha; //Este trecho eu tenho duvida se está correto pois estou utilizando o metodo POST no PHP e o formato deste parâmetro parece estranho. 
                    new SolicitaDados().execute(url);


                }



            }else{
                Toast.makeText(getApplicationContext(), "Nenhuma conexão detectada", Toast.LENGTH_LONG).show();
            }





        }
    });

Code of the class that supposedly searches the connection data:

private class SolicitaDados extends AsyncTask<String, Void, String>{ //LINHA 83 DO ERRO 


    @Override
    protected String doInBackground(String... urls) {
        try{
            return Conexao.postDados(urls[0], parametro);
        } catch (Exception erro){
            return "Impossível se conectar a pagina";
        }
    }

    @Override
    protected void onPostExecute(String resultado){ 


        if(resultado.contains("login_ok")){ // LINHA 99 DO ERRO - AQUI É ONDE OCORRE O ERRO, ISTO SEMPRE RETORNA NULL, JÁ DEBUGUEI O APP PAUSANDO AQUI
            Intent intent = new Intent(MainLoginActivity.this, Perfil.class);
            startActivity(intent);
        }else{
            Toast.makeText(getApplicationContext(), "Usuário ou senha incorretos", Toast.LENGTH_LONG).show();
        }

    }

}

Code for class Connection on android:

 public static String postDados(String urlUsuario, String parametrosUsuario){
        URL url;
        HttpsURLConnection connection = null;

        try{
            url = new URL(urlUsuario);
            connection = (HttpsURLConnection) url.openConnection();

            connection.setRequestMethod("POST");

            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            connection.setRequestProperty("Content-Lenght", "" + Integer.toString(parametrosUsuario.getBytes().length));

            connection.setRequestProperty("Content-Language", "pt-BR");

            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);

        DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());

        dataOutputStream.writeBytes(parametrosUsuario);
        dataOutputStream.flush();
        dataOutputStream.close();

            InputStream inputStream = connection.getInputStream();

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            String linha;
            StringBuilder resposta = new StringBuilder();

            while((linha = bufferedReader.readLine()) != null ){
                resposta.append(linha);
                resposta.append('\r');
            }

            bufferedReader.close();

            return resposta.toString();

        } catch (Exception erro){
            return null;
        } finally {
            if (connection != null){
                connection.disconnect();
            }
        }


    }

PHP code is functional because I have already tested manually (changing the POST methods by GET and forcing input), so I believe the error is in the return of android.

The error is as follows:

 E/AndroidRuntime: FATAL EXCEPTION: main
 java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.contains(java.lang.CharSequence)' on a null object reference
    at project.waifu.com.waifuproject.MainLoginActivity$SolicitaDados.onPostExecute(MainLoginActivity.java:99)
    at project.waifu.com.waifuproject.MainLoginActivity$SolicitaDados.onPostExecute(MainLoginActivity.java:83)

From there the App stops working! I’ve searched everywhere on the internet but nothing solved it!

Note: If you need php files let me know!!

EDIT: The error was in the Connection file, I was returning null inside the catch and so the app stopped working!

catch (Exception erro){
        return null; //Alterei para uma mensagem de erro e tudo deu certo!
  • 1

    Add return null; in a try...catch and not treat the error, it is a very big error. Check which error is occurring in the method postDados. To do so, add error.printStackTrace(); before return null;.

  • Really, I did what you said and changed the return to an error message and the problem was solved!!! Thank you very much, I would never think that was the mistake.

  • Someone is accompanying Duds kkkkk technology

  • Aheaheauh we have a xeroque rolmes here

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.