0

i have a problem with my asynctask to load the content of a url, the content made time to been load to the string and i am forced to do Thread.Sleep to wait until the content is loaded and i'm sure that's not the ri ght way, so i'm asking to you what's the right way to get the content without that

my AsynTask :

package fungames.fungames;

import android.os.AsyncTask;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;


class GetContent extends AsyncTask<String, Void, String> {
    protected  String result = "";
     protected  int done = 0;

     @Override
    protected String doInBackground(String[] params) {

        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(params[0]);
            httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "FGAPP");
         HttpResponse resulte = httpClient.execute(httpPost);
            HttpEntity entity = resulte.getEntity();
          result = EntityUtils.toString(entity,"UTF-8");
        }
        catch(Exception i) {
            result = i.toString();
        }
        done = 1;
        return result;

    }

    protected void onPostExecute(String message) {
    }
}

my Loader :

public static void Example() {
  String values = Servers.Load();
}
 public static String Load() {
        String url = "http://example.com";
        GetContent job = new GetContent();
        job.execute(url);
        return Do2(job);
    }
 public static String Do2(GetContent job)
        {
            String game = job.result;
            if (game != "") {
                    return game;
                }
            } else {
                try {
                    Thread.sleep(50);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return Do2(job);
            }
        }

thanks you !

aZ oTe
  • 21
  • 7
  • You have to override onPostExecute by: super.onPostExecute(message); Then in Load function return job.execute(url).get(); see this post https://stackoverflow.com/questions/10972114/how-to-get-a-string-back-from-asynctask – AhmedAbdelaal Aug 26 '17 at 14:52

1 Answers1

0

Create an interface in you AsyncTask class:

class GetContent extends AsyncTask<String, Void, String> {

protected  String result = "";
 protected  int done = 0;  
protected String action = "";

public interface SendResult {
    void onTaskFinished(String result,String action);
  }  

public SendResult resultInterface = null;

public GetContent(SendResult interface,String action){
    resultInterface  = interface;
    this.action = action;
}
 @Override
protected String doInBackground(String[] params) {

    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(params[0]);
        httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "FGAPP");
     HttpResponse resulte = httpClient.execute(httpPost);
        HttpEntity entity = resulte.getEntity();
      result = EntityUtils.toString(entity,"UTF-8");
    }
    catch(Exception i) {
        result = i.toString();
    }
    done = 1;
    return result;

}

protected void onPostExecute(String message) {
    resultInterface.onTaskFinished(message,action);
}
}  

Implement that interface in your activity:

public class MainActivity extends AppCompatActivity 
implements GetContent.SendResult{

@Override
public void onCreate(Bundle savedInstanceState) {

    String url = "http://example.com";
    fetchDataForUrl(url,"RequestType-1");
}  

public void fetchDataForUrl(String url,String action){
    GetContent job = new GetContent(this,action);
    job.execute(url);
}


@Override
void onTaskFinished(String result,String action){
    //Here you will receive the result.  
    //Do what ever you want here.
      if(action.equals("RequestType-1")){
           //access result here.
        }
    }
}
Murli Prajapati
  • 8,833
  • 5
  • 38
  • 55
  • thanks for the answer, it is possible to use this for all my differents requests ? because i see the method onTaskFinished is the only method to get the result and i don't know how to use it for each request, because they are on the same Activity – aZ oTe Aug 26 '17 at 15:03
  • yes it can be used for different request if your response is a simple string. – Murli Prajapati Aug 26 '17 at 15:06
  • yes but how can i know where the onTaskFinished result is from ? if i request a link in the onCreate AND another link in a button onClick by exemple – aZ oTe Aug 26 '17 at 15:09
  • in constructor of AsyncTask, add a parameter like `url` and add the same to interface method. so in your activity you will receive url, so check the url and perform your operations. – Murli Prajapati Aug 26 '17 at 15:12
  • and i literally don't understand how to get the result , if i do that public void getOnline() { String url = "http://example.com"; GetContent job = new GetContent(this,"RequestType-1"); job.execute(url); } i don't know how with the onTaskFinished i can get the result without set a public string, so i'm at same point i have t o thread.sleep until the string is null – aZ oTe Aug 26 '17 at 15:39
  • the result will be delivered by `onTaskFinished()` method – Murli Prajapati Aug 26 '17 at 15:42
  • thanks, can you see me how to use it in another place than onCreate method i don't understand – aZ oTe Aug 26 '17 at 15:43
  • code edited. call `fetchDataForUrl()` from anywhere within activity and you will get result in `onTaskFinished()` method with request type. – Murli Prajapati Aug 26 '17 at 15:48
  • yes but i wan't to use the result in the whole class and not just the function onTaskFinished() because i have lot of request and put all my code in this function is not appropriated and i don't have access to my layout etc.., so a function who return the result in string may be good – aZ oTe Aug 26 '17 at 15:59
  • you can create a global variable in your class and assign it a value in `onTaskFinished` method – Murli Prajapati Aug 26 '17 at 16:07
  • yes but that's the same that before, i'm gonna execute GetContent and try to use the global variable , but it made time to load url and set the variable so the variable gonna be null – aZ oTe Aug 26 '17 at 16:13
  • you can use `AsyncTask.execute().get()` it will return String but it will be synchronous meaning UI will freeze. – Murli Prajapati Aug 26 '17 at 16:52
  • you can create methods for your operations. so when the result arrives call the method and pass the result to it. it doesn't require checking for the variable is null. – Murli Prajapati Aug 26 '17 at 16:57