Android 2.3.6上的AsyncTask很好,但在Android 4.1.2中崩溃了

时间:2013-11-29 05:09:43

标签: android android-asynctask

我需要提取联系人详细信息,当我提取详细信息时,我需要在Loading...中显示Progress Dialog Box。我的应用程序在Android 2.3.6中运行良好,但它在Android 4.1.2及更高版本中崩溃。 请帮帮我

记录猫

   11-28 23:15:07.630: E/AndroidRuntime(9190): FATAL EXCEPTION: main
    11-28 23:15:07.630: E/AndroidRuntime(9190): java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. [in ListView(2131230721, class android.widget.ListView) with Adapter(class com.example.outgoingcalls.MainActivity$dataListAdapter)]
    11-28 23:15:07.630: E/AndroidRuntime(9190):     at android.widget.ListView.layoutChildren(ListView.java:1549)
    11-28 23:15:07.630: E/AndroidRuntime(9190):     at android.widget.AbsListView.onLayout(AbsListView.java:2166)
    11-28 23:15:07.630: E/AndroidRuntime(9190):     at android.view.View.layout(View.java:13846)
    11-28 23:15:07.630: E/AndroidRuntime(9190):     at android.view.ViewGroup.layout(ViewGroup.java:4464)
    11-28 23:15:07.630: E/AndroidRuntime(9190):     at android.widget.RelativeLayout.onLayout(RelativeLayout.java:948)
    11-28 23:15:07.630: E/AndroidRuntime(9190):     at android.view.View.layout(View.java:13846)
    11-28 23:15:07.630: E/AndroidRuntime(9190):     at android.view.ViewGroup.layout(ViewGroup.java:4464)
    11-28 23:15:07.630: E/AndroidRuntime(9190):     at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
    11-28 23:15:07.630: E/AndroidRuntime(9190):     at android.view.View.layout(View.java:13846)
    11-28 23:15:07.630: E/AndroidRuntime(9190):     at android.view.ViewGroup.layout(ViewGroup.java:4464)
    11-28 23:15:07.630: E/AndroidRuntime(9190):     at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1649)
    11-28 23:15:07.630: E/AndroidRuntime(9190):     at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1507)
    11-28 23:15:07.630: E/AndroidRuntime(9190):     at android.widget.LinearLayout.onLayout(LinearLayout.java:1420)
    11-28 23:15:07.630: E/AndroidRuntime(9190):     at android.view.View.layout(View.java:13846)
    11-28 23:15:07.630: E/AndroidRuntime(9190):     at android.view.ViewGroup.layout(ViewGroup.java:4464)
    11-28 23:15:07.630: E/AndroidRuntime(9190):     at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
    11-28 23:15:07.630: E/AndroidRuntime(9190):     at android.view.View.layout(View.java:13846)
    11-28 23:15:07.630: E/AndroidRuntime(9190):     at android.view.ViewGroup.layout(ViewGroup.java:4464)
    11-28 23:15:07.630: E/AndroidRuntime(9190):     at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2147)
    11-28 23:15:07.630: E/AndroidRuntime(9190):     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1905)
    11-28 23:15:07.630: E/AndroidRuntime(9190):     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1125)
    11-28 23:15:07.630: E/AndroidRuntime(9190):     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4607)
    11-28 23:15:07.630: E/AndroidRuntime(9190):     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:747)
    11-28 23:15:07.630: E/AndroidRuntime(9190):     at android.view.Choreographer.doCallbacks(Choreographer.java:567)
    11-28 23:15:07.630: E/AndroidRuntime(9190):     at android.view.Choreographer.doFrame(Choreographer.java:536)
    11-28 23:15:07.630: E/AndroidRuntime(9190):     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:733)
    11-28 23:15:07.630: E/AndroidRuntime(9190):     at android.os.Handler.handleCallback(Handler.java:615)
    11-28 23:15:07.630: E/AndroidRuntime(9190):     at android.os.Handler.dispatchMessage(Handler.java:92)
    11-28 23:15:07.630: E/AndroidRuntime(9190):     at android.os.Looper.loop(Looper.java:153)
    11-28 23:15:07.630: E/AndroidRuntime(9190):     at android.app.ActivityThread.main(ActivityThread.java:5086)
    11-28 23:15:07.630: E/AndroidRuntime(9190):     at java.lang.reflect.Method.invokeNative(Native Method)
    11-28 23:15:07.630: E/AndroidRuntime(9190):     at java.lang.reflect.Method.invoke(Method.java:511)
    11-28 23:15:07.630: E/AndroidRuntime(9190):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)
    11-28 23:15:07.630: E/AndroidRuntime(9190):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
    11-28 23:15:07.630: E/AndroidRuntime(9190):     at dalvik.system.NativeStart.main(Native Method)

public class MainActivity extends Activity {
    public TextView outputText;
    public List<String> contactNames = new ArrayList<String>();
    public List<String> contactNumber = new ArrayList<String>();
    public List<Bitmap> contactImage = new ArrayList<Bitmap>();
    ListView listview;
    View convertView;
    ProgressDialog progressDialog;

