Problems with Asynctask crashing the application

Asked

Viewed 613 times

2

I am developing a online chat which should update alone all the time, the problem is that each query hangs the application for a half seconds. I had already asked a similar question in: How to make connections to a php work in the background on Android but it wasn’t exactly what I wanted.

I need you to pages did not lock the app on each query. I’ve heard of backgroundWoker and Service but I honestly have no idea what I might be doing wrong.

I am using Mysql+PHP+JSON.

This is my code:

package com.Dannark.livechat;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.AsyncTask;
import android.util.Log;

class Connect extends AsyncTask<String, String, String>{

    @Override
    protected String doInBackground(String... uri) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response;
        String responseString = null;
        try {
            response = httpclient.execute(new HttpGet(uri[0]));
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                out.close();
                responseString = out.toString();
            } else{
                //Closes the connection.
                response.getEntity().getContent().close();
                throw new IOException(statusLine.getReasonPhrase());
            }
        } catch (ClientProtocolException e) {
            //TODO Handle problems..
        } catch (IOException e) {
            //TODO Handle problems..
        }
        return responseString;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        Log.e("-- MYSQL --",result);
        //Do anything with response..
    }
}

EDIT: And I’m interacting with the class connect With class Connect in that way:

package com.Dannark.livechat;

import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;

public class Conectar {

    String response;
    int status;

    public Conectar(String website){
        //First - send request to server
        AsyncTask<String,String,String> task;
        String uri = website;       //  www.meusite.com/get_chat/?room=10


        try {
            task = new Connect().execute(uri);
            response = task.get();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }

}

And finally the class conectar in this way:

Conectar Conn = new Conectar("http://animesslife.engine001.com/chat/login.php?login=" + campoLogin.getText() + "&senha=" + campoSenha.getText() );
Log.i("-RESPOSTA-",Conn.response); //Conn.response seria a resposta no decodificada em JSON

I should use another method instead of this?

  • How are you interacting with the "Connect" class? Apparently I’m not seeing anything wrong with Asynctask, except that of not properly closing resources in a "Finally block".

  • I added some information...

  • I added the answer. I’m answering from my smartphone, so you can’t put the example code, but I hope you get the idea.

1 answer

2


Asynctask was made for you to execute "heavy" code in the method doInBackground() and UI code (update screen) in the method onPostExecute() what are you doing while performing this method get() is to perform a heavy operation synchronously on Mainthread, which causes it to 'crash' as Main Thread is busy with the operation.

What you should do is just call the execute() method, and within the onPostExecute() you will receive the result of the heavy operation as parameter (the return of the method doInBackground() and you can update the screen inside. That is, on onPostExecute() you will do something like: textView.setText(dataResult)

There is example of use here: http://developer.android.com/reference/android/os/AsyncTask.html

  • Ahh I got it, man, because it was really cool your explanation... Would it be just like you show me an example (when you have it on your pc) based on my code so I can be sure what I’m doing? : ) For me to define immediately the answer as accepted?

  • http://developer.android.com/reference/android/AsyncTask.html take a look at the code on this page.

  • Hey hey hey, man... :)

  • And if I were to return a value from onPostExecute(), I would not like to type the phrase textView.setText(result) in there...

  • you can’t do that, because the behavior of Asynctask, as its name says is asynchronous and the method onPostExecute() is the final callback...what you can do is pass the call to another method...but if you use Asynctask you can’t avoid onPostExecute().

Browser other questions tagged

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