【问题标题】:How can I quickly close activity and refresh Contact listview onClick() Android?如何快速关闭活动并刷新联系人列表视图 onClick() Android?
【发布时间】:2014-07-25 23:06:48
【问题描述】:

我正在开发更改联系人图像的应用程序。当我单击保存按钮以更改图像时,我不知道该怎么做或如何刷新联系人列表视图。这是我的 MainActivity.class 和 Detail.class 的代码。

MainActivity.class

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // The contacts from the contacts content provider is stored in this
        // cursor
        mMatrixCursor = new MatrixCursor(new String[] { "_id", "name", "photo",
                "details" });

        // Adapter to set data in the listview
        mAdapter = new SimpleCursorAdapter(getBaseContext(),
                R.layout.lv_layout, null, new String[] { "name", "photo",
                        "details" }, new int[] { R.id.tv_name, R.id.iv_photo,
                        R.id.tv_details }, 0);

        // Getting reference to listview
        ListView lstContacts = (ListView) findViewById(R.id.lst_contacts);

        // Setting the adapter to listview
        lstContacts.setAdapter(mAdapter);

        // Creating an AsyncTask object to retrieve and load listview with
        // contacts
        ListViewContactsLoader listViewContactsLoader = new ListViewContactsLoader();

        // Starting the AsyncTask process to retrieve and load listview with
        // contacts
        listViewContactsLoader.execute();
        lstContacts.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {

                Constants.position = position;
                Constants.id = Constants.ids_list.get(position);
                ByteArrayOutputStream stream = new ByteArrayOutputStream();

                // bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
                byte[] byteArray = stream.toByteArray();

                Intent intent = new Intent(MainActivity.this, detail.class);


                intent.putExtra("bmp", byteArray); // for image



                startActivity(intent);


            }
        });

    }

    /** An AsyncTask class to retrieve and load listview with contacts */
    private class ListViewContactsLoader extends AsyncTask<Void, Void, Cursor> {

        @Override
        protected Cursor doInBackground(Void... params) {
            Uri contactsUri = ContactsContract.RawContacts.CONTENT_URI;

            // Querying the table ContactsContract.Contacts to retrieve all the
            // contacts
            Cursor contactsCursor = getContentResolver().query(contactsUri,
                    null, null, null,
                    ContactsContract.Contacts.DISPLAY_NAME + " ASC ");

            if (contactsCursor.moveToFirst()) {
                do {
                    long contactId = contactsCursor.getLong(contactsCursor
                            .getColumnIndex("_ID"));

                    Uri dataUri = ContactsContract.Data.CONTENT_URI;

                    // Querying the table ContactsContract.Data to retrieve
                    // individual items like
                    // home phone, mobile phone, work email etc corresponding to
                    // each contact
                    Cursor dataCursor = getContentResolver().query(
                            dataUri,
                            null,
                            ContactsContract.Data.RAW_CONTACT_ID + "="
                                    + contactId, null, null);

                    Constants.ids_list.add(contactId);

                    String displayName = "";
                    String nickName = "";
                    String homePhone = "";
                    String mobilePhone = "";
                    String workPhone = "";
                    String photoPath = "" + R.drawable.blank;
                    byte[] photoByte = null;

                    String title = "";

                    if (dataCursor.moveToFirst()) {
                        // Getting Display Name
                        displayName = dataCursor
                                .getString(dataCursor
                                        .getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
                        do {

                            // Getting NickName
                            if (dataCursor
                                    .getString(
                                            dataCursor
                                                    .getColumnIndex("mimetype"))
                                    .equals(ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE))
                                nickName = dataCursor.getString(dataCursor
                                        .getColumnIndex("data1"));

                            // Getting Phone numbers
                            if (dataCursor
                                    .getString(
                                            dataCursor
                                                    .getColumnIndex("mimetype"))
                                    .equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)) {
                                switch (dataCursor.getInt(dataCursor
                                        .getColumnIndex("data2"))) {
                                case ContactsContract.CommonDataKinds.Phone.TYPE_HOME:
                                    homePhone = dataCursor.getString(dataCursor
                                            .getColumnIndex("data1"));
                                    break;
                                case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE:
                                    mobilePhone = dataCursor
                                            .getString(dataCursor
                                                    .getColumnIndex("data1"));
                                    break;
                                case ContactsContract.CommonDataKinds.Phone.TYPE_WORK:
                                    workPhone = dataCursor.getString(dataCursor
                                            .getColumnIndex("data1"));
                                    break;
                                }
                            }

                            // Getting Photo
                            if (dataCursor
                                    .getString(
                                            dataCursor
                                                    .getColumnIndex("mimetype"))
                                    .equals(ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)) {
                                photoByte = dataCursor.getBlob(dataCursor
                                        .getColumnIndex("data15"));

                                if (photoByte != null) {
                                    bitmap = BitmapFactory.decodeByteArray(
                                            photoByte, 0, photoByte.length);

                                    // Getting Caching directory
                                    File cacheDirectory = getBaseContext()
                                            .getCacheDir();

                                    // Temporary file to store the contact image
                                    File tmpFile = new File(
                                            cacheDirectory.getPath() + "/wpta_"
                                                    + contactId + ".png");

                                    // The FileOutputStream to the temporary
                                    // file
                                    try {
                                        FileOutputStream fOutStream = new FileOutputStream(
                                                tmpFile);

                                        // Writing the bitmap to the temporary
                                        // file as png file
                                        bitmap.compress(
                                                Bitmap.CompressFormat.PNG, 100,
                                                fOutStream);

                                        // Flush the FileOutputStream
                                        fOutStream.flush();

                                        // Close the FileOutputStream
                                        fOutStream.close();

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

                                    photoPath = tmpFile.getPath();
                                }

                            }

                        } while (dataCursor.moveToNext());

                        String details = "";

                        // Concatenating various information to single string
                        if (homePhone != null && !homePhone.equals(""))
                            details = "HomePhone : " + homePhone + "\n";
                        if (mobilePhone != null && !mobilePhone.equals(""))
                            details += "MobilePhone : " + mobilePhone + "\n";
                        if (workPhone != null && !workPhone.equals(""))
                            details += "WorkPhone : " + workPhone + "\n";
                        if (nickName != null && !nickName.equals(""))
                            details += "NickName : " + nickName + "\n";

                        if (title != null && !title.equals(""))
                            details += "Title : " + title + "\n";

                        // Adding id, display name, path to photo and other
                        // details to cursor
                        mMatrixCursor.addRow(new Object[] {
                                Long.toString(contactId), displayName,
                                photoPath, details });

                    }

                } while (contactsCursor.moveToNext());

            }
            return mMatrixCursor;
        }

        @Override
        protected void onPostExecute(Cursor result) {
            // Setting the cursor containing contacts to listview
            mAdapter.swapCursor(result);
        }
    }
}

