Android通过Intent传递ArrayList

时间:2014-01-22 06:14:58

标签: android listview csv android-intent android-listview

我试图将数据从一个屏幕传递到另一个屏幕。第一个屏幕从CSV读取数据并将数据放入数据库表中。任何无效的数据(例如年份(整数)中的字符串)都会被捕获并存储在errorItem的ArrayList中,该ArrayList包含Book title,author,date,isbn,copies和tags。我的程序已经成功识别出无效的csv条目,但是当我传递要显示的错误数据时,listview只显示最后一个条目并重复它。

这可能是什么问题?

Repeating Entry

主要代码

ArrayList<itemLink> errorList = new ArrayList<itemLink>();
                        int successCounter = 0;
                          int errorCounter = 0;
                          String[][] errors = new String[1][6];
                          String[] line = new String[6];
                          try {
                              int titleCol = -1, authorCol = -1, dateCol = -1, isbnCol = -1, quantityCol = -1, tagCol = -1;
                              CSVReader reader = new CSVReader(new FileReader(new File(Environment.getExternalStorageDirectory().getPath()+location)));
                              String [] nextLine;
                                nextLine = reader.readNext();
                                int index = 0;
                                int lineLength = nextLine.length;
                                while(titleCol < 0 && index < lineLength)
                                {
                                    if(nextLine[index].contains("TITLE"))
                                        titleCol = index;
                                    index++;
                                }
                                index = 0;
                                while(authorCol < 0 && index < lineLength)
                                {
                                    if(nextLine[index].contains("AUTHOR"))
                                        authorCol = index;
                                    index++;
                                }
                                index = 0;
                                while(dateCol < 0 && index < lineLength)
                                {
                                    if(nextLine[index].contains("DATE"))
                                        dateCol = index;
                                    index++;
                                }
                                index = 0;
                                while(isbnCol < 0 && index < lineLength)
                                {
                                    if(nextLine[index].contains("ISBN"))
                                        isbnCol = index;
                                    index++;
                                }
                                index = 0;
                                while(quantityCol < 0 && index < lineLength)
                                {
                                    if(nextLine[index].contains("COPIES"))
                                        quantityCol = index;
                                    index++;
                                }
                                index = 0;
                                while(tagCol < 0 && index < lineLength)
                                {
                                    if(nextLine[index].contains("TAGS"))
                                        tagCol = index;
                                    index++;
                                }
                                System.out.println(nextLine[titleCol]);
                                System.out.println(nextLine[authorCol]);
                                System.out.println(nextLine[dateCol]);
                                System.out.println(nextLine[isbnCol]);
                                System.out.println(nextLine[quantityCol]);
                                System.out.println(nextLine[tagCol]);
                                int counter = 0;
                                while ((nextLine = reader.readNext()) != null) {
                                    // nextLine[] is an array of values from the line
                                    /*
                                     * nextLine[titleCol] = TITLE
                                     * nextLine[authorCol] = AUTHOR
                                     * nextLine[dateCol] = DATE
                                     * nextLine[isbnCol] = ISBN
                                     * nextLine[quantityCol] = QUANTITY
                                     * nextLine[tagCol] = TAGS
                                     */
                                    lineLength = nextLine.length;
                                    if(nextLine[isbnCol].contains("0") || nextLine[isbnCol].contains("1") 
                                            || nextLine[isbnCol].contains("2") || nextLine[isbnCol].contains("3")
                                            || nextLine[isbnCol].contains("4") || nextLine[isbnCol].contains("5")
                                            || nextLine[isbnCol].contains("6") || nextLine[isbnCol].contains("7")
                                            || nextLine[isbnCol].contains("8") || nextLine[isbnCol].contains("9"))
                                    {

                                        if(InventoryAdapter.isbnFoundInInventory(nextLine[isbnCol]) == false)
                                        {

                                            if(nextLine[dateCol].contains("0") || nextLine[dateCol].contains("1") 
                                                    || nextLine[dateCol].contains("2") || nextLine[dateCol].contains("3")
                                                    || nextLine[dateCol].contains("4") || nextLine[dateCol].contains("5")
                                                    || nextLine[dateCol].contains("6") || nextLine[dateCol].contains("7")
                                                    || nextLine[dateCol].contains("8") || nextLine[dateCol].contains("9"))
                                                line[2] = nextLine[dateCol];
                                            else
                                                line[2]="-9999";
                                            if(nextLine[quantityCol].contains("0") || nextLine[quantityCol].contains("1") 
                                                    || nextLine[quantityCol].contains("2") || nextLine[quantityCol].contains("3")
                                                    || nextLine[quantityCol].contains("4") || nextLine[quantityCol].contains("5")
                                                    || nextLine[quantityCol].contains("6") || nextLine[quantityCol].contains("7")
                                                    || nextLine[quantityCol].contains("8") || nextLine[quantityCol].contains("9"))
                                                line[4] = nextLine[quantityCol];
                                            else
                                                line[4]="-9999";
                                            if(tagCol < lineLength && nextLine[tagCol].length() > 0)
                                                line[5] = nextLine[tagCol];
                                            else
                                                line[5] = "*ERROR*";
                                            if(titleCol < lineLength && nextLine[titleCol].length() > 0)
                                                line[0] = nextLine[titleCol];
                                            else
                                                line[0] = "*ERROR*";
                                            if(authorCol < lineLength && nextLine[authorCol].length() > 0)
                                                line[1] = nextLine[authorCol];
                                            else
                                                line[1] = "*ERROR*";
                                            if(isbnCol < lineLength && nextLine[isbnCol].length() > 0)
                                                line[3] = nextLine[isbnCol];
                                            else
                                                line[3] = "*ERROR*";

                                            if(line[0].equals("*ERROR*") || line[1].equals("*ERROR*")
                                                    || line[3].equals("*ERROR*")|| line[5].equals("*ERROR*")
                                                    || line[2].equals("-9999")|| line[4].equals("-9999"))
                                            {
                                                System.out.println(counter+". ERROR FOUND: "+line[0]);
                                                errorList.add(new itemLink(line[0], line[1], Integer.parseInt(line[2]), 
                                                        line[3], Integer.parseInt(line[4]), line[5]));
                                                errorCounter++;
                                            }
                                            else
                                            {
                                                System.out.println(counter+". SUCCESSFULLY ADDED: "+line[0]);
                                                InventoryAdapter.insertEntry(line[0], line[1], line[3], Integer.parseInt(line[2]),
                                                        line[5], Integer.parseInt(line[4]), 14);
                                                successCounter++;
                                            }
                                        }
                                    }
                                    counter++;

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

                          progressDialog.dismiss();

                          Intent i=new Intent(InventorySyncScreen.this,SyncSuccessScreen.class);
                            i.putExtra("username",userName);
                            i.putExtra("numSuccess",successCounter);
                            i.putExtra("numError", errorCounter);
                            i.putExtra("errorList", errorList);
                            startActivity(i);

SyncSuccessScreen

Intent intent = getIntent();
          final String userName = intent.getExtras().getString("username");
          int numSuccess= intent.getExtras().getInt("numSuccess");
          int numError= intent.getExtras().getInt("numError");
          @SuppressWarnings("unchecked")
          ArrayList<itemLink> errorList = (ArrayList<itemLink>) getIntent().getSerializableExtra("errorList");
          textNumSuccess.setText("Items Successfully Synced: "+numSuccess);
          textNumError.setText("Data Errors Found: "+numError);
// Set up array
            String[] errors = new String[6];
            for(int i = 0; i < errorList.size(); i++)
            {
                System.out.println("errors[0] = "+errors[0]);
                errors[0] = errorList.get(i).title;
                errors[1] = errorList.get(i).author;
                errors[2] = ((Integer)errorList.get(i).date).toString();
                errors[3] = errorList.get(i).isbn;
                errors[4] = ((Integer)errorList.get(i).quantity).toString();
                errors[5] = errorList.get(i).tags;
                    reportArray.add(new ErrorItem(i, errors));
            }

            // add data in custom adapter
            errorAdapter = new CustomErrorAdapter(this, R.layout.errorlist_row, reportArray);
            ListView dataList = (ListView) findViewById(R.id.errorlist_row);
            dataList.setAdapter(errorAdapter);

CustomErrorAdapter

public class CustomErrorAdapter extends ArrayAdapter<ErrorItem> {
Context context;
int layoutResourceId;
LinearLayout linearMain;
ArrayList<ErrorItem> data = new ArrayList<ErrorItem>();

public CustomErrorAdapter(Context context, int layoutResourceId,
              ArrayList<ErrorItem> data) {
       super(context, layoutResourceId, data);
       this.layoutResourceId = layoutResourceId;
       this.context = context;
       this.data = data;
}

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

   if (convertView == null) {
          LayoutInflater inflater = ((Activity) context).getLayoutInflater();
          row = inflater.inflate(layoutResourceId, parent, false);
          //Make sure the textview exists in this xml
   } else {
          row = convertView;
   }

   ErrorItem myItem = data.get(position);
   TextView titleLabel = (TextView) row.findViewById(R.id.titleText);
   titleLabel.setText(myItem.details[0]);
   TextView authorLabel = (TextView) row.findViewById(R.id.authorText);
   authorLabel.setText(myItem.details[1]);
   TextView dateLabel = (TextView) row.findViewById(R.id.dateText);
   dateLabel.setText(myItem.details[2]);
   TextView isbnLabel = (TextView) row.findViewById(R.id.isbnText);
   isbnLabel.setText(myItem.details[3]);
   TextView copiesLabel = (TextView) row.findViewById(R.id.copiesText);
   copiesLabel.setText(myItem.details[4]);
   TextView tagLabel = (TextView) row.findViewById(R.id.tagText);
   tagLabel.setText(myItem.details[5]);

   if(myItem.details[5].equals("*ERROR*"))
       tagLabel.setTextColor(Color.parseColor("#ff2626"));
   if(myItem.details[2].equals("-9999"))
       dateLabel.setTextColor(Color.parseColor("#ff2626"));
   if(myItem.details[4].equals("-9999"))
       copiesLabel.setTextColor(Color.parseColor("#ff2626"));
   if(myItem.details[0].equals("*ERROR*"))
       titleLabel.setTextColor(Color.parseColor("#ff2626"));
   if(myItem.details[1].equals("*ERROR*"))
       authorLabel.setTextColor(Color.parseColor("#ff2626"));
   if(myItem.details[3].equals("*ERROR*"))
       isbnLabel.setTextColor(Color.parseColor("#ff2626"));

   return row;
}
}

错误项

public class ErrorItem {

   public int num;
   public String[] details;

   public ErrorItem(int num, String[] details) {
          super();

          this.details = details;
   }
   public int getNum() {
       return num;
   }
   public void setNum(int num) {
       this.num = num;
   }
   public String[] getDetails() {
          return details;
   }
   public void setDetails(String[] details) {
          this.details = details;
   }

}

日志显示 日志显示ArrayList正在正确传递到SyncSuccessScreen。

01-22 01:42:51.327: I/System.out(8717): errors[0] = *ERROR*
01-22 01:42:51.327: I/System.out(8717): errors[0] = The big beautiful
01-22 01:42:51.327: I/System.out(8717): errors[0] = Pieces of my sister's life

4 个答案:

答案 0 :(得分:3)

你必须在类Itemlink上实现serialisable,并且必须从getintent().getserialisableExtra()

获取活动的价值

例如:

public class Itemlink implements Serializable{

} 将值传递为

intent.putExtra("key",value);
getvalue as `getintent().getSerilaziable.Extra("key")`

答案 1 :(得分:2)

当您需要传达自定义对象(例如ErrorItem)时,自定义对象必须实现ParcelableSerializable

class ErrorItem implements Parcelable{

检查this

检查Parcelable is faster than Serializable

答案 2 :(得分:1)

错误发生在SyncSuccessScreen

errors[0] = errorList.get(i).title;
            errors[1] = errorList.get(i).author;
            errors[2] = ((Integer)errorList.get(i).date).toString();
            errors[3] = errorList.get(i).isbn;
            errors[4] = ((Integer)errorList.get(i).quantity).toString();
            errors[5] = errorList.get(i).tags;
                reportArray.add(new ErrorItem(i, errors));

应该声明String []错误的新实例,否则每个ErrorItem引用相同的String []错误,并且更改其中一个会影响每个ErrorItem。

<强>正确:

String[] errors = new String[6];
        for(int i = 0; i < errorList.size(); i++)
        {
            errors = new String[6]; //add this
            errors[0] = errorList.get(i).getTitle();
            errors[1] = errorList.get(i).getAuthor();
            errors[2] = ((Integer)errorList.get(i).getDate()).toString();
            errors[3] = errorList.get(i).getISBN();
            errors[4] = ((Integer)errorList.get(i).getQuantity()).toString();
            errors[5] = errorList.get(i).getTags();
            reportArray.add(i, new ErrorItem(i, errors));
        }

答案 3 :(得分:0)

让你的ErrorItem实现Serializable

public class ErrorItem implements Serializable{

并在您的意图中更改此行:   i.putExtra(“errorList”,errorList); 至  i.putSerializableExtra( “errorList”,errorList);

然后得到它:

ArrayList errorList =(ArrayList)getIntent()。getSerializableExtra(“errorList”);