多个片段的异步任务

时间:2015-09-27 20:53:27

标签: android android-fragments android-asynctask

在应用程序中有导航抽屉,每个抽屉代表一个片段,每个片段都有一个AsyncTask来下载单独的数据。我正在通过这些代码更改碎片

private void setupNavigationDrawerContent(NavigationView navigationView) {
    navigationView.setNavigationItemSelectedListener(
            new NavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(MenuItem menuItem) {
                    switch (menuItem.getItemId()) {
                        case R.id.home_main:
                            menuItem.setChecked(true);
                            actionBar.setTitle("Home");
                            drawerLayout.closeDrawer(GravityCompat.START);
                            if(getSupportFragmentManager().findFragmentByTag("ranking")==null)
                                {
                                getSupportFragmentManager().beginTransaction().add(R.id.list_view_container,
                                        new Home(), "ranking").
                                        addToBackStack("ranking").
                                        setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                                        .commit();
                                }
                            else
                                {
                                getSupportFragmentManager().popBackStack("ranking", 0);
                                }
                            return true;
                        case R.id.national_events:
                            menuItem.setChecked(true);
                            actionBar.setTitle("National events");
                            drawerLayout.closeDrawer(GravityCompat.START);
                            if(getSupportFragmentManager().findFragmentByTag("ranking3")==null)
                            {
                                getSupportFragmentManager().beginTransaction().add(R.id.list_view_container,
                                        new NationalEvents(), "ranking3").
                                        addToBackStack("ranking3").
                                        setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                                        .commit();
                            }
                            else
                            {
                                getSupportFragmentManager().popBackStack("ranking3", 3);
                            }
                            return true;
                        case R.id.workshops:
                            menuItem.setChecked(true);
                            actionBar.setTitle("Workshops");
                            drawerLayout.closeDrawer(GravityCompat.START);
                            if(getSupportFragmentManager().findFragmentByTag("ranking4")==null)
                            {
                                getSupportFragmentManager().beginTransaction().add(R.id.list_view_container,
                                        new Workshops(), "ranking4").
                                        addToBackStack("ranking4").
                                        setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                                        .commit();
                            }
                            else
                            {
                                getSupportFragmentManager().popBackStack("ranking4", 4);
                            }
                            return true;

用于下载数据的代码是

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {

    View home_view = inflater.inflate(R.layout.list_view, container, false);

    tf = Typeface.createFromAsset(getActivity().getAssets(), "fonts/cool_jazz.ttf");


    swipeLayout = (SwipeRefreshLayout) home_view.findViewById(R.id.swipe_container);
    swipeLayout.setColorSchemeColors(R.color.md_purple_500,
            R.color.md_deep_purple_A400,
            R.color.md_pink_500,
            R.color.md_red_500);

    mRecyclerView = (RecyclerView) home_view.findViewById(R.id.recycler_view);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    mRecyclerView.setItemAnimator(new DefaultItemAnimator());

    mProgressBar = (ProgressBar) home_view.findViewById(R.id.progress_bar);
    mProgressBar.setVisibility(View.VISIBLE);



    mDescription=(TextView)home_view.findViewById(R.id.desription);
    mDescription.setText(getString(R.string.national_events));
    mDescription.setTypeface(tf);

    iu1=(TextView)home_view.findViewById(R.id.iu1);
    iu1.setTypeface(tf);
    iu2=(TextView)home_view.findViewById(R.id.iu2);
    iu2.setTypeface(tf);
    iu3=(TextView)home_view.findViewById(R.id.iu3);
    iu3.setTypeface(tf);
    iu4=(TextView)home_view.findViewById(R.id.iu4);
    iu4.setTypeface(tf);
    iu5=(TextView)home_view.findViewById(R.id.iu5);
    iu5.setTypeface(tf);
    iu6=(TextView)home_view.findViewById(R.id.iu6);
    iu6.setTypeface(tf);



    internet=(RelativeLayout)home_view.findViewById(R.id.internet_unavailable);
    internet.setVisibility(View.GONE);
    Senturl = "http://javatechig.com/?json=get_recent_posts&count=45";
    new MainActivityData().execute(Senturl);

    swipeLayout.setOnRefreshListener(this);


    return home_view;
}
@Override
public void onCreate(Bundle savedInstanceState)

{
    super.onCreate(savedInstanceState);setRetainInstance(true);
}

@Override
public void onRefresh() {
    mProgressBar.setVisibility(View.GONE);
    internet.setVisibility(View.GONE);
    new MainActivityData().execute(Senturl);

}


public class MainActivityData extends AsyncTask<String,Void,Integer>
{
    @Override
    protected void onPreExecute() {
        getActivity().setProgressBarIndeterminateVisibility(true);
    }

    @Override
    protected Integer doInBackground(String... params) {
        Integer result = 0;
        HttpURLConnection urlConnection;

        try {
            URL url = new URL(params[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            int statusCode = urlConnection.getResponseCode();

            // 200 represents HTTP OK
            if (statusCode ==200 ) {
                BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = r.readLine()) != null) {
                    response.append(line);
                }
                parseResult(response.toString());
                result = 1; // Successful
            } else {
                result = 0; //"Failed to fetch data!";
            }
        } catch (Exception e){
            if(e.getLocalizedMessage()!=null){
                Log.d(TAG, e.getLocalizedMessage());
            }
        }
        return result; //"Failed to fetch data!";
    }

    @Override
    protected void onPostExecute(Integer result) {
        // Download complete. Let us update UI
        mProgressBar.setVisibility(View.GONE);
        swipeLayout.setRefreshing(false);
        mDescription.setVisibility(View.GONE);
        if (result == 1) {

            new Thread(new Runnable() {
                @Override
                public void run() {
                    mAdapter = new MembersAdapter(getActivity(),membersList);
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (mAdapter != null)
                            {
                                mRecyclerView.setAdapter(mAdapter);
                            }}
                    });
                }
            }).start();

        } else {
            internet.setVisibility(View.VISIBLE);
        }
    }
}


private void parseResult(String result) {
    try {
        JSONObject response = new JSONObject(result);
        JSONArray posts = response.optJSONArray("posts");
        membersList = new ArrayList<>();

        for (int i = 0; i < posts.length(); i++) {
            JSONObject post = posts.optJSONObject(i);
            Members item = new Members();
            item.setTitle(post.optString("title"));
            item.setThumbnail(post.optString("thumbnail"));
            item.setDescription(post.optString("content"));
            item.setDate(post.optString("date"));
            //item.setSub_title(post.optString("sub_title"));
            membersList.add(item);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

事情工作正常但是当我在非常短的时间间隔内更改多个片段时,应用程序正在崩溃。我认为这一切都是由于给系统提供了很多AysncTasks。可能是想暂停AsyncTask。

1 个答案:

答案 0 :(得分:0)

我建议将每个AsyncTask放在一个单独的非ui保留片段中(一个不包含任何视图的片段,并在setRetainInstance(true)中使用onCreate()方法进行初始化。{ {1}}会将数据加载到此片段中,并且在重新配置期间,由于AsyncTasks,它不会被销毁。然后,在重新配置之后,您可以从此片段中检索数据并按照您的意愿执行操作 - 填充适配器等等。