管理android

时间:2015-08-13 00:11:06

标签: java android asynchronous

嘿大家所以我只是开始在线培训应用程序的第二部分并尝试调整我的异步任务以从电影数据库中获取电影评论。完全不同的异步任务似乎应该有一个更好的方法。以下是仅获取电影数据的当前异步任务实现。

问题是如何向此添加另一个异步任务,以便从此网址/电影/ {id} /视频中重新审核电影评论。

public FetchMovieData(Context context, GridView grid, boolean sortType, ITaskCompleteListener listener) {
    mContext = context;
    this.mMoviesGrid = grid;
    this.mSortByMostPopular = sortType;
    this.mTaskCompleteListener = listener;
}

@Override
protected Void doInBackground(String... params) {

    // These two need to be declared outside the try/catch
    // so that they can be closed in the finally block.
    HttpURLConnection urlConnection = null;
    BufferedReader reader = null;

    try {
        URL url;
        if(mSortByMostPopular)
            url = new URL(mContext.getString(R.string.picasso_url_popular_movies));
        else
            url = new URL(mContext.getString(R.string.picasso_url_highest_rated));

        // Create the request to OpenWeatherMap, and open the connection
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();

        // Read the input stream into a String
        InputStream inputStream = urlConnection.getInputStream();
        StringBuffer buffer = new StringBuffer();
        if (inputStream == null) {
            // Nothing to do.
            mMovieJsonStr = null;
        }
        reader = new BufferedReader(new InputStreamReader(inputStream));

        String line;
        while ((line = reader.readLine()) != null) {
            // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
            // But it does make debugging a *lot* easier if you print out the completed
            // buffer for debugging.
            buffer.append(line + "\n");
        }

        if (buffer.length() == 0) {
            // Stream was empty.  No point in parsing.
            mMovieJsonStr = null;
        }
        mMovieJsonStr = buffer.toString();
    } catch (IOException e) {
        Log.e("PlaceholderFragment", "Error ", e);
        // If the code didn't successfully get the weather data, there's no point in attempting
        // to parse it.
        mMovieJsonStr = null;
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException e) {
                Log.e("PlaceholderFragment", "Error closing stream", e);
            }
        }
    }

    return null;
}

@Override
protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);
    if(mMovieJsonStr != null)
        Constants.mMovies = MovieDataParser.getMovieData(mMovieJsonStr);

    mTaskCompleteListener.onTaskCompleted(); //Task completed alert UI that we have our data
}

所以有人建议使用Retrofit而不是多个异步任务。这似乎是一个好主意,但我很难理解它应该如何工作。目前我有一个WebService类接口,我正在尝试使用它来检索这两部电影,我将添加评论然后预告片。问题是如果我将基本网址设置为" http://api.themoviedb.org"我得到的网址必须以" /"开头在logcat。

当前代码:

public class WebService {
  public List<Movie> getMovies() {

    RestAdapter retrofit = new RestAdapter.Builder()
            .setEndpoint("http://api.themoviedb.org")
            .build();

    MovieDBService service = retrofit.create(MovieDBService.class);

    return service.listMovies("movies");
   }
 }

public interface MovieDBService {
                     @GET("/3/discover/{switchterm}sort_by=popularity.desc&api_key=d273a1a1fb9390dab9  7ac0032b12366a")

  List listMovies(@Path("switchterm") String switchterm);
}

//In code getting movies
WebService service = new WebService();
List movies = service.getMovies();

2 个答案:

答案 0 :(得分:1)

我认为你有很多可能做到这一点。你可以遵循这种方法:当第一个完成后,再向第二个AsyncTask添加一个调用,并向其传递一个带有视频ID的字符串列表:

public class FetchMovieData extends AsyncTask<Void, Void, Void> {

    protected Boolean doInBackground() {
       try {
           String movieJSONString = getJSONMovies();
           String[] ids = parseIdsFromJSON(movieJSONString);
           if(ids.lenth != 0) {
               FetchMovieReviews moviesReviewsAsyncTask = new FetchMovieReviews();
               moviesReviewsAsyncTask.execute(ids);
           } else {
               return false;
           }

           return true;
        } catch (Exception e) {
           return false;
        }
    }

    protected String getJSONMovies() {
       //with the code you post, return the json string
    }

    protected String[] parseIdsFromJSON(String JSON) {
        //parse the json and get the ids and return
        //return {"1","2","3"}
    }
}

public class FetchMovieReviews extends AsyncTask<String[], Void, Void> {

    protected Void doInBackground(String[]... params) {
       for(String id : params[0]) {
           //call the web service and pass the id
       }

       return null;
    }
}

您可以将所有功能用于管理对MoviesRESTCalls类中的Web服务的调用,以及管理MoviesJSONParser类或类似内容中的json,并且代码将更加清晰。

答案 1 :(得分:1)

所以我最终得到的是使用Web服务的Retrofit库。感谢大家的帮助,让我知道你的想法。

public Context mContext;
private MovieJSON mMovieData;
private ReviewJSON mMovieReviews;
private VideoJSON mMovieVideos;
public boolean mSortByMostPopular;
ITaskCompleteListener mTaskCompleteListener;

public FetchMovieData(Context context, boolean sortType, ITaskCompleteListener listener) {
    mContext = context;
    this.mSortByMostPopular = sortType;
    this.mTaskCompleteListener = listener;
}

public void getMovies() {
    new FetchMovies().execute();
}

public void getReviews() {
    new FetchReviews().execute();
}

public void getVideos() {
    new FetchTrailers().execute();
}

private class FetchMovies extends AsyncTask<String, Void, Void > {

    @Override
    protected Void doInBackground(String... params) {
        WebService service = new WebService();
        //TODO Re-Implement sorting
        mMovieData = service.getMovies();
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        if(mMovieData != null)
            Constants.mMovies = MovieDataParser.getMovieData(mMovieData);

        mTaskCompleteListener.onTaskCompleted(); //Task completed alert UI that we have our data
    }
}

private class FetchReviews extends AsyncTask<String, Void, Void > {

    @Override
    protected Void doInBackground(String... params) {
        WebService service = new WebService();
        mMovieReviews = service.getReviews();
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        if(mMovieReviews != null)
            Constants.mReviews = MovieDataParser.getReviewData(mMovieReviews);

        mTaskCompleteListener.onTaskCompleted(); //Task completed alert UI that we have our data
    }
}

private class FetchTrailers extends AsyncTask<String, Void, Void > {

    @Override
    protected Void doInBackground(String... params) {
        WebService service = new WebService();
        mMovieVideos = service.getVideos();
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        if(mMovieVideos != null)
            Constants.mTrailers = MovieDataParser.getVideoData(mMovieVideos);

        mTaskCompleteListener.onTaskCompleted(); //Task completed alert UI that we have our data
    }
}

//网络服务

public class WebService {

RestAdapter mRetrofit;

MovieDBService mService;

public WebService() {
    mRetrofit = new RestAdapter.Builder()
            .setEndpoint("http://api.themoviedb.org")
            .build();
    mService = mRetrofit.create(MovieDBService.class);
}

public MovieJSON getMovies() {
    return mService.listMovies("");
}

public ReviewJSON getReviews() {
    return mService.listReviews("76341");
}

public VideoJSON getVideos() {
    return mService.listVideos("76341");
}

}