asynctask

时间:2015-04-24 05:55:20

标签: android android-fragments android-asynctask navigation-drawer

我在其中一个片段中使用带有asynctask的导航抽屉。只要单击导航抽屉中的元素以启动该片段,即使在asynctask完成后,我的导航抽屉也会停止工作。我可以点击导航抽屉并将其打开,但每当我点击导航抽屉中的其他项目时,它就会关闭而不会在导航抽屉中加载与该项目相关联的片段。

主要活动代码:

package com.example.home;

import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import java.io.File;
import java.io.IOException;
import java.net.HttpCookie;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.apache.http.cookie.Cookie;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.fmapp.R;
import com.example.fmapp.StartActivity;
import com.example.fmapp.R.id;
import com.example.fmapp.R.layout;
import com.example.fmapp.R.menu;

import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;

@SuppressLint("NewApi")
public class Home extends Activity implements ActionBar.OnNavigationListener{
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
    private String[] mDrawerTitles;


    static ProgressBar bar;

    private String mCurrentPhotoPath;

    private final static int FILECHOOSER_RESULTCODE=1;

    //public AsyncHttpUpload uploadThread = null;

    public ArrayAdapter<String> adapter = null;
    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        Log.i("start","started");
        /*
        if ((savedInstanceState != null) && (savedInstanceState.getString("currPath")) != null){
            mCurrentPhotoPath = savedInstanceState.getString("currPath");
        }
        */
        bar = (ProgressBar) this.findViewById(R.id.progressBar);

        ActionBar actionBar = getActionBar();
        actionBar.setDisplayShowTitleEnabled(true);


        if (UserInfo.userId == null){
            //fetchUserData();
        }
        else{
            //UserInfo.populateSpinner(adapter);
        }
        mTitle = mDrawerTitle = getTitle();
        mDrawerTitles = getResources().getStringArray(R.array.planets_array);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        // set a custom shadow that overlays the main content when the drawer opens
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
        // set up the drawer's list view with items and click listener
        mDrawerList.setAdapter(new ArrayAdapter<String>(this,
                R.layout.drawer_list_item, mDrawerTitles));
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        // enable ActionBar app icon to behave as action to toggle nav drawer
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        // ActionBarDrawerToggle ties together the the proper interactions
        // between the sliding drawer and the action bar app icon
        mDrawerToggle = new ActionBarDrawerToggle(
                this,                  /* host Activity */
                mDrawerLayout,         /* DrawerLayout object */
                R.drawable.ic_drawer,  /* nav drawer image to replace 'Up' caret */
                R.string.drawer_open,  /* "open drawer" description for accessibility */
                R.string.drawer_close  /* "close drawer" description for accessibility */
                ) {
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(mDrawerTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            selectItem(0);
        }
    }

