gpt4 book ai didi

android - Android中如何正确使用Parcelable类

转载 作者:行者123 更新时间:2023-11-29 00:51:07 24 4
gpt4 key购买 nike

我有一个类(如下),我想通过 Intent 将其发送到服务类。我已经实现了 Parcelable 接口(interface),但不确定如何实际发送和检索整个对象,包括对象的当前状态。

特别是

@Override 
public void writeToParcel(Parcel dest, int flags) {
//I need this to send the entire state of the object
}

public UrlParamsHelper(Parcel in) {
//I need this to unpack the state of the object
}

这是实际的类

/*
* A holder class for URL parameters
*/
public static class UrlParamsHelper implements Parcelable {
private final HttpClient httpClient;
private final HttpParams params = new BasicHttpParams();
private final SchemeRegistry registry = new SchemeRegistry();
private final ThreadSafeClientConnManager manager;
private final Uri.Builder uri = new Uri.Builder();
final HttpHost host;

final String urlPath;
final String hostname;
/*
* @param hostname the hostname ie. http://www.google.com
* @param urlPath the path to the file of interest ie. /getfiles.php
*/
public UrlParamsHelper(final String hostname, final String urlPath) {
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
registry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(), 80));
manager = new ThreadSafeClientConnManager(params, registry);
httpClient = new DefaultHttpClient(manager, params);
host = new HttpHost(hostname, 80, "http");
uri.path(urlPath);

this.urlPath = urlPath;
this.hostname = hostname;
}

public UrlParamsHelper(Parcel in) {
//unpack the state
}

public void addQueryString(String key, String value) {
uri.appendQueryParameter(key, value);
}

public HttpGet buildGetQuery() {
return new HttpGet(uri.build().toString());
}

public HttpClient getHttpClient() {
return httpClient;
}

public HttpHost getHttpHost() {
return host;
}

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

@Override
public void writeToParcel(Parcel dest, int flags) {
//Parcel the entire state of the object
}

//Constructs the parcel again - REQUIRED
public static final Parcelable.Creator<UrlParamsHelper> CREATOR = new Parcelable.Creator<UrlParamsHelper>() {
public UrlParamsHelper createFromParcel(Parcel in) {
return new UrlParamsHelper(in);
}

public UrlParamsHelper[] newArray(int size) {
throw new UnsupportedOperationException();
//return new UrlParamsHelper[size];
}
};
}

最佳答案

在你的writeToParcel函数中,你需要将你想要的状态对象写入Parcel,例如:

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

写入对象的顺序无关紧要,只要您以相同的顺序读回它们即可:

@Override
public UrlParamsHelper(Parcel in) {
urlPath = in.readString();
hostname = in.readString();
}

问题是您只能读写 Parcel 文档中提到的对象类型, 因此可能很难完全保存所有内容。

关于android - Android中如何正确使用Parcelable类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2256451/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com