AndroidからGAE(slim3)に登録されているデータを取得するサンプルを作成しました。
[開発環境]
・Eclipse Indigo
・Android 2.3.3
・Slim3 Version 1.0.13 (検索結果はJSON形式でクライアントに返す)
[サーバ(GAE)側のソース(Slim3を使用)]
[src\jp\co\hoshisoft\slim3sample02\controller\ListController.java]
package jp.co.hoshisoft.slim3sample02.controller;import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.List;import jp.co.hoshisoft.slim3sample02.meta.MemberMeta;
import jp.co.hoshisoft.slim3sample02.model.Member;
import jp.co.hoshisoft.slim3sample02.service.MemberService;import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.util.ThrowableUtil;public class ListController extends Controller {
private MemberService service = new MemberService();@Override
public Navigation run() throws Exception {List members = service.allList();
Object[] entityArray = members.toArray();
String ret = MemberMeta.get().modelsToJson(entityArray);
String encoding = request.getCharacterEncoding();
if (encoding == null) {
encoding = "UTF-8";
}
response.setContentType("application/json; charset=" + encoding);
try {
PrintWriter out = null;
try {
out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), encoding));
out.print(ret);
}
finally {
if (out != null) {
out.close();
}
}
}
catch (IOException e) {
ThrowableUtil.wrapAndThrow(e);
}return null;
}
}
[src\jp\co\hoshisoft\slim3sample02\model\Member.java]
package jp.co.hoshisoft.slim3sample02.model;import java.io.Serializable;
import com.google.appengine.api.datastore.Key;
import org.slim3.datastore.Attribute;
import org.slim3.datastore.Model;
import org.slim3.datastore.json.Json;@Model(schemaVersion = 1)
public class Member implements Serializable {private static final long serialVersionUID = 1L;
@Attribute(primaryKey = true, json=@Json(ignore=true))
private Key key;@Attribute(version = true, json=@Json(ignore=true))
private Long version;private String name;
private String email;
/**
* Returns the key.
*
* @return the key
*/
public Key getKey() {
return key;
}/**
* Sets the key.
*
* @param key
* the key
*/
public void setKey(Key key) {
this.key = key;
}/**
* Returns the version.
*
* @return the version
*/
public Long getVersion() {
return version;
}/**
* Sets the version.
*
* @param version
* the version
*/
public void setVersion(Long version) {
this.version = version;
}public String getName() {
return name;
}public void setName(String name) {
this.name = name;
}public String getEmail() {
return email;
}public void setEmail(String email) {
this.email = email;
}@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + *1;
return result;
}@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Member other = (Member) obj;
if (key == null) {
if (other.key != null) {
return false;
}
} else if (!key.equals(other.key)) {
return false;
}
return true;
}
}
[src\jp\co\hoshisoft\slim3sample02\service\MemberService.java]
package jp.co.hoshisoft.slim3sample02.service;import java.util.List;
import java.util.Map;import org.slim3.datastore.Datastore;
import org.slim3.util.BeanUtil;import com.google.appengine.api.datastore.Transaction;
import jp.co.hoshisoft.slim3sample02.meta.MemberMeta;
import jp.co.hoshisoft.slim3sample02.model.Member;public class MemberService {
public Member insert(Map
input) {
Member member = new Member();
BeanUtil.copy(input, member);
Transaction tx = Datastore.beginTransaction();
Datastore.put(member);
Datastore.commit(tx);
return member;
}public List
allList() {
MemberMeta e = new MemberMeta();
Listlist = Datastore.query(e)
.sort(e.name.asc)
.asList();return list;
}
[war\WEB-INF\appengine-web.xml]
<?xml version="1.0" encoding="utf-8"?>
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
<application>アプリケーションID</application>
<version>1</version>
<precompilation-enabled>true</precompilation-enabled>
<system-properties>
<property name="slim3.hotReloading" value="true"/>
<!--
<property name="slim3.datastoreDeadline" value="8"/>
<property name="slim3.uploadSizeMax" value="1000000"/>
<property name="slim3.uploadFileSizeMax" value="100000"/>
-->
<property name="java.util.logging.config.file" value="WEB-INF/classes/logging.properties"/>
</system-properties>
<sessions-enabled>false</sessions-enabled>
<threadsafe>true</threadsafe>
</appengine-web-app>
[war\WEB-INF\appengine-web.xml]
<?xml version="1.0" encoding="utf-8"?><web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5">
<context-param>
<param-name>slim3.rootPackage</param-name>
<param-value>jp.co.hoshisoft.slim3sample02</param-value>
</context-param>・
・
・
</web-app>
[クライアント(Android)側のソース]
[src\jp\co\hoshisoft\AndroidTest07Activity.java]
package jp.co.hoshisoft.androidtest07;import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;public class AndroidTest07Activity extends Activity {
static final String uri = "http://XXXXXXXX.appspot.com/list";private TextView txt;
private ListView list;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.txt = (TextView)findViewById(R.id.textView1);
this.list = (ListView)findViewById(R.id.listView1);
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
HttpClient httpClient = new DefaultHttpClient();
HttpUriRequest httpRequest = new HttpGet(uri);
HttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpRequest);
}
catch (ClientProtocolException e) {
//例外処理
}
catch (IOException e){
//例外処理
}
String json = null;
if (httpResponse != null && httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
HttpEntity httpEntity = httpResponse.getEntity();
try {
json = EntityUtils.toString(httpEntity);
}
catch (ParseException e) {
//例外処理
}
catch (IOException e) {
//例外処理
}
finally {
try {
httpEntity.consumeContent();
}
catch (IOException e) {
//例外処理
}
}
}
httpClient.getConnectionManager().shutdown();
AndroidTest07Activity.this.txt.setText(json);ArrayAdapter
adapter = new ArrayAdapter (AndroidTest07Activity.this, android.R.layout.simple_list_item_1);
try {
JSONArray items = new JSONArray(json);
for(int i = 0; i < items.length(); ++i) {
adapter.add(items.getJSONObject(i).getString("name") + ", " + items.getJSONObject(i).getString("email"));
}
AndroidTest07Activity.this.list.setAdapter(adapter);} catch (JSONException e) {
//例外処理
} catch (ParseException e) {
//例外処理
}
}
});
}
}
[res\layout\main.xml]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1" xmlns:android="http://schemas.android.com/apk/res/android">
<Button android:text="一覧取得" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<TextView android:text="TextView" android:id="@+id/textView1" android:layout_height="wrap_content" android:layout_width="match_parent" android:layout_weight="0.35"></TextView>
<ListView android:id="@+id/listView1" android:layout_width="match_parent" android:layout_height="196dp"></ListView>
</LinearLayout>
[実行時の画面]
*1:key == null) ? 0 : key.hashCode(