    @SuppressLint("NewApi")
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.home, menu);
        //MenuItem item = menu.findItem(R.id.accounts_spinner);
        return super.onCreateOptionsMenu(menu);
    }


    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        switch (item.getItemId()) {
            case R.id.action_logout:
                logOut();
                return true;
            case R.id.action_change_pw:
                Intent intent = new Intent(this, ChangePw.class);
                this.startActivity(intent);
                return true;
           // case R.id.accounts_spinner:
            //  Log.i("spinner","spinner click");
            //  return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }


    @SuppressLint("NewApi")
    private void logOut() {
        // TODO Auto-generated method stub
        Log.i("logout","to logout");
        //clear data
        UserInfo.chosenAccount = null;
        //clear client cookies
        String cookieString = "";
        Log.i("number of cookies",Integer.toString(StartActivity.cookieManager.getCookieStore().getCookies().size()));
        if(StartActivity.cookieManager.getCookieStore().getCookies().size() != 0){
            //HttpCookie cookie = (HttpCookie) StartActivity.cookieManager.getCookieStore().getCookies().toArray()[0];
            //HttpCookie cookie = (HttpCookie) StartActivity.cookieManager.getCookieStore().getCookies().get(0);
            int login_cookie_index = 0;
            List<HttpCookie> cookieList = (List<HttpCookie>) StartActivity.cookieManager.getCookieStore().getCookies();
            //TODO: search for ltsid cookie
            for (int cookie_iter = 0; cookie_iter < cookieList.size(); cookie_iter++){
                if((cookieList.get(cookie_iter).getName()).equals("ltsid")){
                    login_cookie_index = cookie_iter;
                    break;
                }
            }
            HttpCookie cookie = cookieList.get(login_cookie_index);
            cookieString = cookie.getValue();
            StartActivity.cookieManager.getCookieStore().removeAll();
        }

        //clear server sessionId
        JSONObject data = new JSONObject();
        JSONObject name = new JSONObject();
        JSONArray arg = new JSONArray();
        try{
            data.put("requestCommand", "LogOut");
            name.put("name","sessionId");
            name.put("type", "String");
            name.put("value", cookieString);
            arg.put(name);
            data.put("args", arg);
            String finaldata = data.toString();
            new AsyncHttpLogout(this).execute(finaldata);
        } catch (JSONException e2) {
            e2.printStackTrace();
        }
        this.finish();
    }



    public boolean onKeyDown(int keyCode, KeyEvent event) {
           if(event.getAction() == KeyEvent.ACTION_DOWN){
               switch(keyCode)
               {
               case KeyEvent.KEYCODE_BACK:
                   finish();
                   return true;
               } //TODO:can go forward
            }
           return super.onKeyDown(keyCode, event);
       }


    @SuppressLint("NewApi")
    private void fetchUserData() {

        int login_cookie_index = 0;
        List<HttpCookie> cookieList = (List<HttpCookie>) StartActivity.cookieManager.getCookieStore().getCookies();
        //TODO: search for ltsid cookie
        for (int cookie_iter = 0; cookie_iter < cookieList.size(); cookie_iter++){
            if((cookieList.get(cookie_iter).getName()).equals("ltsid")){
                login_cookie_index = cookie_iter;
                break;
            }
        }
        HttpCookie cookie = cookieList.get(login_cookie_index);

        JSONObject data = new JSONObject();
        JSONObject sid = new JSONObject();
        JSONArray arg = new JSONArray();
        try {
            data.put("requestCommand","FetchInfo");
            sid.put("name","sessionId");
            sid.put("type", "String");
            sid.put("value", cookie.getValue());
            arg.put(sid);
            data.put("args", arg);
        } catch (JSONException e2) {
            e2.printStackTrace();
        }
        Log.i("fetch data",data.toString());
        String finaldata = data.toString();
        //View mySpinnerView = this.findViewById(R.id.accounts_spinner);
        new AsyncGetAccountInfo(this,adapter).execute(finaldata);

    }


    @Override
    public boolean onNavigationItemSelected(int position, long itemId) {
        Log.i("arg0",Integer.toString(position));
        //Log.i("arg1",Long.toString(itemId));
        //UserInfo.chosenAccount = UserInfo.accountArray.get(position);
        //TODO: fix default account
        return false;
    }



    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
      super.onSaveInstanceState(savedInstanceState);
      // Save UI state changes to the savedInstanceState.
      // This bundle will be passed to onCreate if the process is
      // killed and restarted.
      savedInstanceState.putString("currPath", mCurrentPhotoPath);
      //savedInstanceState.
      // etc.
    }

    /*
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
          super.onConfigurationChanged(newConfig);
    }
    */  
    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position);
        }
    }

    private void selectItem(int position) {
        // update the main content by replacing fragments
        if (position ==0){
            Fragment fragment = new OrderForm();
            Bundle args = new Bundle();
            args.putInt(OrderForm.ARG_LIST_INDEX, position);
            fragment.setArguments(args);

            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

            // update selected item and title, then close the drawer
            mDrawerList.setItemChecked(position, true);
            setTitle(mDrawerTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
        }
        else if (position ==1){
            Fragment fragment = new ServicesGrid();
            Bundle args = new Bundle();
            args.putInt(ServicesGrid.ARG_LIST_INDEX, position);
            fragment.setArguments(args);

            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

            // update selected item and title, then close the drawer
            mDrawerList.setItemChecked(position, true);
            setTitle(mDrawerTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);

        }
        else if (position ==2){
            Fragment fragment = new UserProfile();
            Bundle args = new Bundle();
            args.putInt(UserProfile.ARG_LIST_INDEX, position);
            fragment.setArguments(args);

            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

            // update selected item and title, then close the drawer
            mDrawerList.setItemChecked(position, true);
            setTitle(mDrawerTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
        }
        else if (position ==3){
            Fragment fragment = new OrderList();
            Bundle args = new Bundle();
            args.putInt(OrderList.ARG_LIST_INDEX, position);
            fragment.setArguments(args);

            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

            // update selected item and title, then close the drawer
            mDrawerList.setItemChecked(position, true);
            setTitle(mDrawerTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
        }
        else if (position ==4){

        }
        else{
            Fragment fragment = new PlanetFragment();
            Bundle args = new Bundle();
            args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
            fragment.setArguments(args);

            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

            // update selected item and title, then close the drawer
            mDrawerList.setItemChecked(position, true);
            setTitle(mDrawerTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
        }
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getActionBar().setTitle(mTitle);
    }


    /* Called whenever we call invalidateOptionsMenu() */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // If the nav drawer is open, hide action items related to the content view
        //boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        //menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    public static class PlanetFragment extends Fragment {
        public static final String ARG_PLANET_NUMBER = "planet_number";

        public PlanetFragment() {
            // Empty constructor required for fragment subclasses
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
            int i = getArguments().getInt(ARG_PLANET_NUMBER);
            String planet = getResources().getStringArray(R.array.planets_array)[i];

            int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
                            "drawable", getActivity().getPackageName());
            //((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
            getActivity().setTitle(planet);
            return rootView;
        }
    }

}

有问题的片段位置= 3,片段的代码:

package com.example.home;

import java.io.File;
import java.io.IOException;
import java.net.HttpCookie;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.fmapp.R;
import com.example.fmapp.StartActivity;

import android.app.Fragment;
import android.app.ListFragment;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class OrderList extends ListFragment {
    public static final String ARG_LIST_INDEX = "planet_number";
    public OrderList(){

    }
     public View onCreateView(LayoutInflater inflater, ViewGroup container,
             Bundle savedInstanceState) {
         View rootView = inflater.inflate(R.layout.fragment_orderlist, container, false);
         int i = getArguments().getInt(ARG_LIST_INDEX);
         fetchOrderInfo();
         String planet = getResources().getStringArray(R.array.planets_array)[i];

         int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
                         "drawable", getActivity().getPackageName());
         //((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
         getActivity().setTitle(planet);
         return rootView;
     }
     public void fetchOrderInfo() {
            // TODO Auto-generated method stub
            int login_cookie_index = 0;
            List<HttpCookie> cookieList = (List<HttpCookie>) StartActivity.cookieManager.getCookieStore().getCookies();
            //TODO: search for ltsid cookie
            for (int cookie_iter = 0; cookie_iter < cookieList.size(); cookie_iter++){
                if((cookieList.get(cookie_iter).getName()).equals("ltsid")){
                    login_cookie_index = cookie_iter;
                    break;
                }
            }
            HttpCookie cookie = cookieList.get(login_cookie_index);

            JSONObject data = new JSONObject();
            JSONObject sid = new JSONObject();
            JSONArray arg = new JSONArray();
            try {
                data.put("requestCommand","GetRequestInfo");
                sid.put("name","sessionId");
                sid.put("type", "String");
                sid.put("value", cookie.getValue());
                arg.put(sid);
                data.put("args", arg);
            } catch (JSONException e2) {
                e2.printStackTrace();
            }
            Log.i("fetch data",data.toString());
            String finaldata = data.toString();
            //View mySpinnerView = this.findViewById(R.id.accounts_spinner);
            new AsyncFetchUserOrders(getActivity(),this).execute(finaldata);
            return;
        }
     /*
     public void onListItemClick(ListView l, View v, int position, long id) {

            Log.i("list click","list item click");


        }
        */
    public void populateAdapter(ArrayList<OrderObj> arrayOrderObj) {
        ArrayAdapter<OrderObj> OrderList = new OrderAdapter(getActivity(), arrayOrderObj);
        setListAdapter(OrderList);

    }
}

