  | 
              
	              
	                
 
 
  
    
        
        Android กดปุ่มเเล้วโปรแกรมไม่ยอมค้างค่า กดแล้วปุ่มกลายเป็น OFF ตลอด     | 
   
  
    |   | 
   
 
 
 
              
  
          
		
     
		
	  
        
             | 
            | 
            | 
             | 
         
        
             | 
                       | 
          
            
               
                 นี่ code หน้า สั่งการ 
Code (Android-Java) 
package com.example.smarthome;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
public class Devicestatus extends Activity {
	
	private final Handler mHandler = new Handler();
	
	TextView textView1,textView2,textView3,textView4;
	ImageView devicestatus;
	
	static ToggleButton toggleButton1,toggleButton2,toggleButton3,toggleButton4;
	static String houseUrl;
	
	public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        // Fetch all data from MySQL DB
			getData();
	        
			this.setContentView(R.layout.devicestatus);
	        	    
			textView1 = (TextView)findViewById(R.id.textView1);
			textView2 = (TextView)findViewById(R.id.textView2);
			textView3 = (TextView)findViewById(R.id.textView3);
			textView4 = (TextView)findViewById(R.id.textView4);
			
			toggleButton1 = (ToggleButton)findViewById(R.id.toggleButton1);
			toggleButton2 = (ToggleButton)findViewById(R.id.toggleButton2);
			toggleButton3 = (ToggleButton)findViewById(R.id.toggleButton3);
			toggleButton4 = (ToggleButton)findViewById(R.id.toggleButton4);
			
			// Update the status of all toggle buttons
			updateToggles();
			