    private dataListAdapter mAdapter;
 //   RelativeLayout proLayout;

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        LayoutInflater inflater_main = getLayoutInflater();
        setContentView(R.layout.activity_main);

        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);


        FetchContacts contacts = new FetchContacts();

        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion >= android.os.Build.VERSION_CODES.HONEYCOMB){
        contacts.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }else{
            contacts.execute();
        }
        mAdapter = new dataListAdapter(contactNames,contactNumber,contactImage);
        listview = (ListView)findViewById(R.id.list);
        listview.setAdapter(mAdapter);
        RelativeLayout main = (RelativeLayout)findViewById(R.id.main);
        convertView = inflater_main.inflate(R.layout.activity_main,main);

    }
    private Handler mHandler = new Handler(){
        public void handleMessage(Message msg)  
        {
            switch(msg.what){
            case 0:{
                showProgressDialog();
            }
            break;
            case 1:{
                dismissProgressDialog();
            }
            break;
            }
        }
    };
    private void showProgressDialog() { 
        if(progressDialog != null) {
            progressDialog.setMessage("Loading...");
            progressDialog.show();
        }        
    }

    private void dismissProgressDialog() {
        if(progressDialog != null)
            progressDialog.dismiss();
    }

    private class FetchContacts extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            mHandler.sendEmptyMessage(0);
        }
        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub
            fetchContacts(); 
            return "";
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            mHandler.sendEmptyMessage(1);
            mAdapter.notifyDataSetChanged();
        }

    }
    public void fetchContacts() {
    //    mHandler.sendEmptyMessage(0);
        String phoneNumber = null;
        String email = null;
        String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
        Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
        String _ID = ContactsContract.Contacts._ID;
        String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
        String HAS_PHONE_NUMBER = ContactsContract.Contacts. HAS_PHONE_NUMBER;
        Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
        String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
        String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
        Uri EmailCONTENT_URI =  ContactsContract.CommonDataKinds.Email.CONTENT_URI;
        String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
        String DATA = ContactsContract.CommonDataKinds.Email.DATA;
        StringBuffer output = new StringBuffer();
        ContentResolver contentResolver = getContentResolver();
        Cursor cursor = contentResolver.query(CONTENT_URI, null,null, null, sortOrder);
        int a = cursor.getCount();
        //Cursor cursor =getContacts();
        // Loop for every contact in the phone
        if (cursor.getCount() > 0 ) {
            cursor.moveToFirst();
            do {
                String contact_id = cursor.getString(cursor.getColumnIndex( _ID ));
                String name = cursor.getString(cursor.getColumnIndex( DISPLAY_NAME ));
                int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex( HAS_PHONE_NUMBER )));
                if (hasPhoneNumber > 0 ) {

                    //output.append("\n First Name:" + name);
                    // Query and loop for every phone number of the contact
                    Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[] { contact_id }, null);
                    while (phoneCursor.moveToNext()) {
                        phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
                        //output.append("\n Phone number:" + phoneNumber);
                        if(name!=null){
                            contactNames.add(name);
                        }else{
                            contactNames.add("No name");
                        }
                        String num = phoneNumber;
                        num = num.replaceAll("-", "");
                        if(num.length()==10){
                         phoneNumber=num.substring(0,3)+"-"+num.substring(3,6)+"-"+num.substring(6,10);
                        }else if(num.length()==11){
                            phoneNumber=num.substring(0,3)+"-"+num.substring(3,7)+"-"+num.substring(7,11);
                        }else{
                            phoneNumber = num;
                        }

                        contactNumber.add(phoneNumber);
                        break;
                    }
                    phoneCursor.close();
                    // Query and loop for every email of the contact
//                    Cursor emailCursor = contentResolver.query(EmailCONTENT_URI,    null, EmailCONTACT_ID+ " = ?", new String[] { contact_id }, null);
//                    while (emailCursor.moveToNext()) {
//                        email = emailCursor.getString(emailCursor.getColumnIndex(DATA));
//                        output.append("\nEmail:" + email);
//                    }
//                    emailCursor.close();
                }
            }while (cursor.moveToNext());
        }
    }

public Bitmap getFacebookPhoto(String phoneNumber) {
            Uri phoneUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
            Uri photoUri = null;
            ContentResolver cr = this.getContentResolver();
            Cursor contact = cr.query(phoneUri,
                    new String[] { ContactsContract.Contacts._ID }, null, null, null);

            if (contact.moveToFirst()) {
                long userId = contact.getLong(contact.getColumnIndex(ContactsContract.Contacts._ID));
                photoUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, userId);

            }
            else {
                Bitmap defaultPhoto = BitmapFactory.decodeResource(getResources(),android.R.drawable.ic_menu_report_image);
                return null;
            }
            if (photoUri != null) {
                InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(
                        cr, photoUri);
                if (input != null) {
                    return BitmapFactory.decodeStream(input);
                }
            } else {
                Bitmap defaultPhoto = BitmapFactory.decodeResource(getResources(), android.R.drawable.ic_menu_report_image);
                return null;
            }
            Bitmap defaultPhoto = BitmapFactory.decodeResource(getResources(), android.R.drawable.ic_menu_report_image);
            return null;
        }

1 个答案:

答案 0 :(得分:1)

for progress Dialog 修改AsyncTask ,如下所示:

private class FetchContacts extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            progressDialog.setMessage("Loading...");
            progressDialog.show();
            mHandler.sendEmptyMessage(0);
        }
        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub
            fetchContacts(); 
            return "";
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            mHandler.sendEmptyMessage(1);
            mAdapter.notifyDataSetChanged();
            progressDialog.dismiss();
        }

    }

删除这段代码:

private Handler mHandler = new Handler(){
        public void handleMessage(Message msg)  
        {
            switch(msg.what){
            case 0:{
                showProgressDialog();
            }
            break;
            case 1:{
                dismissProgressDialog();
            }
            break;
            }
        }
    };
    private void showProgressDialog() { 
        if(progressDialog != null) {
            progressDialog.setMessage("Loading...");
            progressDialog.show();
        }        
    }

    private void dismissProgressDialog() {
        if(progressDialog != null)
            progressDialog.dismiss();
    }