从片段开始活动

时间:2015-12-25 11:37:17

标签: android android-fragments android-intent android-activity android-asynctask

我有两个AsyncTasks(FetchDataFromApi,FetchDataFromDb),它们都有“onPostExecute”方法的实现,每个方法都通过调用passDataToDetailedActivity方法启动DetailActivity。 每当我从FetchFromApi onPostExecute方法启动DetailedActivity时它运行良好, 但整个问题是当我尝试从FetchFromDb onPostExecute方法启动DetailedActivity时,cuz的一些组件并没有出现,而其他组件也没有。

请帮助,提前谢谢:)

public class MainFragment extends Fragment {

public final static String API_KEY = "b932ba435fc93a5944938fe9d44cd198";
public final String BASE_URL = "http://api.themoviedb.org/3/discover/movie?sort_by=&api_key=";


ArrayList<Movie> movies = new ArrayList<>();
movieAdapter adapter;
GridView gridview;
DbOpenHelper dbOpenHelper;
ArrayList<Movie> FavList = new ArrayList<>();


public MainFragment() {
}


public MainFragment(String SortBy) {
    if (SortBy == "fav") {
        new FetchDataFromDb().execute();
    } else {
        new FetchDataFromApi(SortBy).execute();
    }
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_main, container, false);
    gridview = (GridView) getActivity().findViewById(R.id.gridView);
    adapter = new movieAdapter(getActivity(), R.layout.movie_item, movies);
    return view;
}


class FetchDataFromApi extends AsyncTask<String, Void, Boolean> {
    String SORT_CATEGORY;

    FetchDataFromApi(String paramUrl) {
        SORT_CATEGORY = paramUrl;
    }

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

        HttpURLConnection urlConnection = null;

        try {
            Uri uriBuilder = Uri.parse(BASE_URL).buildUpon()
                    .appendQueryParameter("sort_by", SORT_CATEGORY)
                    .appendQueryParameter("api_key", API_KEY)
                    .build();
            URL url = new URL(uriBuilder.toString());
            urlConnection = (HttpURLConnection) url.openConnection();

            InputStream in = urlConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
            StringBuilder sb = new StringBuilder();
            String line;

            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }

            String response = sb.toString();
            ParseJsonData(response);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            urlConnection.disconnect();
        }

        return null;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        gridview.setAdapter(adapter);
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                PassDataToDetailedActivity(position);
            }
        });
    }


    private void ParseJsonData(String response) throws JSONException {
        String PosterBaseUrl = "http://image.tmdb.org/t/p/";
        String LargePoster = "w185";
        String SmallPoster = "";
        final String RESULTS = "results";
        final String ORIGINAL_TITLE = "original_title";
        final String OVERVIEW = "overview";
        final String RELEASE_DATE = "release_date";
        final String POSTER_PATH = "poster_path";
        final String VOTE_AVERAGE = "vote_average";
        final String POPULARITY = "popularity";
        final String ID = "id";



        JSONObject jsono = new JSONObject(response);
        Log.v("Json", response);
        JSONArray jarray = jsono.getJSONArray(RESULTS);

        for (int i = 0; i < jarray.length(); i++) {
            JSONObject object = jarray.getJSONObject(i);

            String id = object.getString(ID);
            String title = object.getString(ORIGINAL_TITLE);
            String releaseDate = object.getString(RELEASE_DATE);
            String overView = object.getString(OVERVIEW);
            String voteAverage = object.getString(VOTE_AVERAGE);
            String popularity = object.getString(POPULARITY);
            String posterPath = object.getString(POSTER_PATH);

            String BigPoster = PosterBaseUrl + LargePoster + posterPath;
            String MinPoster = PosterBaseUrl + SmallPoster + posterPath;

            Movie m = new Movie();
            m.setId(id);
            m.setTitle(title);
            m.setReleaseDate(releaseDate);
            m.setOverView(overView);
            m.setVoteAverage(voteAverage);
            m.setPopularity(popularity);
            m.setLargePoster(BigPoster);
            m.setMinPoster(MinPoster);

            movies.add(m);
        }
    }
}

private void PassDataToDetailedActivity(int position) {

    String id = movies.get(position).getId();
    String title = movies.get(position).getTitle();
    String releaseDate = movies.get(position).getReleaseDate();
    String overView = movies.get(position).getOverView();
    String voteAverage = movies.get(position).getVoteAverage();
    String popularity = movies.get(position).getPopularity();
    String BigPoster = movies.get(position).getLargePoster();
    String MinPoster = movies.get(position).getMinPoster();

    Intent intent = new Intent(MainActivity.context, DetailedActivity.class);
    intent.putExtra("id", id);
    intent.putExtra("title", title);
    intent.putExtra("releaseDate", releaseDate);
    intent.putExtra("overView", overView);
    intent.putExtra("voteAverage", voteAverage);
    intent.putExtra("popularity", popularity);
    intent.putExtra("MaxPoster", BigPoster);
    intent.putExtra("MinPoster", MinPoster);
    startActivity(intent);
}

public class FetchDataFromDb extends AsyncTask<String, Void, Boolean> {

    @Override
    protected Boolean doInBackground(String... params) {
        dbOpenHelper = new DbOpenHelper(MainActivity.context);
        movies.clear();
        movies = dbOpenHelper.getAllFavoritePosters();
        Log.v("database count", Integer.toString(FavList.size()));
        return null;
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        super.onPostExecute(aBoolean);
        Log.v("database status", "Finished From Db");

        adapter.notifyDataSetChanged();
        gridview.setAdapter(adapter);
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                PassDataToDetailedActivity(position);
            }
        });
    }
}

}

1 个答案:

答案 0 :(得分:0)

试试这段代码:

@Service
public class AuthenticationService {

    private IAuthentication auth;

    @PostConstruct
    protected void init() {
        boolean useDb = ...;   //got from db
        this.auth = ...; //choose correct one
    }
    public boolean authenticate(...) {        
        return auth.authenticate(...);
    }
}

注意:将gridListener从该post post方法

中取出