このメソッドを使用して、配列リスト内のデータをフェッチします
public ArrayList<NewsItem> getNews(String url) {
ArrayList<NewsItem> data = new ArrayList<NewsItem>();
java.lang.reflect.Type arrayListType = new TypeToken<ArrayList<NewsItem>>(){}.getType();
gson = new Gson();
httpClient = WebServiceUtils.getHttpClient();
try {
HttpResponse response = httpClient.execute(new HttpGet(url));
HttpEntity entity = response.getEntity();
Reader reader = new InputStreamReader(entity.getContent());
data = gson.fromJson(reader, arrayListType);
} catch (Exception e) {
Log.i("json array","While getting server response server generate error. ");
}
return data;
}
これは、ArrayList Typeクラス(ここではNewsItem)を宣言する方法です。
import com.google.gson.annotations.SerializedName;
public class NewsItem {
@SerializedName("title")
public String title;
@SerializedName("content")
public String title_details;
@SerializedName("date")
public String date;
@SerializedName("featured")
public String imgRawUrl;
}
これがWebSErviceUtilクラスです。
public class WebServiceUtils {
public static HttpClient getHttpClient(){
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 50000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 50000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
return httpclient;
}
}