			toggleButton1.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					if (toggleButton1.isChecked()) {
						Smarthome.status = true;
						Devicestatus.postData();
					} else {
						// Set status to false
						// Send to DB
						Smarthome.status = false;
						Devicestatus.postData();
						
					}
				}
			}); 
			
			toggleButton2.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						if (toggleButton2.isChecked()) {
							Smarthome.status = true;
							Devicestatus.postData();
						} else {
							// Set status to false
							// Send to DB
							Smarthome.status = false;
							Devicestatus.postData();
							
						}
				}
			}); 
			
				toggleButton3.setOnClickListener(new OnClickListener() {
						public void onClick(View v) {
							if (toggleButton3.isChecked()) {
								Smarthome.status = true;
								Devicestatus.postData();
							} else {
								// Set status to false
								// Send to DB
								Smarthome.status = false;
								Devicestatus.postData();
								
							}
						}
				}); 
				
				toggleButton4.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						if (toggleButton4.isChecked()) {
							Smarthome.status = true;
							Devicestatus.postData();
						} else {
							// Set status to false
							// Send to DB
							Smarthome.status = false;
							Devicestatus.postData();
							
						}
					}
			}); 
			// Add mTask to execution queue and execute right away
				mHandler.post(mTask); // This is the timed thread handler
		} // end of onCreate
	
	// Timed thread for updating graphics and status
		private Runnable mTask = new Runnable() {
			public void run() {
				// Remove comment for debug only
				// counter1++;
				
				// Collect all data from MySQL DB
				getData();
				// Remove comment to display DB Update URL as toast (For debug only)
				//ShowToast(houseUrl);
				// Update all toggle graphics and texts
				updateToggles();
				// Call mTask 5 seconds later
				// mTask calls itself 5 seconds later from stack
				mHandler.postDelayed(mTask, 5000);        	
			}
		};
		
		public void onConfigurationChanged(Configuration newConfig) {
			super.onConfigurationChanged(newConfig);
			// Since first tab, default is 0
			Smarthome.tabNumber = 0;
			// On orientation change or keyboard pop-up preserve tab data
			Intent intent = new Intent(getBaseContext(),
					Smarthome.class);
			// Disables close and re-open animation
			overridePendingTransition(0, 0);
			intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
			// Finish the current activity
			finish();
			// Override remaining graphics
			overridePendingTransition(0, 0);
			// Call new intent of new orientation change
			startActivity(intent);						  
		}
		// Method called when application is closed
		protected void onDestroy(){
			// Make process Super 
			super.onDestroy();
			// Kill timer handler
			mHandler.removeCallbacks(mTask);
		}
		
		// Method called when application moved to background
		protected void onPause(){
			super.onPause();
			// When in background preserve default tab
			Smarthome.tabNumber = 0;
		}
		// Collect data from MySQL DB
		static public void getData(){
			try {
				// Create a URL object
				URL url = new URL("http://10.0.2.2/smarthome/DataRead.php");
				
				// Read all of the text returned by the HTTP server
				BufferedReader in = new BufferedReader
				(new InputStreamReader(url.openStream()));
										
				// Create data collection variables, string and string array
				String htmlText;
				String[] results;
				while ((htmlText = in.readLine()) != null) {
					// Keep in mind that readLine() strips the newline characters
					// Split the array based on the comma separation
					results = htmlText.split(",");		
					// Load all labels
					Smarthome.id = results[1];
					Smarthome.id = results[2];
					Smarthome.id = results[3];
					Smarthome.id = results[4];
					// Load all statuses
					if (results[1].equals("1")) {Smarthome.status = true;} else {Smarthome.status = false;}
					if (results[2].equals("1")) {Smarthome.status = true;} else {Smarthome.status = false;}
					if (results[3].equals("1")) {Smarthome.status = true;} else {Smarthome.status = false;}
					if (results[4].equals("1")) {Smarthome.status = true;} else {Smarthome.status = false;}
				}
				// Close the open file
				in.close();
			} catch (MalformedURLException e) {
				e.printStackTrace(); // Need code for exception
				System.exit(0);
				//Smarthome mSmarthome = new Smarthome();
				//mSmarthome.testHttpGet();
			} catch (IOException e) {
				e.printStackTrace(); // Need code for exception
				System.exit(0);
				//Smarthome mSmarthome = new Smarthome();
				//mSmarthome.testHttpGet();
			}
			// Return to caller
			return;
		}
		
		public static void postData(){
			// Local string from boolean status variables
			String mstatus;
			// Resolve boolean status to strings
			if (Smarthome.status.equals(true)) {mstatus = "1";} else {mstatus = "0";}
			if (Smarthome.status.equals(true)) {mstatus = "1";} else {mstatus = "0";}
			if (Smarthome.status.equals(true)) {mstatus = "1";} else {mstatus = "0";}
			if (Smarthome.status.equals(true)) {mstatus = "1";} else {mstatus = "0";}
			// Build URL
			houseUrl = "http://10.0.2.2/smarthome/UpdateTable.php";
			houseUrl += "?status=" + Smarthome.gpiopin;
			houseUrl += "&status=" + Smarthome.gpiopin;
			houseUrl += "&status=" + Smarthome.gpiopin;
			houseUrl += "&status=" + Smarthome.gpiopin;
			houseUrl += "&status=" + mstatus;
			houseUrl += "&status=" + mstatus;
			houseUrl += "&status=" + mstatus;
			houseUrl += "&status=" + mstatus;
			// Capture all spaces make them encoded for URL Transfer
			houseUrl = (houseUrl.replace(" ", "%20"));
			// Attempt HTTP Post to Apache Server using MySQL/PHP Script
			try {
				// Access the HTTP world
				HttpClient client = new DefaultHttpClient();  
				// Supply built URL
				String postURL = houseUrl;
				// Post data from URL in the background
				HttpPost post = new HttpPost(postURL); 
				// Collect response
				HttpResponse responsePOST = client.execute(post);  
				// Get response from HTTP Client
				HttpEntity resEntity = responsePOST.getEntity();  
				if (resEntity != null) { // Log event   
					Log.i("RESPONSE",EntityUtils.toString(resEntity));
				}
			} catch (Exception e) {
				e.printStackTrace(); // Need exception handling
			}
			// Return to caller
			return;
		}
		// Show display message on toast when called with variable argument
		public void ShowToast(String msg) {
			// Create new toast message with length long
			Toast toast = Toast.makeText(getApplicationContext(), msg,
					Toast.LENGTH_LONG);
			// Set the toast to display on top at 0,0 position
			toast.setGravity(Gravity.TOP, 0, 0);
			// Display toast
			toast.show();
		}
		// Method to update all toggles and status
		public void updateToggles(){
			// Change toggles from default to loaded value when first called
			// Toggle 1
			toggleButton1.setTextOn(Smarthome.gpiopin +"\nON");
			toggleButton1.setTextOff(Smarthome.gpiopin +"\nOFF");
			// Toggle 2
			toggleButton2.setTextOn(Smarthome.gpiopin +"\nON");
			toggleButton2.setTextOff(Smarthome.gpiopin +"\nOFF");
			// Toggle 3
			toggleButton3.setTextOn(Smarthome.gpiopin +"\nON");
			toggleButton3.setTextOff(Smarthome.gpiopin +"\nOFF");
			// Toggle 4
			toggleButton4.setTextOn(Smarthome.gpiopin +"\nON");
			toggleButton4.setTextOff(Smarthome.gpiopin +"\nOFF");
			// Load the graphical status of toggles
			toggleButton1.setChecked(Smarthome.status);
			toggleButton2.setChecked(Smarthome.status);
			toggleButton3.setChecked(Smarthome.status);
			toggleButton4.setChecked(Smarthome.status);
			// Change defaults of values in local cached flash
			SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
			SharedPreferences.Editor editor = settings.edit();
			editor.putString("room1Pref",Smarthome.gpiopin);
			editor.putString("room2Pref",Smarthome.gpiopin);
			editor.putString("room3Pref",Smarthome.gpiopin);
			editor.putString("room4Pref",Smarthome.gpiopin);
			editor.commit();
		}
}
 
 
ส่วนนี่ หน้า  main 
Code (Android-Java) 
package com.example.smarthome;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.TabActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
public class Smarthome extends TabActivity {
	static String toggleButton1, toggleButton2, toggleButton3, toggleButton4;
	
