Asynktask does not run doInBackGround

Asked

Viewed 54 times

1

I am developing an android app for the integrative college project in which I need to pass parameter 2 strings (user and password) to a PHP API that will return a User object or a Boolean false.

I am using Asynctask for this. But at the time I run the debug, it does not run doInBackground.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:background="@android:color/holo_green_light">

            <TextView
                android:id="@+id/textView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="UniLibrary"
                android:textAlignment="center"
                android:textColor="#dddddd"
                android:textSize="25dp"
                android:textStyle="bold"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:padding="5dp">

            <TextView
                android:id="@+id/txtLogin"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Usuário"
                android:textAppearance="?android:attr/textAppearanceMedium" />

            <EditText
                android:id="@+id/edtUsuario"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10" >
            </EditText>


            <TextView
                android:id="@+id/txtSenha"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Senha"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:inputType="number"/>

            <EditText
                android:id="@+id/edtSenha"
                android:layout_width="match_parent"
                android:layout_height = "wrap_content"
                android:ems="10"
                android:inputType="textPassword" />

            <Button
                android:id="@+id/btnEntrar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Entrar"
                android:onClick="click"/>

        </LinearLayout>

    </LinearLayout>
</android.support.constraint.ConstraintLayout>

Mainactivity

package unifacear.edu.br.unilibrary_mobile;

import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import unifacear.edu.br.unilibrary_mobile.Model.Entity.Login;
import unifacear.edu.br.unilibrary_mobile.Model.Entity.Permissao;
import unifacear.edu.br.unilibrary_mobile.Model.Service.LoginService;

public class MainActivity extends AppCompatActivity {

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

    }



    public void login(Boolean aceite) {
        if(aceite) {
            Intent intent = new Intent(this, ListActivityLivro.class);

            startActivity(intent);
        } else {
            Toast.makeText(this, "Usuario ou senha incorretos", Toast.LENGTH_LONG).show();
        }
    }

    public void click(View v) {
        Button btnEntrar = (Button) v;

        EditText usuario = findViewById(R.id.edtUsuario);
        EditText senha = findViewById(R.id.edtSenha);
        Login l = new Login();
        l.setUsuario(usuario.getText().toString());
        l.setSenha(senha.getText().toString());

        LoginService s = new LoginService(getApplicationContext());
        s.setActivity(this);
        s.execute(l);
    }
}

Loginservice

package unifacear.edu.br.unilibrary_mobile.Model.Service;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

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

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import unifacear.edu.br.unilibrary_mobile.ExibeLivroActivity;
import unifacear.edu.br.unilibrary_mobile.MainActivity;
import unifacear.edu.br.unilibrary_mobile.Model.Entity.Livro;
import unifacear.edu.br.unilibrary_mobile.Model.Entity.Login;
import unifacear.edu.br.unilibrary_mobile.Model.Entity.Usuario;

public class LoginService extends AsyncTask<Login,String,String> {
    private String urlString = "https://unilibrary.000webhostapp.com/usuario/login";


    private MainActivity activity;
    private ProgressDialog dialog;
    private Context context;

    public LoginService(Context context) {
        this.context = context;
    }

    public void setActivity(MainActivity activity) {
        this.activity = activity;
    }



    @Override
    protected void onPreExecute() {
        dialog = new ProgressDialog(context);
        dialog.setTitle("Por favor aguarde");
        dialog.setMessage("Carregando...");
        dialog.show();
    }

    @Override
    protected String doInBackground(Login... logins) {
        JSONObject json = new JSONObject();

        try{

            json.put("usuario", logins[0].getUsuario());
            json.put("senha", logins[0].getSenha());

            URL url = new URL(urlString);

            HttpURLConnection connection = (HttpURLConnection)url.openConnection();

            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-type", "application/json");
            connection.setDoOutput(true);
            connection.setDoInput(true);


            PrintStream printStream = new PrintStream(connection.getOutputStream());
            printStream.println(json.toString());

            connection.connect();

            connection.getOutputStream();

            BufferedReader br = new BufferedReader(
                    new InputStreamReader(url.openStream()));

            StringBuilder sb = new StringBuilder();

            String result;

            while((result = br.readLine()) != null){
                sb.append(result + "\n");
            }

            br.close();
            return sb.toString();
        } catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {

        if(!result.equalsIgnoreCase("false")) {

            try {
                JSONArray jsonArray = new JSONArray(result);
                List<Usuario> usuarios = new ArrayList<>();

                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject object = jsonArray.getJSONObject(i);

                    Usuario usuario = new Usuario();
                    usuario.setId(object.getInt("id"));
                    usuario.setUsuario(object.getInt("usuario"));
                    usuario.setPermissao(object.getInt("permissao"));
                    usuario.setStatus(object.getBoolean("status"));

                    usuarios.add(usuario);

                    dialog.dismiss();
                }
                activity.login(true);
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {
            activity.login(false);
            dialog.dismiss();
        }
    }
}

If anyone can help this young padawan, I will be eternally grateful.

  • What do you mean, "does not run doInBackground"? Gives error, does not do what you want or is not called?

  • From what I saw when debugging, it runs up to onPreExecute and that’s it. It doesn’t do what it should do and gives no error message

  • And what is the result in onPostExecute?

  • I didn’t realize it was in the mood debug, The problem is due to the fact that theInBackground() is executed in another thread.

  • Murilo, the result would be a User object or a Boolean. But it doesn’t come to that because the app closes before

  • @Chewbaquita did you ever use my answer? with it it is possible to use breakpoint in theInBackground to perform the debug, it can make it easier for you to find any error.

  • @Murillocomino I did now, but it hasn’t worked out yet. It’s like I didn’t even enter the

  • @Murilocomino removed onPreExecute and now ran doInBackground. Now it’s showing another error. Thanks for the help.

  • Unfortunately I could not identify any error

Show 4 more comments

1 answer

0

Hello, from what I understand you are wanting to debug inside theInBackground, so first add in theInBackground right at the beginning:

if(android.os.Debug.isDebuggerConnected())
    android.os.Debug.waitForDebugger();

If debug still doesn’t work you can try using Log.d within theInBackground, at least with the logcat you can check where your logic is going.

Browser other questions tagged

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