如何从单独的Asynctask类到另一个片段类获取onPostExecute的结果?

时间:2016-03-23 22:07:46

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

我尝试但它没有显示任何内容,我不知道如何从单独的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- AsyncResponse接口

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

1 个答案:

答案 0 :(得分:0)

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

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);
    }