Friday, February 12, 2010

Programmer - How to use the Parcelable class properly in Android

I have a class I want to send to a Server through an intent. I have implemented the Parcelable interface but am unsure how to actually send and retrieve the strings.



In particular



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


And



public UrlParamsHelper(Parcel in) {
this(in.readString(), in.readString());
}


Here is the actual class



/*
* 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) {
this(in.readString(), in.readString());
}

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) {
dest.writeString(this.hostname);
dest.writeString(this.urlPath);
}

//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];
}
};
}

No comments:

Post a Comment

LinkWithin

Related Posts with Thumbnails