在刷新列表视图显示重复数据 [英] Listview display duplicate data on refresh

查看:311
本文介绍了在刷新列表视图显示重复数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经做了列表视图具有图像和文本元素。如果该数据是文本它显示文本,如果它是图象它显示图像。

当我点击从 MainActivity 按钮,列表视图,作为需要显示的列表视图,即图像,图像和文本的文本数据。

在ListView活动被打开,任何新的数据插入数据库时​​,会出现问题,并在ListView被刷新。在视图中的数据是完全搞砸了。它显示了一些文字数据的图像。

但是,当我回去的主要活动,并再次回来的ListView一切都是完美的。

谁能帮我怎么回事错在这里。

我使用SimpleCursorAdaptor,CursorLoader。

MainActivity.java

 公共类MainActivity扩展ActionBarActivity实现LoaderCallbacks<&光标GT; {从数据私人TextView的; 私人SimpleCursorAdapter DataAdapter的; 私人字符串TO_USER;
 ConnectionService connService;
 布尔mBounded; @覆盖
公共装载机<&光标GT; onCreateLoader(INT为arg0,ARG1捆绑){
的String [] =投影{MessageHelper.COLUMN_ID,
        MessageHelper.COLUMN_FROM,
            MessageHelper.COLUMN_DATA};
    字符串ARGS [] = {CID,数据};
        CursorLoader cursorLoader =新CursorLoader(这一点,
            MyContentProvider.CONTENT_URI,投影,
                    MessageHelper.COLUMN_CONVERSATION_ID +=? +和+
                    MessageHelper.COLUMN_EXIN +=? ,ARGS,
                    MessageHelper.COLUMN_RECIEVED_TIMESTAMP);
              返回cursorLoader;
}
公共无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    setListAdapter();
     getLoaderManager()initLoader(0,null,则此)。
}私人无效setListAdapter(){
     的String [] =列新的String [] {
                MessageHelper.COLUMN_FROM,
                MessageHelper.COLUMN_DATA
              };              INT []为= INT新[] {
                R.id.data
               };              光标光标= loadMessage();
              cursor.moveToFirst();
              DataAdapter的=新CustomCursorAdapter(
                        这个,
                        R.layout.linear_listitem,
                        光标,
                        列,
                        至,
                        0);              listview.setAdapter(DataAdapter的);
。}
公共无效onLoaderReset(装载机<&光标GT;装载机){
     dataAdapter.swapCursor(NULL);
} 保护无效onResume(){
  super.onResume();
  getLoaderManager()restartLoader(0,null,则此)。
 } 保护无效onRestart(){
     super.onRestart();
    }

CursorAdapter.java

 进口java.io.BufferedInputStream中;
