使用Android中的Loader类禁用互联网时,应用程序崩溃了吗?

时间:2014-01-30 07:32:21

标签: android loader android-listfragment android-loadermanager

我在我的应用程序中使用LoaderCallBacks并从webservice获取数据并在包装类中保存数据如果数据状态为true我将保存bean类中的所有记录,否则返回空列表。问题是它带来数据但是如果我恢复应用程序和diconnect互联网并再次打开应用程序看到结果当时我的应用程序崩溃其工作正常的互联网存在而未能显示空列表如果互联网没有连接并发送错误 01-30 23 :12:19.800:E / AndroidRuntime(24136):致命异常:ModernAsyncTask#2

ProposalListActivity.java

    public class ProposalListActivity extends FragmentActivity  {

        public final static String ASSIGNED_USER_ID = "assignedUserId";

        public static final String PROPOSAL_LIST_TYPE = "proposalListType";

        public final static int ASSIGNED_PROPOSALS = 1;
        /**
         * The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each of the sections. We use a
         * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which will keep every loaded fragment in memory. If this becomes too memory
         * intensive, it may be best to switch to a {@link android.support.v4.app.FragmentStatePagerAdapter}.
         */
        SectionsPagerAdapter mSectionsPagerAdapter;

        /**
         * The {@link ViewPager} that will host the section contents.
         */
        ViewPager mViewPager;
    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_proposal_list);
            Log.i("Proposal list activity","Proposal list activity");

            Log.i("sharedpreferences get Response in PP",""+SessionManager.getLoginResponse(getApplicationContext(),
                                    "responseLogin"));
             // Create the adapter that will return a fragment for each of the three
            // primary sections of the app.
            mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
            // Set up the ViewPager with the sections adapter.
            mViewPager = (ViewPager) findViewById(R.id.pager);
            mViewPager.setAdapter(mSectionsPagerAdapter);

        }

        @Override
        protected void onResume() {
            // TODO Auto-generated method stub
            super.onResume();
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.proposal_list, menu);
            return true;
        }
    /**
         * A {@link FragmentPagerAdapter} that returns a fragment corresponding to one of the sections/tabs/pages.
         */
        public class SectionsPagerAdapter extends FragmentPagerAdapter {


            public SectionsPagerAdapter(FragmentManager fm) {
                super(fm);
            }

            @Override
            public Fragment getItem(int position) {

                if(position == 0) {
                    Bundle args = new Bundle();
                    args.putInt(ProposalListActivity.ASSIGNED_USER_ID, 1);
                    args.putInt(PROPOSAL_LIST_TYPE,ASSIGNED_PROPOSALS);
                    ProposalListFragment frag = new ProposalListFragment();
                    frag.setArguments(args);
                    return frag;
                    }
        }
**ProposalListFragment.java**



     public class ProposalListFragment extends ListFragment implements LoaderManager.LoaderCallbacks<List<ProposalListItem>>{

        private final static String TAG = ProposalListFragment.class.getName();
        private ProposalListLoader proposalListLoader;
        private ProposalListAdapter proposalListAdapter;
        private int userId;
        NetworkConnection networkConnection;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            networkConnection = new NetworkConnection(getActivity());
            int proposalListType = getArguments().getInt(ProposalListActivity.PROPOSAL_LIST_TYPE);
            switch (proposalListType) {
                case ProposalListActivity.ASSIGNED_PROPOSALS:
                    userId = getArguments().getInt(ProposalListActivity.ASSIGNED_USER_ID);
                    break;

                default:
                    break;
            }
          Log.i("net diable",""+networkConnection.isConnectingToInternet());
      getLoaderManager().initLoader(100001, null, this);
         }

        @Override
        public Loader<List<ProposalListItem>> onCreateLoader(int id, Bundle args) {
            proposalListLoader = new ProposalListLoader(userId, getActivity());
            return proposalListLoader;
        }

        @Override
        public void onLoadFinished(Loader<List<ProposalListItem>> arg0,List<ProposalListItem> proposals) {
             if(proposals == null)
           {
             Log.i(TAG,"INTERNET DISABLE ....OnLoadFinished of PP list fragment");
            // getLoaderManager().destroyLoader(arg0.getId());
                setListAdapter(proposalListAdapter);
                if(isResumed()) {
                       setListShown(false);
                   } else {
                       setListShownNoAnimation(true);
                   }
           }
           else
           {
            proposalListAdapter = new ProposalListAdapter(getActivity(), proposalListLoader);
            setListAdapter(proposalListAdapter);
            if(isResumed()) {
                   setListShown(true);
               } else {
                   setListShownNoAnimation(true);
               }

           }
    }
    }

ProposalListService.java 它从服务

带来数据
public class ProposalListService {

