【问题标题】:How to get result on onPostExecute from a separate Asynctask class to another fragment class?如何从单独的 Asynctask 类获取 onPostExecute 的结果到另一个片段类?
【发布时间】:2016-03-23 22:07:46
【问题描述】:

我尝试了它,但它没有显示任何内容,我不知道如何从单独的 AsyncTask 类获取 onPostExecute 方法的结果到片段类。 请帮帮我...

public class MainActivity extends AppCompatActivity {

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

        getFragmentManager()
                .beginTransaction()
                .add(R.id.Fragment_Container, new ForecastFragment(),
                        ForecastTask.class.getSimpleName())
                .commit();

    }

2- AsyncTask 类

public class ForecastTask extends AsyncTask<String, String, `List<MovieModel>> {`

    private final String LOG_TAG = ForecastTask.class.getSimpleName();
    private List<MovieModel> movieModelList;
    public AsyncResponse delegate=null;

    public ForecastTask(AsyncResponse listener) {
        delegate = listener;
    }

    @Override
    protected List<MovieModel> doInBackground(String... params) {
        if (params.length == 0) {
            return null;
        }

        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(param[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();

            InputStream inputStream = connection.getInputStream();
            if (inputStream == null) {
                return null;
            }

            reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuffer buffer = new StringBuffer();
            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            JSONObject jsonObject = new JSONObject(buffer.toString());
            JSONArray jsonArray = jsonObject.getJSONArray("results");

            movieModelList= new ArrayList<>();
            //adding JSON Array data into MovieModel Class object
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject finalObject = jsonArray.getJSONObject(i);
                MovieModel movieModel = new MovieModel();
                movieModel.setId(finalObject.getInt("id"));
                movieModel.setTitle(finalObject.getString("title"));
                movieModel.setPoster_path(finalObject.getString("poster_path"));

            }
            return movieModelList;
        } catch (JSONException | IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public ForecastTask() {
        super();
    }

    @Override
    protected void onPostExecute( List<MovieModel> movieModels) {
        delegate.processFinish(movieModels);
    }
}

3- 片段类

public class ForecastFragment extends Fragment implements AsyncResponse {

    private String Popular = "http://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=xxxxxxxxxxxxxxxxxxxxxxxxxx";

    private List<MovieModel> movieModels;
    private static final String STATE_MOVIES ="state_movies";
    CustomAdapter customAdapter=null;
    GridView gridView=null;
    View rootView=null;
    ForecastTask forecastTask;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }    

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.activity_main, container, false);
        gridView=(GridView)rootView.findViewById(R.id.gridView);
        movieModels=new ArrayList<MovieModel>();
            forecastTask=new ForecastTask(this);
            forecastTask.delegate = this;
            forecastTask.execute(Popular);

        customAdapter = new CustomAdapter(getActivity(), movieModels);
        gridView.setAdapter(customAdapter);   

        return rootView;
    }

    @Override
    public void processFinish(List<MovieModel> movieModels) {
        this.movieModels=movieModels;
    }
}

4- 异步响应接口

public interface AsyncResponse {
    void processFinish(List<MovieModel> movieModels);
}

【问题讨论】:

  • 如何将结果从单独的 Asynctask 类获取到单独的片段类?请帮帮我...

标签: android android-fragments android-studio android-asynctask asynctaskloader


【解决方案1】:

您没有在movieModelList 中添加您的Movie 项目。这就是为什么它仍然是空的。你必须修改喜欢 -

movieModelList= new ArrayList<>();
            //adding JSON Array data into MovieModel Class object
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject finalObject = jsonArray.getJSONObject(i);
                MovieModel movieModel = new MovieModel();
                movieModel.setId(finalObject.getInt("id"));
                movieModel.setTitle(finalObject.getString("title"));
                movieModel.setPoster_path(finalObject.getString("poster_path"));


movieModelList.add(movieModel); //Add this line 




            }

此外,您必须在 processFinish() 回调中设置或刷新适配器。 因为ForecastTask 将在不同的线程中运行并且是异步的。

 @Override
    public void processFinish(List<MovieModel> movieModels) {
        this.movieModels=movieModels;
        customAdapter = new CustomAdapter(getActivity(), movieModels);
        gridView.setAdapter(customAdapter);
    }

【讨论】:

  • movieModelList= new ArrayList(); for (int i = 0; i
  • 能否请您查看我在 github 上的项目链接:github.com/superssingh/MoviesInfoApp.git
  • 添加后有什么问题?
  • 没有错误...但是我不知道为什么来自 forecastFragment 类的movieModels 不能从 AsyncTask 类中获取结果数据...这是我的第一个应用程序,当我将 asynctask 类转换为片段然后它可以工作但我想学习如何从单独的 asynctask 类中获取结果并显示。
  • 伟大的兄弟,,,,无限
猜你喜欢
  • 2016-02-20
  • 2012-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多