Проблема с посылкой // ArrayList - PullRequest
0 голосов
/ 07 июня 2011

В настоящее время я пытаюсь передать ArrayList объектов из одного действия в другое.После долгих поисков я увидел, что вы можете передавать вещи как посылки.Вот что я в итоге сделал:

public class PartsList extends ArrayList<Part> implements Parcelable {

public PartsList(){

}

public PartsList(Parcel in){

}

@SuppressWarnings("unchecked")
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
    public PartsList createFromParcel(Parcel in) {
        return new PartsList(in);
    }

    public Object[] newArray(int arg0) {
        return null;
    }
};

private void readFromParcel(Parcel in) {
    this.clear();

    // read the list size
    int size = in.readInt();

    // order of the in.readString is fundamental
    // it must be ordered as it is in the Part.java file

    for (int i = 0; i < size; i++) {
        Part p = new Part();
        p.setDesc(in.readString());
        p.setItemNmbr(in.readString());
        p.setPrice(new BigDecimal(in.readString()));
        this.add(p);
    }
}


@Override
public int describeContents() {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public void writeToParcel(Parcel arg0, int arg1) {
    int size = this.size();

    arg0.writeInt(size);

    for (int i = 0; i < size; i++) {
        Part p = this.get(i);
        arg0.writeString(p.getDesc());
        arg0.writeString(p.getItemNmbr());
        arg0.writeString(p.getPrice().toString());
    }
}
    }

И вот часть объекта:

public class Part implements Parcelable{
private String desc;
private String itemNmbr;
private BigDecimal price;

public Part(){

}

public Part(String i, String d, BigDecimal p){
    this.desc = d;
    this.itemNmbr = i;
    this.price = p;
}

Он также имеет геттеры / сеттеры, конечно.

Этогде список создан:

for (String i : tempList){
        Matcher matcher = pattern.matcher(i);
        while (matcher.find()){

            // getting matches
            String desc = matcher.group(6);
            String item = matcher.group(9);
            BigDecimal price = new BigDecimal(matcher.group(12).toString());

            // adding the new part to the parts list
            parts.add(new Part(item, desc, price));
        }
    }

Теперь вот где он получен:

    public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  // get extras (list)
  Bundle b = getIntent().getExtras();
  parts = b.getParcelable("parts");
//    Part[] PARTS = (Part[]) parts.toArray();
  final Part[] PARTS = new Part[] {
    new Part("desc", "item id", new BigDecimal(0))    
  };
  final String[] COUNTRIES = new String[] {
        "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra"
      };
  setListAdapter(new ArrayAdapter<Part>(this, R.layout.list_item, PARTS));

  ListView lv = getListView();
  lv.setTextFilterEnabled(true);

  lv.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view,
        int position, long id) {
      // When clicked, show a toast with the TextView text
      Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
          Toast.LENGTH_SHORT).show();
    }
  });
}

Если я не использую посылку, а просто использую массив - это работаетхорошо.Я закомментировал свой список тестов, и он работал нормально, в противном случае он вылетел.

//          parts.add(new Part("desc", "item id", new BigDecimal(0)));
//          parts.add(new Part("desc2", "item id2", new BigDecimal(1)));
//          parts.add(new Part("desc3", "item id3", new BigDecimal(2)));
        // create a new bundle
        Bundle b = new Bundle();

        // put the list into a parcel
        b.putParcelable("parts", parts);
        Intent i = new Intent(SearchActivity.this, Results.class);

        // put the bundle into the intent
        i.putExtras(b);
        startActivity(i);

Что-то не так с реализацией посылки?Я не могу понять это.Если бы кто-нибудь мог помочь мне как можно скорее - это было бы удивительно.

1 Ответ

2 голосов
/ 07 июня 2011

В вашей реализации Parcelable.Creator это выглядит схематично:

public Object[] newArray(int arg0) {
    return null;
}

Я считаю, что это должно быть:

public Object[] newArray(int arg0) {
    return new PartsList[arg0];
}

Вам также нужно определить свой объект CREATOR для Part, есливы собираетесь объявить его для реализации Parcelable (хотя я не уверен, зачем это нужно).

...