进口的java.io.File;
进口java.io.FileNotFoundException;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口的java.net.URL;
进口java.net.URLConnection中;
进口的java.util.ArrayList;
进口的java.util.HashMap;
进口的java.util.Map;进口android.content.Context;
进口android.database.Cursor;
进口android.graphics.Bitmap;
进口android.graphics.BitmapFactory;
进口android.graphics.drawable.BitmapDrawable;
进口android.graphics.drawable.ClipDrawable;
进口android.net.Uri;
进口android.os.Environment;
进口android.provider.MediaStore;
进口android.view.Gravity;
进口android.view.LayoutInflater;
进口android.view.View;
进口android.view.ViewGroup;
进口android.widget.CursorAdapter;
进口android.widget.ImageView;
进口android.widget.RelativeLayout;
//进口android.widget.LinearLayout.LayoutParams;
进口android.widget.RelativeLayout.LayoutParams;
进口android.widget.SimpleCursorAdapter;
进口android.widget.TextView;进口com.expert.sqllite.MessageChat;
进口com.expert.sqllite.MessageHelper;公共类CustomCursorAdapter扩展SimpleCursorAdapter {
私人LayoutInflater mInflater;
私人地图<整数,ArrayList的< MessageChat>> chatMapConId =新的HashMap<整数,ArrayList的< MessageChat>>();
公共CustomCursorAdapter(上下文的背景下,INT布局,光标C,的String []从,INT []到,诠释标志){
    超(背景下,布局,C,发件人,收件人,旗);
    mInflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}@覆盖
公共无效bindView(查看视图,上下文的背景下,光标光标){    MessageChat msgchat =新MessageChat();
       msgchat.setData(cursor.getString(cursor.getColumnIndex(MessageHelper.COLUMN_DATA)));
      msgchat.setFrom(cursor.getString(cursor.getColumnIndex(MessageHelper.COLUMN_FROM)));
    ViewHolder持有人;
    如果(!msgchat.getData()包含( - 形象 - )){            支架=(ViewHolder)view.getTag();    }
    其他{
        支架=(ViewHolder)view.getTag();    }
            TextView的dataMsg =(TextView中)view.findViewById(R.id.data);
         RelativeLayout.LayoutParams LP1 =新RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);            ImageView的imgMsg = NULL;            如果(msgchat.getFrom()。equalsIgnoreCase(我))
            {                如果(!msgchat.getData()包含( - 形象 - )){
                    dataMsg.setBackgroundResource(R.drawable.speech_bubble_green);
                    dataMsg.setText(msgchat.getData());                }
                其他
                {
                    的String [] = imageSplit msgchat.getData()分( - 图像 - )。
                    乌里imgUri = Uri.parse(imageSplit [1]);
                    尝试{
                        imgMsg(ImageView的)view.findViewById(R.id.chat_image);
                        imgMsg.setImageBitmap(getThumbnail(imgUri,上下文));
                              dataMsg.setVisibility(View.INVISIBLE);
                    }赶上(FileNotFoundException异常五){
                        // TODO自动生成catch块
                        e.printStackTrace();
                    }赶上(IOException异常五){
                        // TODO自动生成catch块
                        e.printStackTrace();
                    }
                }
                lp1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            }            其他
            {                如果(!msgchat.getData()包含( - 形象 - )){
                    dataMsg.setBackgroundResource(R.drawable.speech_bubble_orange);
                    dataMsg.setText(msgchat.getData());
                }
                其他{
                    的String [] = imageSplit msgchat.getData()分( - 图像 - )。
                    乌里imgUri = Uri.parse(imageSplit [1]);
                    尝试{
                        imgMsg =(ImageView的)view.findViewById(R.id.chat_image);
                        imgMsg.setImageBitmap(getThumbnail(imgUri,上下文));
                        imgMsg.setBackgroundResource(R.drawable.speech_bubble_orange);
                    dataMsg.setVisibility(View.INVISIBLE);                    }赶上(FileNotFoundException异常五){
                        // TODO自动生成catch块
                        e.printStackTrace();
                    }赶上(IOException异常五){
                        // TODO自动生成catch块
                        e.printStackTrace();
                    }                }
                lp1.addRule(RelativeLayout.ALIGN_PARENT_LEFT);            }            如果(!msgchat.getData()包含( - 形象 - )){
            dataMsg.setLayoutParams(LP1);
            dataMsg.setTextColor(R.color.textColor);
            }
            其他{
                imgMsg.setLayoutParams(LP1);
            }}@覆盖
公共查看NewView的(上下文的背景下,光标光标的ViewGroup父){
    // TODO自动生成方法存根
    文件镜像文件;
    查看rowView = mInflater.inflate(R.layout.linear_listitem,父母,假);    查看rowViewImage = mInflater.inflate(R.layout.linear_listitem_image,父母,假);
    ViewHolder支架=无效;
    ViewHolderImage holderImage = NULL;    字符串数据= cursor.getString(cursor.getColumnIndex(MessageHelper.COLUMN_DATA));
    字符串路径= NULL;
    如果(data.contains( - 形象 - )){
    PATH = data.split( - 形象 - )[1];
    }        持有人=新ViewHolder();           holder.data =(TextView中)rowView.findViewById(R.id.data);
           holder.imageHolder =(ImageView的)rowViewImage.findViewById(R.id.chat_image);
            rowView.setTag(保持器);
            返回rowView;    }类ViewHolder
{
    TextView的数据显示,从;
    ImageView的imageHolder的;
}
类ViewHolderImage
{
    ImageView的imageHolder的;
}公共静态位图getThumbnail(URI URI,上下文语境)抛出FileNotFoundException异常,IOException异常{
    的InputStream输入= context.getContentResolver()openInputStream(URI)。    BitmapFactory.Options onlyBoundsOptions =新BitmapFactory.Options();
    onlyBoundsOptions.inJustDe codeBounds = TRUE;
    onlyBoundsOptions.inDither = TRUE; //可选
    onlyBoundsOptions.in preferredConfig = Bitmap.Config.ARGB_8888; //可选
    BitmapFactory.de codeStream(输入,空,onlyBoundsOptions);
    input.close();
    如果((onlyBoundsOptions.outWidth == -1)||(onlyBoundsOptions.outHeight == -1))
        返回null;    INT originalSize =(onlyBoundsOptions.outHeight> onlyBoundsOptions.outWidth)?onlyBoundsOptions.outHeight:onlyBoundsOptions.outWidth;   //双率=(originalSize> THUMBNAIL_SIZE)? (originalSize / THUMBNAIL_SIZE):1.0;
    双比= 1.0;
    BitmapFactory.Options bitmapOptions =新BitmapFactory.Options();
    //bitmapOptions.inSampleSize = getPowerOfTwoForSampleRatio(比率);
    bitmapOptions.inSampleSize = 2;    bitmapOptions.inMutable = TRUE;
    bitmapOptions.inDither = TRUE; //可选
    bitmapOptions.in preferredConfig = Bitmap.Config.RGB_565; //可选
    bitmapOptions.outHeight = 150;
    bitmapOptions.outWidth = 150;
    输入= context.getContentResolver()openInputStream(URI)。
    位图位图= BitmapFactory.de codeStream(输入,空,bitmapOptions);
    input.close();
    //bitmap.setWidth(400);
    //bitmap.setHeight(400);
    返回位图;
}私有静态诠释getPowerOfTwoForSampleRatio(双率){
    INT K = Integer.highestOneBit((int)的Math.floor(比));
    如果(K == 0)返回1;
    否则返回K表;
}

}

