这个Android增删查的例子本来不打算写的,不过觉得这个热门的技术,不写一下,就跟不上潮流,另外也是太多人写了几乎雷同,似乎也没什么好些的,不过看到网上比较难找到完整的前后台进行通讯交互的例子,就写一下;
本例子涉及的面不算广,不过涉及的知识对于初学者来说也不少,具体涉及到java,servlet,mysl数据库连接,sql语句,json等,对于初学者来说,应该是不错的入门案例,如果有时间的人,可以对这个进行重构,扩展
现在先来看一下一个简单的网站架构图:
这里实现的是android部分
首先,表结构:
CREATE TABLE androiduser` ( `name` varchar(45) NOT NULL default '', `age` int(10) unsigned NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
主要的android类:
package minn.minnapp; /** * * @author minn * @@@ 394286006 * @email [email protected] * */ @TargetApi(Build.VERSION_CODES.GINGERBREAD) @SuppressLint("NewApi") public class MainActivity extends Activity { private View user = null; private UserService userService = null; private final static String HTTP_STR = "http://192.168.3.100:8080/minnAndroidServer/userServlet"; @TargetApi(Build.VERSION_CODES.GINGERBREAD) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads().detectDiskWrites().detectNetwork() .penaltyLog().build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects().detectLeakedClosableObjects() .penaltyLog().penaltyDeath().build()); userService = new UserService(); initBtn(); search(); } private void createWin() { LayoutInflater layoutInflater = LayoutInflater.from(this); user = layoutInflater.inflate(R.layout.user, null); new AlertDialog.Builder(this).setTitle(R.string.title_add) .setView(user) .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { add(); } }).setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).show(); } private void initBtn() { ((Button) findViewById(R.id.add)) .setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { createWin(); } }); ((Button) findViewById(R.id.close)) .setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub exit(); } }); ((Button) findViewById(R.id.search_btn)) .setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub search(); } }); } private void exit() { this.finish(); System.exit(0); } private void add() { Log.i("add", "开始新增数据"); EditText name = ((EditText) user.findViewById(R.id.name)); EditText age = ((EditText) user.findViewById(R.id.age)); StringBuffer params = new StringBuffer(); params.append("?method=add"); try { params.append("&name=" + URLEncoder.encode(name.getText().toString(), "UTF-8")); params.append("&age=" + age.getText().toString()); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } userService.request(HTTP_STR + params.toString()); search(); } private void del(String name, String age) { Log.i("del", "开始删除数据"); StringBuffer params = new StringBuffer(); params.append("?method=del"); try { params.append("&name=" + URLEncoder.encode(name, "UTF-8")); params.append("&age=" + age); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } userService.request(HTTP_STR + params.toString()); search(); } private void search() { Log.i("search", "开始加载数据"); StringBuffer params = new StringBuffer(); params.append("?method=search"); try { EditText name = ((EditText) findViewById(R.id.search_name)); String sname = ""; if (name.getText() != null) sname = name.getText().toString(); params.append("&name=" + URLEncoder.encode(sname, "UTF-8")); JSONObject jobj = userService.request(HTTP_STR + params.toString()); JSONArray jarr = (JSONArray) jobj.get("data"); TableLayout table = (TableLayout) findViewById(R.id.vtable); table.removeViews(1, table.getChildCount() - 1); for (int i = 0; i < jarr.length(); i++) { final JSONObject obj = jarr.getJSONObject(i); TableRow row = new TableRow(this); TextView t = new TextView(this); t.setWidth(80); t.setGravity(Gravity.CENTER); t.setPadding(3, 3, 3, 3); t.setText(obj.getString("name")); row.addView(t); t = new TextView(this); t.setGravity(Gravity.CENTER); t.setPadding(5, 3, 3, 3); t.setText(obj.getString("age")); row.addView(t); Button b = new Button(this); b.setPadding(3, 3, 3, 3); b.setWidth(20); b.setText("删除"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub try { del(obj.getString("name"), obj.getString("age")); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); row.addView(b); table.addView(row, new TableLayout.LayoutParams()); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
android发送请求公共方法:
/** * * @author minn * @@@ 394286006 * @email [email protected] * */ public JSONObject request(String req) { JSONObject rsobj=null; try { HttpClient hc=new DefaultHttpClient(); HttpGet hg=new HttpGet(req); HttpResponse response=hc.execute(hg); InputStreamReader isr=new InputStreamReader(response.getEntity().getContent()); BufferedReader br=new BufferedReader(isr); String rs=""; String rl=null; while((rl=br.readLine())!=null) rs+=rl; isr.close(); rsobj=new JSONObject(rs); } catch (Exception e) { //e.printStackTrace(); } return rsobj; }
j2ee工程主要代码:
package minn.service; /** * @author minn * @QQ 394286006 * @email [email protected] * */ public class UserService { DaoOperator daoOperator=new DaoOperator(); public JSONObject search(String name) throws Exception{ JSONObject jobj=new JSONObject(); try { jobj.put("success", true); jobj.put("data", daoOperator.query("SELECT name,age FROM androiduser where name like '"+name+"%'")); } catch (JSONException e) { // TODO Auto-generated catch block jobj.put("success", false); e.printStackTrace(); } return jobj; } public JSONObject add(String name ,String age) throws Exception{ JSONObject jobj=new JSONObject(); try { jobj.put("success", true); daoOperator.execute("insert into androiduser(name,age) values('"+name+"',"+age+")"); } catch (JSONException e) { // TODO Auto-generated catch block jobj.put("success", false); e.printStackTrace(); } return jobj; } public JSONObject del(String name,String age) throws Exception{ JSONObject jobj=new JSONObject(); try { jobj.put("success", true); daoOperator.execute("delete from androiduser where name='"+name+"' and age="+age); } catch (JSONException e) { // TODO Auto-generated catch block jobj.put("success", false); e.printStackTrace(); } return jobj; } }
效果图: