2012年4月11日 星期三

Android-TQC109 AlertDialog顯示結果

學習重點:
(1)利用 button與AlertDialog結合利用



package COM.TQC.GDD01;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;

public class GDD01 extends Activity {
  private EditText et;
  private RadioButton rb1;
  private RadioButton rb2;
  private CheckBox cb1;
  private CheckBox cb2;
  private CheckBox cb3;
  private Button button;
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    et = (EditText) findViewById(R.id.name);
    rb1 = (RadioButton) findViewById(R.id.rButton1);
    rb2 = (RadioButton) findViewById(R.id.rButton2);
    cb1 = (CheckBox) findViewById(R.id.cBox1);
    cb2 = (CheckBox) findViewById(R.id.cBox2);
    cb3 = (CheckBox) findViewById(R.id.cBox3);
    button = (Button) findViewById(R.id.button1);
        
    button.setOnClickListener(new Button.OnClickListener(){

      public void onClick(View v){
     String s="";
     String b =""; 
        if(!et.getText().toString().equals("")){
         s += "姓名:"+et.getText().toString()+"\n";
        }else{
         s += "姓名:未填\n";
        }
        
        if(rb1.isChecked()){
         s +="性別:"+rb1.getText().toString()+"\n";
        }else{
         s +="性別:"+rb2.getText().toString()+"\n";
        }
        
        
        if(cb1.isChecked()){
         b +=cb1.getText().toString()+",";
        }
        if(cb2.isChecked()){
         b +=cb3.getText().toString()+",";
        }
        if(cb3.isChecked()){
         b +=cb2.getText().toString()+",";
        }
        
        if(!b.equals("")){
         s += "興趣:" + b;
        }else{
         s += "興趣:未選擇";
        }
        
        new AlertDialog.Builder(GDD01.this)
        .setTitle("結果")
        .setMessage(s)
        .setPositiveButton("離開", new DialogInterface.OnClickListener() {
   
   public void onClick(DialogInterface arg0, int arg1) {
    // TODO Auto-generated method stub
    
   }
  })
        .show();
      }
    });
  }
}

android開發-利用button進行webserver資料存取-完整程式碼

以本機進行web方法畫面呈現
輸入http://localhost/Website/WebService.asmx




using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;

/// 
/// WebService 的摘要描述
/// 
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// 若要允許使用 ASP.NET AJAX 從指令碼呼叫此 Web 服務,請取消註解下一行。
// [System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
    private const string CONNECT = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True;User Instance=True";

    public WebService () {

        //如果使用設計的元件,請取消註解下行程式碼 
        //InitializeComponent(); 
    }

    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }

    [WebMethod]
    public string HelloAndroid(string whoName)
    {
        string output;

        output = whoName + " 您好,這是Android Web Service";

        return output;
    }

    [WebMethod]
    public string[] getMessage()
    {
        String[] output = null;

        output = new String[] { "早安", "Hello", "How are you?", "Ok", "7 見"};

        return output;
    }

    [WebMethod] //取得資料紀錄
    public string[] getRecord()
    {
        String[] output = null;

        //產生資料庫連線
        SqlConnection conn = new SqlConnection(CONNECT);

        conn.Open();

        //需要執行 SQL 指令
        string sql = "Select msg_content, msg_now From Message Order by msg_id desc";

        //產生指令物件
        SqlCommand sqlcmd = new SqlCommand(sql, conn);

        SqlDataAdapter da = new SqlDataAdapter();
        DataTable dt = new DataTable();

        da.SelectCommand = sqlcmd;
        da.Fill(dt);

        //記錄筆數判斷
        if (dt.Rows.Count > 0)
        {
            output = new String[dt.Rows.Count];

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                //讀取 msg_content
                output[i] = dt.Rows[i].ItemArray[0].ToString() + "    ";
                //讀取 msg_now
                output[i] += dt.Rows[i].ItemArray[1].ToString();
            }
        }

        da.Dispose();
        dt.Dispose();
        sqlcmd.Dispose();
        conn.Close();
        conn.Dispose();

        return output;
    }

    [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
    }
    
}


畫面執行步驟
程式範例
package tw.edu.nfu;

import java.util.ArrayList;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class TestActivity extends Activity {
    /** Called when the activity is first created. */
 private EditText input;
 private TextView output;
 private Button btn,insert;
 private ListView dataList;
 private static Handler handler;
 private static Runnable right,right_message;
 private static Runnable error,error_message;
 private static String result;
 private static String[] Msg = new String[]{"大家好","Hello","中午一起吃個飯如何","Ok", "7 見"};
 private static ArrayList messageList;
 private static String message;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        input=(EditText)findViewById(R.id.editText);
        output=(TextView)findViewById(R.id.textView1);
        dataList = (ListView)findViewById(R.id.listView1);
        btn=(Button)findViewById(R.id.btn);
        insert=(Button)findViewById(R.id.button1);
        
        btn.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);
       messageList = WebService.Welcome(input.getText().toString());
       
       sleep(3000);
       handler.post(right);
      }catch(Exception a){
       System.out.println("3");
       handler.post(error);
       a.printStackTrace();
      }finally{
       System.out.println("4");
       mydialog.dismiss();
      }
     }
    }.start();
   
    handler = new Handler();
    right = new Runnable() 
    {
     public void run() {
      // TODO Auto-generated method stub
      System.out.println("6");
      output.setText(result);
      
      ArrayAdapter myAdp = new ArrayAdapter(TestActivity.this,android.R.layout.simple_list_item_1,messageList);
      dataList.setAdapter(myAdp);
     }
     
    };
    
    error = new Runnable() 
    {

     public void run() {
      // TODO Auto-generated method stub
      System.out.println("7");
      output.setText("執行失敗");
     }
     
    };
    
    System.out.println("5");
    
   }
         
        });
        
        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
      Toast.makeText(TestActivity.this, message, Toast.LENGTH_LONG).show();
     }
     
    };
    
    error_message = new Runnable() 
    {

     public void run() {
      // TODO Auto-generated method stub
      
     }
     
    };
    
    System.out.println("5");
    
   }
         
        });
    }
    
    public static class WebService {
     public static final String NAMESPACE = "http://tempuri.org/"; 
     public static final String URL_PATH = "http://10.0.2.2/website/";
     public static final String SERVICE_NAME = "WebService.asmx"; 
     
        public static String InsertMsg(String personal){
      
      //String method = "getMessage";
      String method = "Insert";
      String output = "";
      ArrayList list = 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;  
     }
     
     public static ArrayList Welcome(String personal){
      
      //String method = "getMessage";
      String method = "getRecord";
      String output = "";
      ArrayList list = null;

      try
      {
       
       SoapObject request = new SoapObject(NAMESPACE, method);
       //request.addProperty("whoName", 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();
             SoapObject result = (SoapObject)((SoapObject)envelope.bodyIn).getProperty(0);
             
             if(result != null && result.getPropertyCount()>0)
             {
              list  = new ArrayList();
              
              for(int i = 0; i < result.getPropertyCount(); i++)
              {
               SoapPrimitive msg_content = (SoapPrimitive)result.getProperty(i);
               list.add(msg_content.toString());
              }
             }
             
      }catch(Exception e){}
      
      System.gc();
   
      return list;  
     }
    }
}

android開發-利用button進行webserver資料存取-簡單介紹



程式碼片段-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 = "";
      ArrayList list = 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