更新
如果我有数据仅文本或仅影像。然后列表视图是完美的。我认为这个问题是当两个视图即文字和图片进入图片。


解决方案

  @覆盖
公众诠释getItemViewType(INT位置){
    光标光标=(光标)的getItem(位置);
    返回getItemViewType(光标);
}@覆盖
公众诠释getViewTypeCount(){
    返回2;
}

这些方法解决了显示不正确的问题。

I have made a listview with image and text as elements. If the data is text it displays text and if it is image it displays image.

When i click button from MainActivity to the listview, the listview is displayed as needed, i.e images for image and text for text data.

The problem occurs when the listview activity is opened and any new data is inserted in db and the listview is refreshed. The data in the view is completely messed up. it shows image in the some of the text data.

But when i go back to the main activity and again come back to listview everything is perfect.

Can anyone please help me whats going wrong here.

I am using SimpleCursorAdaptor, CursorLoader.

MainActivity.java

public class MainActivity extends ActionBarActivity implements LoaderCallbacks<Cursor>{

private TextView from, data;

 private SimpleCursorAdapter dataAdapter;

 private String TO_USER;
 ConnectionService  connService;
 boolean mBounded;  

 @Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
String[] projection = {MessageHelper.COLUMN_ID,
        MessageHelper.COLUMN_FROM,
            MessageHelper.COLUMN_DATA};
    String args[] ={ "cid","data"};
        CursorLoader cursorLoader = new CursorLoader(this,
            MyContentProvider.CONTENT_URI, projection,   
                    MessageHelper.COLUMN_CONVERSATION_ID + " = ?" + " AND " + 
                    MessageHelper.COLUMN_EXIN + " =  ?" ,args, 
                    MessageHelper.COLUMN_RECIEVED_TIMESTAMP);
              return cursorLoader;
}
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setListAdapter();
     getLoaderManager().initLoader(0, null, this);
}



private void setListAdapter() {
     String[] columns = new String[] {
                MessageHelper.COLUMN_FROM,
                MessageHelper.COLUMN_DATA
              };

              int[] to = new int[] {
                R.id.data
               };

              Cursor cursor = loadMessage();
              cursor.moveToFirst();
              dataAdapter = new CustomCursorAdapter(
                        this,
                        R.layout.linear_listitem,
                        cursor,
                        columns,
                        to,
                        0);

              listview.setAdapter(dataAdapter);
.

}


public void onLoaderReset(Loader<Cursor> loader) {
     dataAdapter.swapCursor(null);
}

 protected void onResume() {
  super.onResume();
  getLoaderManager().restartLoader(0, null, this);
 }

 protected void onRestart(){
     super.onRestart();
    }

CursorAdapter.java

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection; 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ClipDrawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
//import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import com.expert.sqllite.MessageChat;
import com.expert.sqllite.MessageHelper;