这是我的 Detail.class。在那个保存按钮那里。

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.custom_list);

        Intent i = getIntent();

        this.photo = (ImageView) this.findViewById(R.id.photo);
        this.camera = (Button) this.findViewById(R.id.camera);
        this.galery = (Button) this.findViewById(R.id.galary);
        this.save = (Button) this.findViewById(R.id.save);

        this.galery.setOnClickListener(new ImagePickListener());
        this.camera.setOnClickListener(new TakePictureListener());

        save.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {

                ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

                int position = getIntent().getExtras().getInt("bmp");
                // int po=ops.size();
                ByteArrayOutputStream stream = new ByteArrayOutputStream();

                if (image != null) { // If an image is selected successfully
                    // Bitmap bmp = BitmapFactory.decodeResource(getResources(),
                    // R.drawable.ic_launcher);
                    image.compress(Bitmap.CompressFormat.PNG, 0, stream);
                    //

                    long id = Constants.id;
                    // setContactPhoto(stream.toByteArray(), id);
                    setContactPhoto(detail.this.getContentResolver(),
                            stream.toByteArray(), id);

                    detail.this.finish();
                    Intent intent=new Intent(detail.this,MainActivity.class);
                    startActivity(intent);

                }

            }
        });

    }

    void setContactPhoto(byte[] byteArray, long parseLong) {
        // TODO Auto-generated method stub
        Uri uri = ContentUris.withAppendedId(People.CONTENT_URI, parseLong);
        android.provider.Contacts.People.setPhotoData(
                detail.this.getContentResolver(), uri, byteArray);
        Log.d("main", "id: " + parseLong + " Uri: " + uri + " bytearray: "
                + byteArray.length);

    }

    /**
     * Receive the result from the startActivity
     */
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
            case IMAGE_PICK:
                this.imageFromGallery(resultCode, data);
                break;
            case IMAGE_CAPTURE:
                this.imageFromCamera(resultCode, data);
                break;
            case PICK_PHOTO:
                if (resultCode == RESULT_OK) {
                    // Getting the uri of the picked photo
                    Uri updateImageView = data.getData();

                    InputStream imageStream = null;
                    try {
                        // Getting InputStream of the selected image
                        imageStream = getContentResolver().openInputStream(
                                updateImageView);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }

                    // Creating bitmap of the selected image from its
                    // inputstream
                    image = BitmapFactory.decodeStream(imageStream);

                    // Getting reference to ImageView
                    // ImageButton ibPhoto = (ImageButton)
                    // findViewById(R.id.photo);

                    // Setting Bitmap to ImageButton
                    photo.setImageBitmap(image);

                }
                break;
            default:
                break;
            }
        }
    }

    /**
     * Update the imageView with new bitmap
     * 
     * @param newImage
     */
    private void updateImageView(Bitmap newImage) {
        BitmapProcessor bitmapProcessor = new BitmapProcessor(newImage, 1000,
                1000, 90);

        this.image = bitmapProcessor.getBitmap();
        this.photo.setImageBitmap(this.image);
    }

    /**
     * Image result from camera
     * 
     * @param resultCode
     * @param data
     */
    private void imageFromCamera(int resultCode, Intent data) {
        this.updateImageView((Bitmap) data.getExtras().get("data"));
    }

    /**
     * Image result from gallery
     * 
     * @param resultCode
     * @param data
     */
    private void imageFromGallery(int resultCode, Intent data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String filePath = cursor.getString(columnIndex);
        cursor.close();

        this.updateImageView(BitmapFactory.decodeFile(filePath));
    }

    /**
     * Click Listener for selecting images from phone gallery
     * 
     * @author tscolari
     * 
     */
    class ImagePickListener implements OnClickListener {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setType("image/*");
            startActivityForResult(
                    Intent.createChooser(intent, "select photo"), IMAGE_PICK);

        }
    }

    /**
     * Click listener for taking new picture
     * 
     * @author tscolari
     * 
     */
    class TakePictureListener implements OnClickListener {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(
                    android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent, IMAGE_CAPTURE);

        }
    }

     @Override
     protected void onPause() {

     super.onPause();
     }

    @Override
     protected void onDestroy() {
     // Constants.ids_list.clear();
     startActivity(new Intent(this, MainActivity.class));
     super.onDestroy();

    // finish();

     }

    void setContactPhoto(ContentResolver c, byte[] bytes, long personId) {
        ContentValues values = new ContentValues();
        int photoRow = -1;
        // personId = 8863;
        String where = ContactsContract.Data._ID + " = " + personId + " AND "
                + ContactsContract.Data.MIMETYPE + "=='"
                + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE
                + "'";
        Cursor cursor = c.query(ContactsContract.Data.CONTENT_URI, null, where,
                null, null);
        int idIdx = cursor.getColumnIndexOrThrow(ContactsContract.Data._ID);
        if (cursor.moveToFirst()) {
            photoRow = cursor.getInt(idIdx);
        }
        cursor.close();

        values.put(ContactsContract.Data.RAW_CONTACT_ID, personId);
        values.put(ContactsContract.Data.IS_SUPER_PRIMARY, 1);
        values.put(ContactsContract.CommonDataKinds.Photo.PHOTO, bytes);
        values.put(ContactsContract.Data.MIMETYPE,
                ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);

        if (photoRow >= 0) {
            c.update(ContactsContract.Data.CONTENT_URI, values,
                    ContactsContract.Data._ID + " = " + photoRow, null);
            Toast.makeText(detail.this, "updated " + personId, 50000).show();
        } else {
            c.insert(ContactsContract.Data.CONTENT_URI, values);
            Toast.makeText(detail.this, "inserted " + personId, 50000).show();
        }
    }
}

