某些图片在ImageView

时间:2016-01-10 16:23:56

标签: java android listview android-studio

我创建了一个短信应用程序,我想显示联系人的图片,我得到了InputStream:

public InputStream openPhoto(long contactId) {
    Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
    Uri photoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
    Cursor cursor = getContentResolver().query(photoUri, new String[]{ContactsContract.Contacts.Photo.PHOTO}, null, null, null);
    if (cursor == null) {
        return null;
    }
    try {
        if (cursor.moveToFirst()) {
            byte[] data = cursor.getBlob(0);
            if (data != null) {
                return new ByteArrayInputStream(data);
            }
        }
    } finally {
        cursor.close();
    }
    return null;
}

然后我这样显示:

Bitmap bmp = BitmapFactory.decodeStream(listMessage.get(position).photo);
imageContact.setImageBitmap(bmp);

以下是发生的事情:

首先当我向下滚动时运行我的应用程序时,会显示一些图像,但是当我向上滚动到顶部然后返回到最后图像消失enter image description here

你可以看到我的列表中没有第一张图片,只有最后一张图片 所以我的第一个问题是,为什么我联系的第一张图片“Nico Aragon”和“Elouuuuuuudie”不显示? 第二个问题,为什么当我的listView“刷新”时,最后一张图片消失了? :/

这是我的自定义listView适配器

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:descendantFocusability="blocksDescendants"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#000"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Medium Text"
        android:id="@+id/tvContact"
        android:layout_gravity="center_horizontal"
        android:layout_alignTop="@+id/im_photoContact"
        android:layout_alignLeft="@+id/lastSms"
        android:layout_alignStart="@+id/lastSms" />

    <ImageView
        android:contentDescription="@string/photoContact"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/im_photoContact"
        android:minWidth="50dp"
        android:minHeight="50dp"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="10dp"
        android:layout_marginBottom="10dp"
        android:maxHeight="50dp"
        android:maxWidth="50dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/lastSms"
        android:ellipsize="end"
        android:maxWidth="300dp"
        android:maxLines="1"
        android:singleLine="true"
        android:textColor="#c4c4c4"
        android:textSize="15dp"
        android:layout_alignBottom="@+id/im_photoContact"
        android:layout_toRightOf="@+id/im_photoContact"
        android:layout_toEndOf="@+id/im_photoContact"
        android:layout_marginLeft="10dp" />

    <ImageView
        android:layout_width="10dp"
        android:layout_height="10dp"
        android:background="@drawable/new_message"
        android:id="@+id/im_new_message"
        android:layout_marginRight="10dp"
        android:layout_marginTop="25dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

</RelativeLayout>

和我的列表视图:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#f4f4f4">

        <TextView
            android:id="@+id/toolbar_title"
            android:textColor="#000"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="30dp"
            android:layout_gravity="center"
            android:text="@string/message"
            android:theme="@android:style/DeviceDefault.ButtonBar.AlertDialog" />

    </android.support.v7.widget.Toolbar>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ListView
            android:id="@+id/ListView01"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </RelativeLayout>

</LinearLayout>

这是我的listView适配器:

public class ContactAdapter extends BaseAdapter {


    ArrayList<CreateContactAdapter> listMessage;
    Context context;
    LayoutInflater Inflater;

    public ContactAdapter(ArrayList<CreateContactAdapter> listMessage, Context context) {
        this.listMessage = listMessage;
        this.context = context;
        Inflater = LayoutInflater.from(context);

    }

    @Override
    public int getCount() {
        return listMessage.size();
    }

    @Override
    public Object getItem(int position) {
        return listMessage.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        RecordHolder holder = null;

        if (convertView == null) {

            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            convertView = inflater.inflate(R.layout.contact_items, parent, false);
            holder = new RecordHolder();

            holder.tvContact = (TextView) convertView.findViewById(R.id.tvContact);
            holder.lastSms = (TextView) convertView.findViewById(R.id.lastSms);
            holder.imageContact = (ImageView) convertView.findViewById(R.id.im_photoContact);
            holder.newMsg = (ImageView) convertView.findViewById(R.id.im_new_message);

            convertView.setTag(holder);
        } else {
            holder = (RecordHolder) convertView.getTag();
        }


        if (listMessage.get(position).photo != null) {
            Bitmap bmp = BitmapFactory.decodeStream(listMessage.get(position).photo);
            holder.imageContact.setImageBitmap(bmp);
        } else {
            holder.imageContact.setImageResource(R.drawable.contacticon);
        }
        if (!listMessage.get(position).contact.equals("no"))
            holder.tvContact.setText(listMessage.get(position).contact);
        else
            holder.tvContact.setText(listMessage.get(position).address);
        if (listMessage.get(position).read == 0) {
            holder.newMsg.setBackgroundResource(R.drawable.new_message);
        } else
            holder.newMsg.setBackgroundResource(0);
        holder.lastSms.setText(listMessage.get(position).body);
        //On retourne l'item créé.
        return convertView;
    }

    public int getImageId(String imageName) {
        return context.getResources().getIdentifier(imageName, "drawable", context.getPackageName());
    }

