程式碼片段-website程式
[WebMethod] public int Insert(String msg_content) { SqlConnection conn = new SqlConnection(CONNECT); conn.Open(); SqlTransaction tran = conn.BeginTransaction(); string sql = "Insert into Message(msg_content,msg_now) values (@msg_content, @msg_now)"; SqlCommand sqlcmd = new SqlCommand(sql, conn, tran); sqlcmd.Parameters.Add("@msg_content", SqlDbType.Text).Value = msg_content; sqlcmd.Parameters.Add("@msg_now", SqlDbType.DateTime).Value = DateTime.Now; try { sqlcmd.ExecuteNonQuery(); tran.Commit(); } catch (Exception e) { tran.Rollback(); } sqlcmd.Dispose(); conn.Close(); conn.Dispose(); return 1; //回傳成功,呈現數字1 }
程式碼畫面
以本機server測試,http://localhost/Website/WebService.asmx?op=Insert
android手機開發「讀取」button程式碼片段
insert=(Button)findViewById(R.id.button1); insert.setOnClickListener(new Button.OnClickListener(){ public void onClick(View arg0) { // TODO Auto-generated method stub final ProgressDialog mydialog=new ProgressDialog(TestActivity.this); mydialog.setTitle("請稍後!"); mydialog.setMessage("紀錄新增中...!"); mydialog.show(); //output.setText("測試~~~"); //output.setText(input.getText().toString()); System.out.println("1"); new Thread(){ public void run(){ int num; int x = 10; int y = 3; try{ //num = x/y; //模擬伺服器處理結果 //System.out.println("2:" + num); message = WebService.InsertMsg(input.getText().toString()); sleep(3000); handler.post(right_message); }catch(Exception a){ System.out.println("3"); handler.post(error_message); a.printStackTrace(); }finally{ System.out.println("4"); mydialog.dismiss(); } } }.start(); handler = new Handler(); right_message = new Runnable() { public void run() { // TODO Auto-generated method stub } }; error_message = new Runnable() { public void run() { // TODO Auto-generated method stub } }; System.out.println("5"); } }); public static String InsertMsg(String personal){ //String method = "getMessage"; String method = "Insert"; String output = ""; ArrayListlist = null; try { SoapObject request = new SoapObject(NAMESPACE, method); request.addProperty("msg_content", personal); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.dotNet = true; envelope.setOutputSoapObject(request); HttpTransportSE androidHttpTransport = new HttpTransportSE(URL_PATH + SERVICE_NAME); androidHttpTransport.call(NAMESPACE + method, envelope); Object result = envelope.getResponse(); output = result.toString(); }catch(Exception e){} System.gc(); return output; }
畫面執行結果
完整說明如下:
http://linjsian.blogspot.com/2012/04/android-buttonwebserver_10.html
沒有留言:
張貼留言