异步任务与响应监听器

huangapple go评论100阅读模式
英文:

AsyncTask with ResponseListener

问题

以下是您要的翻译内容:

我想从JSON获取数据,并在asyncTask中执行此操作。问题是onPostExecute在doInBackground之前执行。

因此,这是我调用execute的片段:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    new GetPlantsList().execute();
}

以及我的AsyncTask:

public class GetPlantsList extends AsyncTask<Void, Void, Void> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... voids) {
        Response.Listener<String> responseListener = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                // 如果没有错误
                try {
                    // 这里是我的JSON响应
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };

        // 通过strings.xml中的变量获取php文件,并发送请求
        PlantsListRequest plantsListRequest = new PlantsListRequest(user_id, responseListener, getResources().getString(R.string.php_file) + "get_plants_list.php");
        RequestQueue queue = Volley.newRequestQueue(getActivity());
        queue.add(plantsListRequest);
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        // 初始化recycler view(包含植物列表)
        rv_plants = (RecyclerView) view_frag.findViewById(R.id.rv_list_plants);

        // 使用Recycler view Plants List类来创建植物列表(将用户的所有植物传递给它)
        PlantsList plantsList = new PlantsList(getActivity(), tv_plants_name, tv_plants_variety, iv_plants_img, id_plants);

        // recycler view显示植物列表
        rv_plants.setAdapter(plantsList);
        rv_plants.setLayoutManager(new LinearLayoutManager(getActivity()));
    }
}

在我的onPostExecute中,我只是尝试显示我从JSON获取的所有信息(并在请求结束时执行此操作)。

我刚开始学习Android编程。提前感谢您的帮助 😉

英文:

I would like to get data from JSON and doing this in the asyncTask. The problem is that the onPostExecute is executed before the doInBackground.

So here is my fragment where I called the execute :

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new GetPlantsList().execute();
}

And my AsyncTask

public class GetPlantsList extends AsyncTask&lt;Void, Void, Void&gt; {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... voids) {
Response.Listener&lt;String&gt; responseListener = new Response.Listener&lt;String&gt;() {
@Override
public void onResponse(String response) {
//Si pas d&#39;erreur
try {
// Here my JSON response
} catch (JSONException e) {
e.printStackTrace();
}
}
};
//On r&#233;cup&#233;re le fichier php via la variable dans strings.xml et on envoi la requete
PlantsListRequest plantsListRequest = new PlantsListRequest(user_id, responseListener, getResources().getString(R.string.php_file) + &quot;get_plants_list.php&quot;);
RequestQueue queue = Volley.newRequestQueue(getActivity());
queue.add(plantsListRequest);
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
// Initialisation de la recycler view (qui va comporter la liste des plantes)
rv_plants = (RecyclerView) view_frag.findViewById(R.id.rv_list_plants);
//On vient cr&#233;er la liste des plantes avec la class Recycler view Plants List (on lui envoie toutes les plantes de mon utilisateurs)
PlantsList plantsList = new PlantsList(getActivity(), tv_plants_name, tv_plants_variety, iv_plants_img, id_plants);
//Mon recycler view vient afficher la liste des plantes
rv_plants.setAdapter(plantsList);
rv_plants.setLayoutManager(new LinearLayoutManager(getActivity()));
}
}

In my onPostExecute, I just try to display all the informations that I got from the JSON (and to do this at the end of the request ;)).

I m new in the android programmation. Thanks in advance for your help 异步任务与响应监听器

答案1

得分: 0

问题在于 onPostExecutedoInBackground 之前执行。

Volley 中的 RequestQueue 通过网络线程以异步方式操作。因此,在 doInBackground 中的 plantsListRequest 的响应之前,将调用 onPostExecute

如果您想在网络调用期间阻塞线程(任务),可以使用 RequestFuture但是,不建议这样做。 您可以通过带有 ListenerNetworkQueue 实现简单的网络调用(无需使用 AsyncTask)。

使用 RequestFuture

@Override
protected Void doInBackground(Void... voids) {
    RequestFuture&lt;String&gt; future = RequestFuture.newFuture();
    
    // 从 strings.xml 中获取 php 文件,并发送请求
    PlantsListRequest plantsListRequest = new PlantsListRequest(user_id, future, getResources().getString(R.string.php_file) + "get_plants_list.php");
    RequestQueue queue = Volley.newRequestQueue(getActivity());
    queue.add(plantsListRequest);

    String response = future.get(); // 阻塞线程

    return null;
}

Volley

异步任务与响应监听器

参考资料

英文:

> The problem is that the onPostExecute is executed before the doInBackground.

RequestQueue in Volley that operates asynchronously through network threads. thus, onPostExecute is called before the response of plantsListRequest in doInBackground.

If you want to block thread(task) while network call, you can use RequestFuture. But, it's not recommended. you could simply implement network calls via NetworkQueue with Listener. (without AsyncTask).

Using RequestFuture

@Override
protected Void doInBackground(Void... voids) {
    RequestFuture&lt;String&gt; future = RequestFuture.newFuture();
    
    //On r&#233;cup&#233;re le fichier php via la variable dans strings.xml et on envoi la requete
    PlantsListRequest plantsListRequest = new PlantsListRequest(user_id, future, getResources().getString(R.string.php_file) + &quot;get_plants_list.php&quot;);
    RequestQueue queue = Volley.newRequestQueue(getActivity());
    queue.add(plantsListRequest);

    String response = future.get(); // blocking thread

    return null;
}

Volley

异步任务与响应监听器

Reference

huangapple
  • 本文由 发表于 2020年4月6日 15:43:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/61055076.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定