public class CustomCursorAdapter extends SimpleCursorAdapter {
private LayoutInflater mInflater;
private Map<Integer, ArrayList<MessageChat>> chatMapConId = new HashMap<Integer, 

ArrayList<MessageChat>>();  
public CustomCursorAdapter(Context context, int layout, Cursor c, String[] from,          int[] to, int flags) {
    super(context, layout, c, from, to,flags);
    mInflater = (LayoutInflater)context.getSystemService

(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public void bindView(View view, Context context, Cursor cursor) {



    MessageChat msgchat = new MessageChat();
       msgchat.setData(cursor.getString(cursor.getColumnIndex(MessageHelper.COLUMN_DATA)));
      msgchat.setFrom(cursor.getString(cursor.getColumnIndex(MessageHelper.COLUMN_FROM)));


    ViewHolder  holder;
    if(!msgchat.getData().contains("-image-")){

            holder = (ViewHolder) view.getTag();

    }
    else{
        holder = (ViewHolder) view.getTag();

    }


            TextView dataMsg =(TextView)view.findViewById(R.id.data);
         RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams 

(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

            ImageView imgMsg =null;



            if(msgchat.getFrom().equalsIgnoreCase("me"))
            {

                if(!msgchat.getData().contains("-image-")){
                    dataMsg.setBackgroundResource

(R.drawable.speech_bubble_green);
                    dataMsg.setText(msgchat.getData());

                }
                else
                {
                    String[]         imageSplit=msgchat.getData().split("-image-");
                    Uri imgUri=Uri.parse(imageSplit[1]);
                    try {
                        imgMsg (ImageView)view.findViewById

(R.id.chat_image);
                        imgMsg.setImageBitmap(getThumbnail

(imgUri,context));




                              dataMsg.setVisibility(View.INVISIBLE);
                    } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }


                lp1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            }

            else
            {

                if(!msgchat.getData().contains("-image-")){
                    dataMsg.setBackgroundResource

(R.drawable.speech_bubble_orange);
                    dataMsg.setText(msgchat.getData());
                }
                else{
                    String[]   imageSplit=msgchat.getData().split("-image-");
                    Uri imgUri=Uri.parse(imageSplit[1]);
                    try {
                        imgMsg =(ImageView)view.findViewById

(R.id.chat_image);
                        imgMsg.setImageBitmap(getThumbnail

(imgUri,context));
                        imgMsg.setBackgroundResource

(R.drawable.speech_bubble_orange);
                    dataMsg.setVisibility(View.INVISIBLE);

                    } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
                lp1.addRule(RelativeLayout.ALIGN_PARENT_LEFT);

            }

            if(!msgchat.getData().contains("-image-")){
            dataMsg.setLayoutParams(lp1);
            dataMsg.setTextColor(R.color.textColor);
            }
            else{
                imgMsg.setLayoutParams(lp1);
            }



}



@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    // TODO Auto-generated method stub
    File imageFile;
    View rowView = mInflater.inflate(R.layout.linear_listitem, parent, false);

    View rowViewImage = mInflater.inflate(R.layout.linear_listitem_image,  parent, false);
    ViewHolder holder = null;
    ViewHolderImage holderImage = null;

    String data = cursor.getString(cursor.getColumnIndex(MessageHelper.COLUMN_DATA));
    String path = null;
    if(data.contains("-image-")){
    path = data.split("-image-")[1];
    }

        holder = new ViewHolder();

           holder.data = (TextView)rowView.findViewById(R.id.data);
           holder.imageHolder =   (ImageView)rowViewImage.findViewById(R.id.chat_image);
            rowView.setTag(holder);
            return rowView;

    }

class ViewHolder
{   
    TextView data,from;
    ImageView imageHolder ;
}
class ViewHolderImage
{   
    ImageView imageHolder ;
}

public static Bitmap getThumbnail(Uri uri,Context context) throw    FileNotFoundException,IOException{
    InputStream input = context.getContentResolver().openInputStream(uri);

    BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
    onlyBoundsOptions.inJustDecodeBounds = true;
    onlyBoundsOptions.inDither=true;//optional
    onlyBoundsOptions.inPreferredConfig=Bitmap.Config.ARGB_8888;//optional
    BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
    input.close();
    if ((onlyBoundsOptions.outWidth == -1) || (onlyBoundsOptions.outHeight == -1))
        return null;

    int originalSize = (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth) ? 

onlyBoundsOptions.outHeight : onlyBoundsOptions.outWidth;

   // double ratio = (originalSize > THUMBNAIL_SIZE) ? (originalSize / THUMBNAIL_SIZE):   1.0;
    double ratio = 1.0;
    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
    //bitmapOptions.inSampleSize = getPowerOfTwoForSampleRatio(ratio);
    bitmapOptions.inSampleSize = 2;

    bitmapOptions.inMutable = true;
    bitmapOptions.inDither=true;//optional
    bitmapOptions.inPreferredConfig=Bitmap.Config.RGB_565;//optional
    bitmapOptions.outHeight=150;
    bitmapOptions.outWidth=150;
    input = context.getContentResolver().openInputStream(uri);
    Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
    input.close();
    //bitmap.setWidth(400);
    //bitmap.setHeight(400);
    return bitmap;
}

private static int getPowerOfTwoForSampleRatio(double ratio){
    int k = Integer.highestOneBit((int)Math.floor(ratio));
    if(k==0) return 1;
    else return k;
}

}

Update If i have data only text or only image. Then the list view is perfect. The problem i think is when both the view i.e text and image comes into picture.

解决方案

    @Override
public int getItemViewType(int position) {
    Cursor cursor = (Cursor) getItem(position);
    return getItemViewType(cursor);
}

@Override
public int getViewTypeCount() {
    return 2;
}

These method has solved the problem of improper display

这篇关于在刷新列表视图显示重复数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