	static TabHost tabHost;
	
	static int tabNumber;
	
	static String id,gpiopin;
	static Boolean status;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_smarthome);
        
     // Test connection at boot to Apache web-server
     	testHttpGet();
     	
     // Call all from MySQL Database
     		Devicestatus.getData();
     	// Record all default values from MySQL DB to local flash cache
    		SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    		SharedPreferences.Editor editor = settings.edit();
    		/*editor.putString("room1Pref",Smarthome.id);
			editor.putString("room2Pref",Smarthome.id);
			editor.putString("room3Pref",Smarthome.id);
			editor.putString("room4Pref",Smarthome.id);*/
    		// Commit to record to flash
    		editor.commit();
    		tabHost = (TabHost)findViewById(android.R.id.tabhost);
    		Resources res = getResources(); // Resource object to get Drawables
    		
    		TabSpec firstTabSpec = tabHost.newTabSpec("tid1");
    		TabSpec secondTabSpec = tabHost.newTabSpec("tid1");
    		TabSpec thirdTabSpec = tabHost.newTabSpec("tid1");
    		
    		firstTabSpec.setIndicator("Home Status",
    				res.getDrawable(R.drawable.icon_devicestatus_tab)).setContent(new Intent(this,Devicestatus.class));
    		
    		secondTabSpec.setIndicator("Change Password",
    				res.getDrawable(R.drawable.icon_changepass_tab)).setContent(new Intent(this,Change.class));
    		
    		thirdTabSpec.setIndicator("About Us",
    				res.getDrawable(R.drawable.icon_aboutus_tab)).setContent(new Intent(this,Aboutus.class));
    		
    		tabHost.addTab(firstTabSpec);
    		tabHost.addTab(secondTabSpec);
    		tabHost.addTab(thirdTabSpec);
    		
    		tabHost.setCurrentTab(tabNumber);
 		
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	getMenuInflater().inflate(R.menu.activity_smarthome, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.exit_app:
			// if user press exit, finish application 
			// free all memory with exit animation
			// Return to default tab
			this.finish();
			System.exit(0); // Remove all application resources from memory
			System.runFinalizersOnExit(true); // Tell Android application is closed
			return true;
		}
    	// menu pressed again, exit menu
		return super.onOptionsItemSelected(item);
	}
    protected void onStop(){
		// Make process Super 
		super.onStop();
		// Kill timer handler
		// We need an Editor object to make preference changes.
		// All objects are from android.context.Context
		// Editor is at application private level 0 data cannot be shared with world
		SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
		SharedPreferences.Editor editor = settings.edit();
		// Commit the edits!
		editor.commit();
	}
    public void testHttpGet() {	
		try {		
			// Create a URL object
			URL url = new URL("http://10.0.2.2/smarthome/Present.php");
			// Read all of the text returned by the HTTP server
			BufferedReader in = new BufferedReader
			(new InputStreamReader(url.openStream()));
			// Create data collection variables
			@SuppressWarnings("unused") // It is used, glitch maybe?
			String htmlText;
			while ((htmlText = in.readLine()) != null) {
			}
			// Close the open file
			in.close();
		} catch (MalformedURLException e) {
			e.printStackTrace(); // Need code for exception
		} catch (IOException e) {
			Intent settingsActivity = new Intent(getBaseContext(),
					offline.class);
			startActivity(settingsActivity); // Start Death Box						
			finish();
			System.exit(0);
		}
	}
}
                        
               
               | 
             
            
              
			                              
                              
              
                
                     | 
                     | 
                     | 
                 
                
                     | 
                  
                      
                        | Date :
                            2013-04-19 22:52:58 | 
                        By :
                            shindo | 
                         
                    | 
                     | 
                 
                
                     | 
                     | 
                     | 
                 
                | 
             
           
			         | 
             | 
         
        
             | 
            | 
             | 
             | 
         
          
	    
     
               
		
     
		
	  
        
             | 
            | 
            | 
             | 
         
        
             | 
                       | 
          
            
               
                 Code มันเยอะเกินไปน่ะครับ ดูไม่ออกครับ คุณอาจจะต้องใช้การ Debug ดูเอง                          
               
               | 
             
            
              
			  			  
			                              
                              
              
                
                     | 
                     | 
                     | 
                 
                
                     | 
                  
                      
                        | Date :
                            2013-04-20 07:02:54 | 
                        By :
                            mr.win | 
                         
                    | 
                     | 
                 
                
                     | 
                     | 
                     | 
                 
                | 
             
           
			         | 
             | 
         
        
             | 
            | 
             | 
             | 
         
          
	    
     
               
		
     
		
	  
        
             | 
            | 
            | 
             | 
         
        
             | 
                       | 
          
            
               
                 แล้ว code php ของผมเขียนถูกมั้ยครับ ผมไม่แน่ใจคำสั่งในการเรียกค่าใน field status                        
               
               | 
             
            
              
			                              
                              
              
                
                     | 
                     | 
                     | 
                 
                
                     | 
                  
                      
                        | Date :
                            2013-04-20 08:57:09 | 
                        By :
                            shindo | 
                         
                    | 
                     | 
                 
                
                     | 
                     | 
                     | 
                 
                | 
             
           
			         | 
             | 
         
        
             | 
            | 
             | 
             | 
         
          
	    
     
               
		
     
		
	  
        
             | 
            | 
            | 
             | 
         
        
             | 
                       | 
          
            
               
                 คุณก็ลองเรียกไฟล์ php ตรง ๆ ดูเลยครับ โดยการสร้างตัวแปร เพื่อทดสอบครับ                          
               
               | 
             
            
              
			  			  
			                              
                              
              
                
                     | 
                     | 
                     | 
                 
                
                     | 
                  
                      
                        | Date :
                            2013-04-20 09:17:22 | 
                        By :
                            mr.win | 
                         
                    | 
                     | 
                 
                
                     | 
                     | 
                     | 
                 
                | 
             
           
			         | 
             | 
         
        
             | 
            | 
             | 
             | 
         
          
	    
     
               
		
     
		
	  
        
             | 
            | 
            | 
             | 
         
        
             | 
                       | 
          
            
               
                 ลองเรียกไฟล์ php ตรง แล้วครับมันขึ้น เชื่อมต่อได้ 
 
 แต่เวลาลองรันโปรแกรมเหมือนมันไม่ยอมรับค่าครับ                        
               
               | 
             
            
              
			                              
                              
              
                
                     | 
                     | 
                     | 
                 
                
                     | 
                  
                      
                        | Date :
                            2013-04-20 10:06:38 | 
                        By :
                            shindo | 
                         
                    | 
                     | 
                 
                
                     | 
                     | 
                     | 
                 
                | 
             
           
			         | 
             | 
         
        
             | 
            | 
             | 
             | 
         
          
	    
     
      		  
	
     | 
   
 
                 |