2012年4月11日 星期三

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

2012年4月8日 星期日

Android-TQC105 MENU功能選單

學習重點:
(1)利用menu按鈕,改變setTitle



package COM.TQC.GDD01;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class GDD01 extends Activity {
 
 // ...
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    protected static final int MENU_ADD=Menu.FIRST;
    protected static final int MENU_DEL=Menu.FIRST+1;
    protected static final int MENU_ABOUT=Menu.FIRST+2;
    protected static final int MENU_Quit=Menu.FIRST+3;
        
    
    @Override
    //建立menu選單的項目
    public boolean onCreateOptionsMenu(Menu menu){
     super.onCreateOptionsMenu(menu);
     //新增menu選單,再利用onOptionsItemSelected擷取選單選擇項目,處理相對應的事件
     menu.add(0,MENU_ADD,0,getString(R.string.menu_add));
     menu.add(0,MENU_DEL,0,getString(R.string.menu_delete));
     menu.add(0,MENU_ABOUT,0,getString(R.string.menu_about));
     menu.add(0,MENU_Quit,0,getString(R.string.menu_exit));
          
     return true ; 
    }
    //menu被選擇執行後的事件處理
    public boolean onOptionsItemSelected(MenuItem item){
     //點選menu,出現四個選擇,以switch區分點選何項,設定title並繫結至其功能
     switch(item.getItemId()){
     
     case MENU_ADD:
      setTitleAdd();
     break;
     
     case MENU_DEL:
      setTitleDEL();
     break;
          
     case MENU_ABOUT:
      openAboutDialog();
     break;
     
     case MENU_Quit:
      openExitDialog();
     break;
     
     
     }
     return super.onOptionsItemSelected(item) ;
    }
    
    
    
    
    private void setTitleAdd() {
  // TODO Auto-generated method stub
  setTitle(getString(R.string.menu_add));
 }
 private void setTitleDEL() {
  // TODO Auto-generated method stub
  setTitle(getString(R.string.menu_delete));
 }
 //點選「關於」功能
    public void openAboutDialog()
    {     
     setTitle(getString(R.string.menu_about));
     AlertDialog.Builder dialog=new AlertDialog.Builder(this);
     dialog.setTitle(R.string.menu_add); //新增項目
     dialog.setMessage(R.string.menu_about_msg); //TQC+ Android認證題庫
     dialog.setPositiveButton(R.string.str_ok,new DialogInterface.OnClickListener()
     {      //確認 
   @Override
   public void onClick(DialogInterface arg0, int arg1) {
    // TODO Auto-generated method stub
    
   }
  });
       dialog.show();
       
    }
    //點選「離開」功能
    public void openExitDialog()
    {
        //開啟視窗詢問【是否確認離開系統?】,於訊息視窗點選「確認」後,關閉程式
     //於訊息視窗點選「取消」,則關閉此詢問視窗,則回到MENU功能選單畫面
     AlertDialog.Builder dialog = new AlertDialog.Builder(this);
     dialog.setTitle(R.string.menu_exit);//離開
     dialog.setMessage(R.string.menu_exit_msg); //是否確認離開系統
     dialog.setPositiveButton(R.string.str_ok,new DialogInterface.OnClickListener(){
           //確認     
   @Override
   public void onClick(DialogInterface arg0, int arg1) {
    // TODO Auto-generated method stub
    finish();
   }
      
     });
     dialog.setNegativeButton(R.string.str_cancel, new DialogInterface.OnClickListener() {
        //取消
   @Override
   public void onClick(DialogInterface arg0, int arg1) {
    // TODO Auto-generated method stub
     //dialog.dismiss();
   }
  });
      dialog.show();
       }
}

Android-TQC103點餐系統

學習重點:
(1)點選button呼叫AlertDialog
(2)將陣列的值放值AlertDialog中並將勾選的,顯示出來。



package COM.TQC.GDD01;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class GDD01 extends Activity {
  private Button button1;
  private TextView text1;
  private String[] s1={"美味蟹堡","義式香腸堡","蔬菜水果堡","香蕉潛艇堡","香烤雞肉堡"};
  private boolean[] chsBool={false,false,false,false,false,false}; //先將checkbox值設為false
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    
    findview();   //宣告物件
    setlistner();    
  }
  
private void findview(){
  // TODO Auto-generated method stub
  button1 = (Button) findViewById(R.id.button1);
     text1 = (TextView) findViewById(R.id.text1);
 }
  
private void setlistner() {
 // TODO Auto-generated method stub
 button1.setOnClickListener(new Button.OnClickListener()
    {
      @Override
      public void onClick(View v)
      {
       setdialog();
      }
     });
 }
 
 private void setdialog()
 {
  AlertDialog dialog=new AlertDialog.Builder(GDD01.this)
  //.setIcon(null)//設定無圖示
  .setTitle(getResources().getString(R.string.str2))
  .setMultiChoiceItems(s1, chsBool, new OnMultiChoiceClickListener()
  {
   public void onClick(DialogInterface dialog, int which, boolean isChecked)
   {
    
   }
  })
  .setPositiveButton("確認", new DialogInterface.OnClickListener() {
   public void onClick(DialogInterface dialog, int whichButton) {
    String selectedStr = "";
    
    
    for(int _i=0;_i< chsBool.length;_i++)
    {
     if(chsBool[_i] == true)
     {
      
     selectedStr=selectedStr+"\n"+s1[_i].toString();  //換行動作
            
     }
    }
    text1.setText("您點的餐有:"+selectedStr+"\n");
   }
  })
  .setNegativeButton("離開",  new DialogInterface.OnClickListener() {
   public void onClick(DialogInterface dialog, int whichButton) {
    
   }
  })
  .create();
  
  dialog.show();
      
 }
     
    } 
 

Android-TQC101整存整付計算機

學習重點:
(1)利用button將textview的值進行運作,並以settext方式呈現出計算的值


package COM.TQC.GDD01;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class GDD01 extends Activity 
{
 public Button mButton1;
 public EditText mEditText1,mEditText2,mEditText3;
 
 public TextView mTextView1;
 
 
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        mButton1=(Button)findViewById(R.id.submit);
        mEditText1=(EditText)findViewById(R.id.input_lend);
        mEditText2=(EditText)findViewById(R.id.input_rate);
        mEditText3=(EditText)findViewById(R.id.input_number);
        mTextView1=(TextView)findViewById(R.id.amount);
        
        mButton1.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View v) {
        
          int a =Integer.parseInt(mEditText1.getText().toString());
          Double b =Double.parseDouble(mEditText2.getText().toString());
          int c =Integer.parseInt(mEditText3.getText().toString());
    
          b=b/100/12+1;
          
          Double count=b;
          for(int i=1;i< c;i++)
    {
     count=count*b;
    }
                    
          int area= (int) (a*count);
          
          String answer=Integer.toString(area); 
          mTextView1.setText("本利和為"+answer);
   }
         
        });      
        
    }
}