将值从onPostExecute传递给onCreate

时间:2018-07-26 12:22:08

标签: android android-activity

我正在运行一个查询,以从数据库中收集YouTube ID。 AsyncTask 工作正常,我获得了信息,但无法将其从onPostExecute传递给onCreate。

这是我尝试做的事情。

  1. youtubeIdCode设为全局变量。
  2. 运行查询以从数据库获取ID。
  3. 返回doInBackground中的youtubeid。
  4. 在onPostExecute中设置youtubeIdCode = doInBackground的结果。
  5. 尝试在onCreate中调用youtubeIdCode,以查看onPostExecute的结果是否传递给youtubeIdCode。这是我遇到的问题。它没有从onPostExecute传递到onCreate。如何传递它,因为在onCreate中,我将需要ID来形成YouTube网址。

    //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.");
        youtubeIdCode = "";
    
        loadMovieData();
        String test = "The value is" + youtubeIdCode;
        Log.v("youtube code test", test);
    
        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);
    
    }
    
    public class FetchTrailer extends AsyncTask<String, Void, String> {
    
        @Override
        protected String 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 youtubeId;
        }
    
        @Override
        protected void onPostExecute(String s) {
            youtubeIdCode = s;
            Log.v("onposttest", s);
        }
    }
    
    //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();
        }
     }
    }
    

3 个答案:

答案 0 :(得分:2)

我认为您需要重新考虑应用程序的逻辑。使用AsyncTask的主要思想是任务运行时主线程不会阻塞。

这意味着onCreate()不应等待AsyncTask完成以继续执行,这就是您所暗示的应该发生的情况。

应用程序的思考方式是,您要使用youtube id进行URL设置,并在任务完成时通过onPostExecute()触发任何附加处理。

答案 1 :(得分:0)

只需要对var进行设置,就需要输入te值,然后onPostExecute只需调用该setter函数并在AsyncTask中传递var的值,然后使用一种方法来获取小部件上的文本(如果您必须在传递值之前将其设置为空。

也尝试在单独的类中执行AsyncTask

AsyncTask OnPostExecute

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.ComponentModel.Annotations" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> 
        <bindingRedirect oldVersion="0.0.0.0-4.2.1.0" newVersion="4.2.1.0" /> 
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

在您的情况下,setupData看起来与此类似

 @Override
    protected void onPostExecute(List<ListaLineal> superlistItems) {
        super.onPostExecute(superlistItems);


        activity.setSuperListItems(superlistItems); -> this retrieve the value of a list that I was using (I got the value of the list in doInBackground)
        activity.setupData(); -> method for setting up data
    }

答案 2 :(得分:0)

在致电asynTask时,您可以这样做,但我不确定它是否可以正常工作。

new FetchTrailer(){
     @Override
     protected void onPostExecute(Object o) {
     super.onPostExecute(o);
  }
}.execute()