    private final static ProposalListService INSTANCE = new ProposalListService();
public List<ProposalListItem> getAssignedProposals(int surveyourId) {

        MultiValueMap<String, Object> formData = new LinkedMultiValueMap<String, Object>();
        formData.add("surveyour_id",String.valueOf(surveyourId));

        //Populate the MultiValueMap being serialized and headers in an HttpEntity object to use for the request
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(formData, WorkflowRestService
                .getInstance().getRequestHeaders());

        // Perform the HTTP GET request
        ResponseEntity<ProposalListItemHolder> responseEntity = WorkflowRestService.getInstance().getRestTemplate()
                .exchange(WorkflowApp.getServicesURL()+"proposals/getProposals", HttpMethod.POST, requestEntity, ProposalListItemHolder.class);
        Log.i("response Entity",""+responseEntity);
        //convert the array to a list and return it
        ProposalListItemHolder holder = responseEntity.getBody();
        Log.i("response Entity body",""+responseEntity.getBody());
        if ("true".equals(holder.getStatus()))
        {   Log.i("holder.getProposalListItems",""+holder.getProposalListItems());
            return holder.getProposalListItems();
        }
        else
            Log.i("else block of pp",""+holder.getProposalListItems());
            return Collections.EMPTY_LIST;
    }
}

还有Adapter类和ListItemHolder类包装数据,唯一的问题是它没有显示缺少互联网的空列表/数据而且崩溃并给出

**error 01-30 23:12:19.800: E/AndroidRuntime(24136): FATAL EXCEPTION: ModernAsyncTask #2**
can someone please help me its very weird error that is crashing app.Please help me 
**EDIT added more logcat:**

> 01-30 23:30:55.970: I/internet connection cheking before calling doLogin()(25590): true
01-30 23:30:55.970: I/do login method(25590): login button clickedusername:kongpasswor:kongkong
01-30 23:30:55.970: I/try block login(25590): try block of initialize Loader
01-30 23:30:55.970: I/in loader(25590): login button clickedusername:kongpasswor:kongkong
01-30 23:30:55.970: I/login loader(25590): LoginLoader{422d8f28 id=0}
01-30 23:30:55.970: D/com.mrfs.android.surveyapp.model.User(25590): starting proposals loader...
01-30 23:30:55.970: D/com.mrfs.android.surveyapp.model.User(25590): load in background if
01-30 23:30:55.970: I/username(25590): kong
01-30 23:30:55.970: I/password(25590): kongkong
01-30 23:30:55.970: I/apkVersion(25590): 2013-07-10 01:18:26
01-30 23:30:57.295: I/response Entity Login(25590): <200 OK,com.mrfs.android.surveyapp.model.UserListItemHolder@4233a248,{Server=[nginx/1.4.4], Date=[Thu, 30 Jan 2014 07:37:36 GMT], Content-Type=[application/json], Transfer-Encoding=[chunked], Connection=[close], Access-Control-Allow-Origin=[*], X-Android-Sent-Millis=[1391106656297], X-Android-Received-Millis=[1391106657272]}>
01-30 23:30:57.295: I/response Entity Body Login Function(25590): com.mrfs.android.surveyapp.model.UserListItemHolder@4233a248
01-30 23:30:57.295: I/LoginListService if condition(25590): Name: kong,Password: f10343d1dc8d44c8935b356aa3f8aae2,First Name: Kongmesssage:Successfully Logged In.status:true
01-30 23:30:57.295: D/com.mrfs.android.surveyapp.model.User(25590): load in background else
01-30 23:30:57.300: D/com.mrfs.android.surveyapp.model.User(25590): delivering login, size
01-30 23:30:57.300: I/status(25590): Name: kong,Password: f10343d1dc8d44c8935b356aa3f8aae2,First Name: Kong
01-30 23:30:57.580: W/IInputConnectionWrapper(25590): showStatusIcon on inactive InputConnection
01-30 23:31:04.940: I/Proposal list activity(25590): Proposal list activity
01-30 23:31:04.940: I/sharedpreferences get Response in PP(25590): not null
01-30 23:31:04.960: I/net diable(25590): false
01-30 23:31:04.965: D/AbsListView(25590): Get MotionRecognitionManager
01-30 23:31:04.965: D/com.mrfs.android.surveyapp.loader.ProposalListLoader(25590): starting proposals loader...
01-30 23:31:04.965: D/com.mrfs.android.surveyapp.loader.ProposalListLoader(25590): proposals not found in cache, loading proposals...
01-30 23:31:04.970: I/net diable(25590): false
01-30 23:31:04.970: W/dalvikvm(25590): threadid=15: thread exiting with uncaught exception (group=0x416162a0)
01-30 23:31:04.970: D/AbsListView(25590): Get MotionRecognitionManager
01-30 23:31:04.970: E/AndroidRuntime(25590): FATAL EXCEPTION: ModernAsyncTask #3
01-30 23:31:13.300: I/Choreographer(25590): Skipped 491 frames!  The application may be doing too much work on its main thread.

[格式化代码&amp; logcat正确]

1 个答案:

答案 0 :(得分:0)

我认为问题是因为您没有检查getAssignedProposals()内的连接可用性。 也许你应该尝试在IOException中捕获getAssignedProposals()(并且可能返回一个空列表?),所以异常不会被抛到工作线程?