Android / AppEngine / JPA – sample


Is a simple example of how to deploy an android app using REST method to communicate to AppEngine,and how you can save data remotely with the JPA method.
Here you can find the sources of the two projects to import into eclipse (ClientAndroid/ServerAppEngine)
Test_Android_AppEngine.zip – 6.4 MB
Screen Android Client:

Servlet Code:

import java.io.IOException;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class Test_RestServerServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		String strKey = null, strName = null, strNum = null;
		boolean actGetAll, actEraseAll, actGetId, actEraseId;
		actGetAll = actEraseAll = actGetId = actEraseId = false;

		resp.setContentType("text/plain");

		if (req.getParameterMap().containsKey("insert_key")) {
			strKey = new String(req.getParameter("insert_key"));
		}
		if (req.getParameterMap().containsKey("insert_name")) {
			strName = new String(req.getParameter("insert_name"));
		}
		if (req.getParameterMap().containsKey("insert_num")) {
			strNum = new String(req.getParameter("insert_num"));
		}
		if (req.getParameterMap().containsKey("get_all_data")) {
			actGetAll = true;
			resp.getWriter().println(getallData());
		}
		if (req.getParameterMap().containsKey("get_data_by_key")) {
			actGetId = true;
			resp.getWriter().println(
					getDataByKey(req.getParameter("get_data_by_key")));
		}
		if (req.getParameterMap().containsKey("delete_data_by_key")) {
			actEraseId = true;
			resp.getWriter().println(
					deleteDataByKey(req.getParameter("delete_data_by_key")));
		}
		if (req.getParameterMap().containsKey("erase_all_data")) {
			actEraseAll = true;
			eraseallData();
		}

		if (strKey != null || strName != null || strNum != null) {
			insertData(strKey, strName, strNum);

			resp.getWriter().println(
					"OK,Receive INSERT REQ :3 data\n" + strKey.toString()
							+ " - " + strName.toString() + " - "
							+ strNum.toString());

		} else if (actGetAll == true) {
			resp.getWriter().println("\nGet all request");
		} else if (actEraseAll == true) {
			resp.getWriter().println("\nErase all request");
		} else if (actEraseId == true) {
			resp.getWriter().println("\nErase ID request");
		} else if (actGetId == true) {
			resp.getWriter().println("\nGet ID request");
		} else
			resp.getWriter().println("\nERROR REST REQUEST!!!");

	}

	private void insertData(String strKey, String strName, String strNum) {
		EntityManager em = EMF.get().createEntityManager();

		try {
			em.getTransaction().begin();
			em.persist(new TestDataRecord(strKey, strName, strNum));
			em.getTransaction().commit();

		} finally {
			em.close();
		}
	}

	private String getallData() {
		EntityManager em = EMF.get().createEntityManager();
		StringBuilder strblT = new StringBuilder();

		try {
			final List<TestDataRecord> list = em.createQuery(
					"select d from TestDataRecord d").getResultList();

			int numRecord = list.size();
			strblT.append("\nRecord found:" + String.valueOf(numRecord));

			for (TestDataRecord current : list) {
				strblT.append("\nkey :" + current.getDataKey() + "\nname :"
						+ current.getDataName() + "\nnum :"
						+ current.getDataNum() + "------\n");
			}

			return strblT.toString();

		} finally {
			em.close();
		}
	}

	private void eraseallData() {
		EntityManager em = EMF.get().createEntityManager();

		try {
			Query q = em.createQuery("DELETE FROM TestDataRecord m");
			q.executeUpdate();

		} finally {
			em.close();
		}
	}

	private String getDataByKey(String strKey) {
		EntityManager em = EMF.get().createEntityManager();

		try {
			Query q = em
					.createQuery("SELECT d FROM TestDataRecord d WHERE d.dataKey =  ?1");
			q.setParameter(1, strKey);
			try {
				TestDataRecord tdrT = (TestDataRecord) q.getSingleResult();

				return tdrT.getDataKey() + " - " + tdrT.getDataName() + " - "
						+ tdrT.getDataNum();
			} catch (NoResultException e) {
				return "ERROR - not found record";
			}
		} finally {
			em.close();
		}
	}

	private String deleteDataByKey(String strKey) {
		EntityManager em = EMF.get().createEntityManager();

		try {
			Query q = em
					.createQuery("SELECT d FROM TestDataRecord d WHERE d.dataKey =  ?1");
			q.setParameter(1, strKey);

			try {

				em.getTransaction().begin();
				TestDataRecord tdrT = (TestDataRecord) q.getSingleResult();
				em.remove(tdrT);
				em.getTransaction().commit();

				return "REMOVE OK";
			} catch (NoResultException e) {
				return "ERROR - not found record";
			}
		} finally {
			em.close();
		}
	}
}

Entity Code:

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

import com.google.appengine.api.datastore.Key;

@Entity
public class TestDataRecord {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Key key;

	private String dataKey;

	private String dataName;

	private String dataNum;

	/*
	 * methods for access to a data from app
	 */

	public TestDataRecord(String strKey,String strName,String strNum){
		setDataKey(strKey);
		setDataName(strName);
		setDataNum(strNum);
	}
	
	public Key getKey() {
		return key;
	}

	public String getDataKey() {
		return dataKey;
	}

	public void setDataKey(String strT) {
		this.dataKey = strT;
	}

	public String getDataName() {
		return dataName;
	}

	public void setDataName(String strT) {
		this.dataName = strT;
	}

	public String getDataNum() {
		return dataNum;
	}

	public void setDataNum(String strT) {
		this.dataNum = strT;
	}
}

ATTENTION:To communicate between the two applications you must change the name of serverlet app.
Credits:In the client project I used a class taken by http://lukencode.com

Lascia un commento

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione / Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione / Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione / Modifica )

Google+ photo

Stai commentando usando il tuo account Google+. Chiudi sessione / Modifica )

Connessione a %s...