【问题讨论】:

    标签: java android performance android-intent android-button


    【解决方案1】:

    在ButtonClick的保存功能后使用这个

    Intent intent = getIntent();
    finish();
    startActivity(intent);
    
    
    
     @Override
                public void onClick(View arg0) {
    
                    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    
                    int position = getIntent().getExtras().getInt("bmp");
                    // int po=ops.size();
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    
                    if (image != null) { // If an image is selected successfully
                        // Bitmap bmp = BitmapFactory.decodeResource(getResources(),
                        // R.drawable.ic_launcher);
                        image.compress(Bitmap.CompressFormat.PNG, 0, stream);
                        //
    
                        long id = Constants.id;
                        // setContactPhoto(stream.toByteArray(), id);
                        setContactPhoto(detail.this.getContentResolver(),
                                stream.toByteArray(), id);
    
                        detail.this.finish();
                        Intent intent = getIntent();
                        startActivity(intent);
    
    
                    }
    

    【讨论】:

    • 我完全不知道我在哪个地方输入了这个代码??
    • aftre cilck 保存按钮,活动快速关闭并刷新 MainActivity 列表视图@Soumil Deshpande
    猜你喜欢
    • 2016-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-08
    • 1970-01-01
    • 1970-01-01
    • 2014-06-09
    相关资源
    最近更新 更多