    static class RecordHolder {
        TextView tvContact, lastSms;
        ImageView imageContact , newMsg;
    }

这是我使用openPhoto的地方,在我的mainActivity中,当我检索联系人及其信息时:

cursor = this.getContentResolver().query(uriSms, selectionSms, null, null, "date DESC");
if (cursor.moveToFirst()) {
    while (!cursor.isAfterLast()) {
        id = cursor.getString(2);
        if (!(idList.contains(id))) {
            body = cursor.getString(1);
            numero = cursor.getString(3);
            read = cursor.getInt(5);
            cursorPhone = this.getContentResolver().query(uriPhone, selectionPhone, ContactsContract.CommonDataKinds.Phone.NUMBER + "='" + numero + "'", null, null);
            if (cursorPhone.moveToFirst()) {
                contact = cursorPhone.getString(0);
                Uri uriContact = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(numero));
                cursorContact = this.getContentResolver().query(uriContact, selectionContact, null, null, null);
                cursorContact.moveToFirst();
                long idContact = cursorContact.getLong(0);
                photo = openPhoto(idContact);
                if (photo != null)
                    listContact.add(new CreateContactAdapter(contact, numero, body, id, photo, read));
                else
                    listContact.add(new CreateContactAdapter(contact, numero, body, id, null, read));
            } else {

                listContact.add(new CreateContactAdapter("no", numero, body, id, null, read));
            }
            idList.add(id);
        }
        cursor.moveToNext();
    }
}
cursor.close();
adapter = new ContactAdapter(listContact, this);
}

我设置我的适配器:

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

final String packageName = MainActivity.this.getPackageName();
if (!Telephony.Sms.getDefaultSmsPackage(MainActivity.this).equals(packageName)) {
    Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
    intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, packageName);
    startActivity(intent);
}

toolbar = (Toolbar) findViewById(R.id.toolbar);
ListView lv = (ListView) findViewById(R.id.ListView01);

setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false); //enlever le titre originel
getSupportActionBar().setHomeButtonEnabled(true); // ajout du bouton retour
getSupportActionBar().setDisplayHomeAsUpEnabled(true); // ajout du bouton retour

listContact = new ArrayList<>();
idList = new ArrayList<>();

getInfoMain();
lv.setAdapter(adapter);

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String persoId = listContact.get(position).id;
        String numero = listContact.get(position).address;
        String contact = listContact.get(position).contact;
        String body = listContact.get(position).body;
        Intent intent = new Intent(MainActivity.this, PrintMessage.class);
        intent.putExtra("id", persoId);
        intent.putExtra("numero", numero);
        intent.putExtra("contact", contact);
        markMessageRead(ctx, numero, body);
        startActivity(intent);
    }
});

}

listMessage.get(position).photo =包含photo 这是openPhoto的结果,这是一个inputStream

2 个答案:

答案 0 :(得分:0)

使用以下代码替换ContactAdapter.java的getView():

            @Override
public View getView(int position, View convertView, ViewGroup parent) {

    RecordHolder holder = null;

    if (convertView == null) {

        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        convertView = inflater.inflate(R.layout.contact_items, parent, false);
        holder = new RecordHolder();

    holder.tvContact = (TextView) layoutItem.findViewById(R.id.tvContact);
    holder.lastSms = (TextView) layoutItem.findViewById(R.id.lastSms);
    holder.imageContact = (ImageView) layoutItem.findViewById(R.id.im_photoContact);
    holder.newMsg = (ImageView) layoutItem.findViewById(R.id.im_new_message);

        convertView.setTag(holder);
    } else {
        holder = (RecordHolder) convertView.getTag();
    }


    if (listMessage.get(position).photo != null) {
        Bitmap bmp = BitmapFactory.decodeStream(listMessage.get(position).photo);
        holder.imageContact.setImageBitmap(bmp);
    } else {
        holder.imageContact.img.setImageResource(R.drawable.contacticon);
    }
    if (!listMessage.get(position).contact.equals("no"))
        tvContact.setText(listMessage.get(position).contact);
    else
        holder.tvContact.setText(listMessage.get(position).address);
    if (listMessage.get(position).read == 0) {
        holder.newMsg.setBackgroundResource(R.drawable.new_message);
    } else
        holder.newMsg.setBackgroundResource(0);
    holder.lastSms.setText(listMessage.get(position).body);
    //On retourne l'item créé.
    return convertView;
}

OutSide getView()创建一个RecordHolder

static class RecordHolder {
    TextView tvContact, lastSms;
    ImageView imageContact , newMsg;
}

答案 1 :(得分:0)

好的,好的,我解决了我的问题。 我的方法openPhoto(接受官方文档android)返回一个InputStream,我用byte []改变它。然后我打印出来:

    Bitmap bmp = BitmapFactory.decodeByteArray(listMessage.get(position).photo, 0, listMessage.get(position).photo.length);;
    holder.imageContact.setImageBitmap(bmp);

但我不知道为什么它有效..如果有人可以解释我。

谢谢:)