【问题标题】:Application crashed when internet is disabled using Loader class in Android?使用 Android 中的 Loader 类禁用 Internet 时应用程序崩溃?
【发布时间】:2014-01-30 07:32:20
【问题描述】:

我在我的应用程序中使用 LoaderCallBacks 并从 web 服务获取数据并将数据保存在包装器类中,如果数据状态为真,我将所有记录保存在 bean 类中,否则它返回空列表。问题是它带来了数据,但如果我恢复应用程序并断开互联网并再次打开应用程序以查看当时的结果我的应用程序在存在互联网的情况下崩溃了它的工作正常,而如果没有连接互联网并发送错误 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;
    }
}

还有适配器类和 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.

[正确格式化代码和logcat]

【问题讨论】:

  • 你能粘贴更多的日志吗?
  • 我也遇到了同样的问题,然后我所做的是,要解决这个问题,您可以检查互联网连接是否可用,如果是,则转到内容,如果不是,则显示警报框。
  • 请粘贴您的日志。
  • @InnocentKiller 我不能这样做,因为每次我需要知道互联网是否连接......即使在应用程序简历上,我也需要检查互联网是否存在
  • @SMR logcat 表示应用程序在 ProposalListFragment.java 的 ONLOadFnished 的某个点中断

标签: android loader android-listfragment android-loadermanager


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2014-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多