-1

I try it but it not show anything, I thing I don't know how to get result of onPostExecute method from separate AsyncTask class to fragment class. Please Help me...

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 class

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- Fragment class

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 Interface

public interface AsyncResponse {
    void processFinish(List<MovieModel> movieModels);
}
Santosh
  • 227
  • 1
  • 4
  • 18
  • How to get result from a separate Asynctask class to a separate fragment class? Please help me... – Santosh Mar 23 '16 at 22:11

1 Answers1

0

You are not adding your Movie item in movieModelList. That's why it remains empty. You have to modify like -

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 




            }

Also, You have to set or refresh the adapter in your processFinish() callback. Because ForecastTask will run in different thread and is asynchronous.

 @Override
    public void processFinish(List<MovieModel> movieModels) {
        this.movieModels=movieModels;
        customAdapter = new CustomAdapter(getActivity(), movieModels);
        gridView.setAdapter(customAdapter);
    }
Shadab Ansari
  • 7,022
  • 2
  • 27
  • 45
  • movieModelList= new ArrayList<>(); 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); } – Santosh Mar 23 '16 at 22:25
  • Could you please check my project on github link: https://github.com/superssingh/MoviesInfoApp.git – Santosh Mar 23 '16 at 22:26
  • What is the problem after adding it ? – Shadab Ansari Mar 23 '16 at 22:28
  • No error... But I don't know Why movieModels from forecastFragment class not get result data from AsyncTask Class... This is my first app when I past asynctask class into fragment then it works but I want to learn how to get result from separate asynctask class and show. – Santosh Mar 23 '16 at 22:36
  • Great Brother,,,, Infinite – Santosh Mar 23 '16 at 22:43
  • Infinite Thanks to You... I am Tired with that...Lots of thanks again... :) – Santosh Mar 23 '16 at 22:44
  • It works... I have been trying for 15 days and you solved it... Lots of Thanks to you... Great help :) – Santosh Mar 23 '16 at 22:45