Good evening! I'm developing a simple interface in Android Studio for login and user registration. I followed the steps of a YouTube tutorial and almost everything works perfectly, I'm just having trouble trying to log in.
Button code 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();
}
}
});
Class code that purportedly fetches 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 android connection class:
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();
}
}
}
The PHP code is functional because I have already tested manually (changing the POST methods by GET and forcing the input), so I believe the error is in the return of the 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 a catch and so the app stopped working!
catch (Exception erro){
return null; //Alterei para uma mensagem de erro e tudo deu certo!