简体   繁体   English

如何将数据从异步类传递到主要活动类

[英]How to pass data from Async Class to Main Activity class

I have JSON data that i converted into JSONArray . 我有转换为JSONArray JSON数据。 I have performed this conversion in an inner class which is extending AsyncTask . 我已经在扩展AsyncTask的内部类中执行了此转换。

Now i have data which contains Images and their Titles . 现在我有包含Images及其Titles I want to create a Loop and create ImageView dynamically. 我想创建一个Loop并动态创建ImageView

The problem i am facing is that my data is in inner class and in doInBackground() method, and the stuff; 我面临的问题是我的数据在内部类和doInBackground()方法中,以及其他内容中; ie: ImageView i need to create is in Outer class and in onCreate() method. 即:我需要创建的ImageView在外部类和onCreate()方法中。

I am unable to understand how to use jsonArray which i created in my InnerClass in my outer class. 我无法理解如何使用jsonArray我在我的创建InnerClass在我的外部类。

Inner Class: 内部舱位:

public class NewsService extends AsyncTask { 公共类NewsService扩展了AsyncTask {

    @Override
    protected JSONArray doInBackground(String... params) {

        URL url = null;
        try {
          //All JSON to JSONArray conversion code goes here
          //..

          JSONArray jsonArray = new JSONArray(jsonString);
         return jsonArray; 

Main Activity 主要活动

public class MainActivity extends Activity {

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

        NewsService newsService = new NewsService();
        newsService.execute();

//I need to use `jsonArray` in this part of my code

I have a number of solutions for your problem. 对于您的问题,我有很多解决方案。

  1. On the top what comes into my mind is that you pass the context of activity class as a data member of your async task class, then when the work is donein onPostExecute 最重要的是,您将活动类的上下文作为异步任务类的数据成员传递,然后在onPostExecute中完成工作时

    ((YourActivityName)context).createDynamicImages(yourJsonArray); (((YourActivityName)context).createDynamicImages(yourJsonArray);

Before this you will need to save the context of your activity as data member of async task class 在此之前,您需要将活动的上下文另存为异步任务类的数据成员

YourAsyncTask task = new YourAsyncTask(this);
task.execute();

and so the constructor of your async task class will become 因此您的异步任务类的构造函数将变为

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

One easy way to do this is defining an interface as your AsyncTask 's callback. 一种简单的方法是将interface定义为AsyncTask的回调。 Here is an example : 这是一个例子:

public interface Callback {
    void processData(DataType data);
}

and in your MainActivity you should implement that interface : 在您的MainActivity您应该implementinterface

public class MainActivity extends Activity  implements Callback {
    ...
    void processData(DataType data) {
     //your code here
    }
}

and in your calling code : 并在您的调用代码中:

new NewService(this).execute();

and your NewService class : 和您的NewService类:

public class NewService extends AsyncTask ... {
    ...
    Callback cb;
    public NewService(Callback cb) {
    this.cb = cb;
    }
    ...
}

and call your Callback method in onPostExecute 并在onPostExecute调用您的Callback方法

void onPostExecute(DataType data) {
    cb(data);
}

AsynTask.doInBackground runs on the Background , Not on the main thread, So you should use onPostExecute (this method runs after the task is done) in case you want process data on the main thread including UI updates, You can achieve that with using an interface inside your AsyncTask class: AsynTask.doInBackgroundBackground上运行,而不是在主线程上运行,因此,如果要在主线程上处理数据(包括UI更新),则应使用onPostExecute (此方法在任务完成后运行) ,可以使用AsyncTask类内部的interface

    interface OnJsonArrayReceive {
    void onReceive(JSONArray array);
    }

AsyncTask class will look like this: AsyncTask类将如下所示:

   class SomeTask extends AsyncTask<String, Void, JSONArray> {

    OnJsonArrayReceive mOnJsonArrayRecieve;

    public SomeTask(OnJsonArrayRecieve listener) {
        mOnJsonArrayRecieve = listener;
    }

    @Override
    protected JSONArray doInBackground(String... params) {
        //do something with and return your array
        //this runs on background
        return jsonArray;
    }

    @Override
    protected void onPostExecute(JSONArray jsonArray) {
        //This runs on main thread
        if (mOnJsonArrayReceive != null) {
            mOnJsonArrayReceive.onReceive(jsonArray);
        }
    }
}

This class takes a OnJsonArrayRecieve listener as argument (that is implemented in the MainActivity ) and when the data process on background is done onRecieve will be called, use it in your code like this : 此类使用OnJsonArrayRecieve侦听器作为参数(在MainActivity实现),并且在完成后台数据处理onRecieve将在其代码中使用它,如下所示:

    new SomeTask(new OnJsonArrayRecieve() {
        @Override
        public void onReceive(JSONArray array) {
            //do something with json array
        }
        }).execute(someArgument);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM