Tarik Hodzic
Tarik Hodzic

Reputation: 357

Passing a string from AsyncTask to onCreate or other Activities

I am trying to query JSON data on a background thread using AsyncTask and use one of the values from the query in onCreate of the same Activity. How should I do this? Should I use intents or is there a more intuitive and better way of doing it?

In my code below, I am trying to pull the youtube ID using an AsyncTask out of an online database. It works because when I log the value inside the AsyncTask, the correct youtube ID is shown. But I need to use this ID in onCreate so that I can use it to create the full youtube URL. How can I pass the youtube ID string from doInBackground to onCreate? The id is stored in the variable youtubeId

 //Activity needs added to manifest.
public class DetailsActivity extends AppCompatActivity {

    //LOG tag for debugging
    private static final String TAG = "GalleryActivity";

    String youtubeIdCode;

    //Override on Create and set contentView to new activity_details layout.
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_details);
        //Log for debugging so we can tell if activity started successfully.
        Log.d(TAG, "onCreate: started.");

        loadMovieData();

        Intent intent = getIntent();
        Movie movie = intent.getParcelableExtra("movie");

        String image = movie.getMoviePoster();
        String title = movie.getTitle();
        String releaseDate = movie.getDate();
        String voteAverage = movie.getVoteAverage();
        String plot = movie.getPlot();

        ImageView poster = findViewById(R.id.details_image);
        Picasso.with(this).load(image).into(poster);

        TextView name = findViewById(R.id.details_title);
        name.setText((getResources().getString(R.string.movie_title)) + " " + title);

        TextView dateRelease = findViewById(R.id.details_release_date);
        dateRelease.setText((getResources().getString(R.string.release_date)) + " " + releaseDate);

        TextView averageVote = findViewById(R.id.details_voter_average);
        averageVote.setText((getResources().getString(R.string.vote_average)) + " " + voteAverage);

        TextView moviePlot = findViewById(R.id.details_plot);
        moviePlot.setText((getResources().getString(R.string.plot)) + " " + plot);

        ImageView watchTrailer = findViewById(R.id.imageView);

//        watchTrailer.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(trailerUrl.toString()));
//                Log.v("OnClick URL",trailerUrl.toString());
//                startActivity(intent);
//            }
//        });

    }

    public class FetchTrailer extends AsyncTask<String, Void, Void> {

        @Override
        protected Void doInBackground(String... strings) {
            final String YOUTUBE_ID = "id";
            final String RESULTS = "results";
            String youtubeId = " ";

            Intent intent = getIntent();
            Movie movie = intent.getParcelableExtra("movie");
            String id = movie.getID();

            final URL trailerUrl = NetworkUtils.buildUrlTrailer(id);
            Log.v("Built trailer url", trailerUrl.toString());

            try {
                String jsonResponse = NetworkUtils.getReponseFromHttpUrl(trailerUrl);

                JSONObject moviesObject = new JSONObject(jsonResponse);

                JSONArray resultsArray = moviesObject.getJSONArray(RESULTS);

                for(int i = 0; i < resultsArray.length(); i ++){
                    JSONObject movieObject = resultsArray.getJSONObject(i);
                    youtubeId = movieObject.getString(YOUTUBE_ID);
                    Log.v("youtubeid", youtubeId);
                }

            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }
    }

    //Tell the new method to get the data based on the search term within the url.
    private void loadMovieData() {
        //If there is a network connection, fetch the data.
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null &&
                activeNetwork.isConnectedOrConnecting();
        if (isConnected) {
            new FetchTrailer().execute();
        } else {
            Toast toast = Toast.makeText(this, getString(R.string.no_internet_toast), Toast.LENGTH_LONG);
            toast.show();
        }
    }
}

Upvotes: 0

Views: 41

Answers (2)

Sahil
Sahil

Reputation: 972

Seems youtubeId is a pre-requisite for your DetailsActivity. So we would need youtubeId prior to DetailsActivity initialization.

In your previous activity from where user can be landed to DetailsActivity , before calling startActivity(intent) call your

loadMovieData()

method as is, you would have to declare method in prior activity. After that pass the youtubeId through intent to DetailsActivity, and you can retrieve value in oncreate():

Intent myIntent = new Intent(CurrentActivity.this, 
NextActivity.class);
myIntent.putExtra("youtubeId", value); //Optional parameters
CurrentActivity.this.startActivity(myIntent);

Extras are retrieved on the other side via:

@Override
protected void onCreate(Bundle savedInstanceState) {
 Intent intent = getIntent();
 String value = intent.getStringExtra("youtubeId"); //if it's a string you 
 stored.
}

Upvotes: 1

keerthana murugesan
keerthana murugesan

Reputation: 581

You can use a Callback Listener to achieve this

public interface FetchTrailerListener {
   public void onTrailerFetched(String youtubeId);
}

Make DetailsActivity to implement this. Pass this listener reference to asynctask when you are instantiating it.In this way from your postexecute notify the activity through this listener.

protected void onPostExecute( String youtubeId) {
   fetchTrailerListenr.onTrailerFetched(youtubeId);
}

Upvotes: 0

Related Questions