请注意,如果我注释掉asynctask行,导航抽屉工作正常。

现在是asynctask代码:

package com.example.home;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;

import com.example.fmapp.GlobalVars;
import com.example.fmapp.JsonUtil;

import android.annotation.SuppressLint;
import android.app.ListFragment;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ProgressBar;
import android.widget.Toast;

public class AsyncFetchUserOrders extends AsyncTask<String,Boolean,Integer> {
    protected static String USER_SERVER = GlobalVars.USER_SERVER;
    private int errorCode = -1;
    ProgressBar bar = Home.bar;
    private Context mainContext;
    private OrderList orderFragment;
    //private Arra
    private ArrayAdapter<String> adapter;
    public ArrayList<OrderObj> arrayOrderObj = new ArrayList<OrderObj>();// TODO: populate this shit

    private String toastMsg = null;

    public AsyncFetchUserOrders(Context mainContext, OrderList orderFragment) {
        this.mainContext = mainContext;
        this.orderFragment = orderFragment;
    }

    protected void onPreExecute(){
        bar.setVisibility(View.VISIBLE);
    }

    @SuppressLint("NewApi")
    @Override
    protected Integer doInBackground(String... params) {
        URL url = null;
        Log.i("req data",params[0]);

        try {
            url = new URL(USER_SERVER);
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        }
        HttpURLConnection urlConnection = null;
        try {
            urlConnection = (HttpURLConnection) url.openConnection();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        urlConnection.setReadTimeout( 10000 /*milliseconds*/ );
        urlConnection.setConnectTimeout( 15000 /* milliseconds */ );
        //urlConnection.setRequestProperty("X-Requested-With", "XMLHttpRequest");
        urlConnection.setRequestProperty("Connection", "Keep-Alive");

        try {
             urlConnection.setDoOutput(true);
             try {
                urlConnection.setRequestMethod("POST");
            } catch (ProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                urlConnection.connect();
                OutputStream os = urlConnection.getOutputStream();
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
                writer.write(params[0]);
                writer.close();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            //response:

            try { //parse errorCode
                if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {

                String response = urlConnection.getResponseMessage();

                /*   
                InputStream responseStream = new BufferedInputStream(urlConnection.getInputStream());
                BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
                String line = "";
                StringBuilder stringBuilder = new StringBuilder();
                while ((line = responseStreamReader.readLine()) != null) {
                    stringBuilder.append(line);
                    Log.i("line",line);
                }
                responseStreamReader.close();
                */

                BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                String inputLine;
                StringBuffer stringBuilder = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    stringBuilder.append(inputLine);
                }
                in.close();


                String resp = stringBuilder.toString();
                Log.i("resp",resp);
                processResp(resp);

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

         finally {
             urlConnection.disconnect();
         }

         return 1;
    }


    protected void onProgressUpdate(Integer... progress) {

    }

    protected void onPostExecute(Integer result) {
        //Log.i("postexec","in post execute");
        bar.setVisibility(View.GONE);

        Toast toast = Toast.makeText(mainContext, toastMsg, Toast.LENGTH_SHORT);
        toast.show();
        if (JsonUtil.authSucess == false){

        }
        else{
            // Imp TODO : get to new Activity
            Log.i("ltid","populate spinner");
            //IMP TODO :UserInfo.populateSpinner(adapter);

            JsonUtil.authSucess = false;
            /*
            if (arrayOrderObj != null){
                ArrayAdapter<OrderObj> OrderList = new OrderAdapter(mainContext, arrayOrderObj);
                orderFragment.setListAdapter(OrderList);
            }*/
        }

        //this.cancel(true);
    }

    /*
    public void onStop() {
        //super.onStop();
        if(this!=null){
            this.cancel(true);
        }
    }
    */ 

    private void processResp(String resp) {
        errorCode = JsonUtil.processRespForErrorCode(resp);
        if (errorCode == 0){
            JsonUtil.authSucess = true;
            toastMsg = "Order info received";
            //TODO: parse JSON and populate user orderinfo info
            Log.i("orders", "to populate Order");
            JsonUtil.populateOrderInfo(resp,arrayOrderObj);
            //Log.i("fname",UserInfo.chosenAccount.firstName);
            /*
            ArrayAdapter<OrderObj> OrderList = new OrderAdapter(mainContext, arrayOrderObj);
            orderFragment.setListAdapter(OrderList);
            */
            //orderFragment.populateAdapter(arrayOrderObj);
        }
        else{
            toastMsg = "Something wrong";
        }
    }


}

再一次,没有什么花哨的。仍然无法弄清楚是什么让导航抽屉关闭而不是启动片段,如果点击项目以启动另一个片段。 感谢。

1 个答案:

答案 0 :(得分:0)

我想Home.bar会覆盖你的片段吗?也许您应该使用ProgressBar.show()ProgressBar.dismiss()来控制进度条的可见性