如何在Android中创建可分配的对象列表?

时间:2015-06-23 14:59:37

标签: android parcelable

所以我有一个应用程序,通过API在互联网上搜索艺术家,并在执行此搜索后显示结果列表(艺术家姓名)。我希望保留此列表,因为我更改了设备的方向(纵向 - 横向),而无需再次执行搜索。这是一些代码:

public class MainActivityFragment extends Fragment{

    public static final String ARTIST_ID = "artistId";
    private final String NO_RESULTS = "No artists found. Please check your input!";

    private List<Artist> artists = new ArrayList<>();
    private ArtistArrayAdapter adapter;

    public MainActivityFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_main, container, false);

        final SearchView searchView = (SearchView) rootView.findViewById(R.id.search_artist);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String artistName) {
                SearchArtist(artistName);
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(searchView.getWindowToken(), 0);
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });

        ListView listView = (ListView) rootView.findViewById(android.R.id.list);
        adapter = new ArtistArrayAdapter(getActivity(), R.layout.artist_list_item, artists);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Artist artist = artists.get(position);
                String artistId = artist.id;
                Intent detailArtist = new Intent(getActivity(), DetailActivity.class);
                detailArtist.putExtra(ARTIST_ID, artistId);
                startActivity(detailArtist);
            }
        });

        return rootView;
    }

所以我认为我必须使艺术家列表可以使用,然后将其传递给onSaveInstanceState方法。但是如何使这个列表变得可以分辨?

非常感谢,我希望这不会让人感到困惑......

3 个答案:

答案 0 :(得分:7)

您需要为Artist Data Model类实现Parcelable接口。例如

public class ArtistParcelable implements Parcelable {
    public String id;
    public String artistName;
    public List<String> artistImageUrls = Collections.emptyList();

    public ArtistParcelable(Artist artist) {
        // Do the assignments here
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        //write 
        dest.writeString(this.id);
        dest.writeString(this.artistName);
        dest.writeStringList(this.artistImageUrls);
    }

    protected ArtistParcelable(Parcel in) {
        //retrieve
        this.id = in.readString();
        this.artistName = in.readString();
        this.artistImageUrls = in.createStringArrayList();
    }

    public static final Parcelable.Creator<ArtistParcelable> CREATOR = new Parcelable.Creator<ArtistParcelable>() {
        public ArtistParcelable createFromParcel(Parcel source) {
            return new ArtistParcelable(source);
        }

        public ArtistParcelable[] newArray(int size) {
            return new ArtistParcelable[size];
        }
    };
}

在你的片段中 - 如果你有List mArtists,那么你保存并检索像

这样的列表
@Override
public void onSaveInstanceState(final Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putParcelableArrayList(ARTISTS, (ArrayList<? extends Parcelable>) mArtists);
}

在onCreateView

if (savedInstanceState != null) {
        mArtists = savedInstanceState.getParcelableArrayList(ARTISTS);

这是一个很好的指南,您可以遵循。 https://guides.codepath.com/android/Using-Parcelable

还有一个名为Android Parcelable Code Generator的IDE插件,可以为您生成所有样板代码。

还有一个名为Parceler的图书馆,非常方便。它完全删除了样板。

答案 1 :(得分:0)

首先,您的Artist类必须实现parcelable

public class Artist implements Parcelable

然后你应该覆盖你想要保存的方法writeToParcel,例如:

  @Override
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeString(mSavedString);
     }

创建一个构造函数来读取已保存的变量:

 protected Artist(Parcel in){
    mSavedString = in.readString();
}

然后是创作者:

 public static final Parcelable.Creator<Artist> CREATOR
             = new Parcelable.Creator<Artist>() {
         public Artist createFromParcel(Parcel in) {
             return new Artist(in);
         }

         public Artist[] newArray(int size) {
             return new Artist[size];
         }
     };

最后你的活动覆盖onsavedinstance:

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putParcelableArray("AristArray", mArtistArray);
}

另外,不要忘记在活动的创建上执行此操作:

 if (savedInstanceState != null) {
   mArtistArray= new List<Artist>(savedInstanceState.getParcelableArray("ArtistArray"));
 }

Ps:没试过代码,所以你想知道的任何问题,我会尽力帮助你;)

src:http://developer.android.com/reference/android/os/Parcelable.html

希望有所帮助;)

答案 2 :(得分:0)

如何修改Artist类以使其成为Parcelabel。

public class Artist implements Parcelable {

    public static final Creator<Artist> CREATOR = new Creator<Artist>() {
        public Artist createFromParcel(Parcel source) {
            return new Artist(source);
        }

        public Artist[] newArray(int size) {
            return new Artist[size];
        }
    };

    private final String name;

    public Artist(String name) {
        this.name = name;
    }

    private Artist(Parcel in) {
        name = in.readString();
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
    }

    @Override
    public int describeContents() {
        return 0;
    }

    public String getName() {
        return name;
    }
}

然后使用以下。

protected void onSaveInstanceState(Bundle outState) {
 outState.putParcelableArrayList("key_artists",artists);
}