Friday, June 8, 2012

Project MotionMote - Control Games via Android Phone Wirelessly


MotionMote is all about turning your Android smart phone to control PC games. This idea be extended for other mobile OS platforms as well.

Most of the motion based controllers WiiMote and PlayStationMove are not very popular in  computer gaming due to price, lack of connectivity. Instead joysticks, joy pads and steering wheels are heavily used for computer simulation based games, but they do not support motion detection. The MotionMote binds the functionality of smartphone touch screen and and motion sensors, to create a virtual gaming environment for PC simulation based games wirelessly. The six axis accelerometer sensor and the multi-touch technology in the latest smartphones gives precise inputs to the PC.

The smartphone and the computer should be connected through wifi. Data is transmitted to the computer via the phone, and then the compute retransmit  data to virtual joypad (PPJoy) is a virtual joystick driver.

All the executable files can be downloaded from here.

Technologies used
  • Android SDK 2.1(Mobile App)
  • .Net Framework 3.5(Desktop Application)
References – DroidPad

Thursday, September 8, 2011

Android MySQL Connectivity via JSON


The most common way to connect to a remote MySQL database from an android device, is to put some kind of service into the middle. Since MySQL is usually used together with PHP, the easiest and most obvious way to write a PHP script to manage the database and run this script using HTTP protocol from the android system.

Earlier in my post I have mentioned a way of connection via mysql connector Link

This example source code provides two way synchronization (Phone to Server and from Server to Phone)

Send Data from SQLite to MySQL

      //Retrieve query results in cursor format
      startManagingCursor(cs);  
      if(cs!=null)  
      {  
           cs.moveToFirst();  
           jsonarray = new JSONArray();  
           while (cs.isAfterLast() == false) {  
           json = new JSONObject();  
      try {  
           json.put("a",cs.getString(cs.getColumnIndex("a")));  
           json.put("b",cs.getString(cs.getColumnIndex("b")));  
           json.put("c",cs.getString(cs.getColumnIndex("c")));   
           jsonarray.put(json);  
           cs.moveToNext();  
      }  
      catch (Exception e) {  
           Log.d("Android", "JSON Error");  
      }  
           }  
           try {  
           // Create a new HttpClient and Post Header  
           HttpClient httpclient = new DefaultHttpClient();  
           HttpPost httppost = new HttpPost("http://192.168.1.1/set_file.php");  
           // Post the data:  
           StringEntity se = new StringEntity(jsonarray.toString());  
           httppost.setEntity(se);  
           httppost.setHeader("Accept", "application/json");  
           httppost.setHeader("Content-type", "application/json");  
           // Execute HTTP Post Request  
           System.out.print(json);  
           HttpResponse response = httpclient.execute(httppost);  
           // for JSON:  
           if(response != null)  
           {  
                InputStream is = response.getEntity().getContent();  
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));  
                StringBuilder sb = new StringBuilder();  
                String line = null;  
                try {  
                     while ((line = reader.readLine()) != null) {  
                     sb.append(line + "\n");  
                     }  
                } catch (IOException e) {  
                     e.printStackTrace();  
                     }   
                finally {  
                     try {  
                          is.close();  
                     } catch (IOException e) {  
                                         e.printStackTrace();  
                                    }  
                               }  
                          }  
           }  
           catch (ClientProtocolException e) {                 
           } catch (IOException e) {   
        }            
      }  
      cs.close();



Retreive Data from MySQL to SQLite

 String result = "";  
        //http get  
        try{  
              lastsync = URLEncoder.encode(lastsync,"utf-8");  
           String address = url + "/get.php?variable1="+variable1+"&variable2="+variable2;  
           Log.v("Sync", address);  
           HttpClient httpclient = new DefaultHttpClient();  
           HttpGet httpget = new HttpGet(address);  
           response = httpclient.execute(httpget);  
           HttpEntity entity = response.getEntity();  
           is = entity.getContent();  
        }catch(Exception e){  
            Log.e("log_tag", "Error in http connection "+e.toString());   
        }  
        //convert response to string  
        try{  
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);  
            StringBuilder sb = new StringBuilder();  
            String line = null;  
            while ((line = reader.readLine()) != null) {  
                 Log.v("Test",line);  
                sb.append(line + "\n");  
            }  
            is.close();  
            result=sb.toString();  
        }catch(Exception e){  
            Log.e("log_tag", "Error converting result "+e.toString());   
        }  
        set_tms_logsheet();         
        if(result.length()==5)  
        {  
        }  
        else {  
        //parse json data  
        try{  
            JSONArray jArray = new JSONArray(result);  
            for(int i=0;i<jArray.length();i++){  
                JSONObject json_data = jArray.getJSONObject(i);  
                String querylog= "insert or replace into table(a,b,c) values('"+json_data.getString("a")+"','"+json_data.getString("b")+"','"+json_data.getString("c")+"')";    
                dbA.insert(querylog);  
            }   
        }  
        catch(JSONException e){  
            Log.e("log_tag", "Error parsing data "+e.toString());   
        }  
        }  


get.php Code (Push Data to Phone from MySQL)

 <?php   
      require_once('Connections/connection.php');   
      mysql_select_db($database_localhost,$con);  
      $timestamp = $_GET['timestamp'];  
      $query_search = "select * from table where a = '".$timestamp."' ";  
      $query_exec = mysql_query($query_search) or die(mysql_error());  
      if (mysql_errno()) {   
   header("HTTP/1.1 500 Internal Server Error");  
   echo $query.'\n';  
   echo mysql_error();   
      }  
      else {  
      if( $query_exec!=null){  
      while($row=mysql_fetch_assoc($query_exec))  
     $output[]=$row;  
      print(json_encode($output));       
      }       
      else {echo "No Data"; }  
      mysql_close();  
 }  
 ?>  

set.php Code (Push Data to MySQL form SQLite)

 <?php  
      $json = file_get_contents('php://input');  
      $data = json_decode($json);  
      require_once('Connections/connection.php');   
      mysql_select_db($database_localhost,$con);  
      foreach ($data as $id => $jsons) {  
      $query= "insert into table(a,b,c) values(".$jsons->a.",".$jsons->b.",".$jsons->c.",'".$jsons->c."')";  
      //echo $query;  
      echo "\n";  
      $query_exec = mysql_query($query) or die(mysql_error());  
      }  
      mysql_close();  
      echo "Success";  
 ?>  


Connection.php (Database Connection)

 <?php  
 $hostname_localhost ="localhost:3306";  
 $database_localhost ="dbname";  
 $username_localhost ="username";  
 $password_localhost ="password";  
 $con = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)  
 or  
 trigger_error(mysql_error(),E_USER_ERROR);  
 ?>  

Wednesday, September 7, 2011

Google Weather API Widget (PHP) (No longer Working)




Note: Google has killed the free hidden weather API so this method no longer works

The Google Weather API is a hidden service for developers to get weather data for any location with ease.
Indeed, you just simply pass a city name or postal code, such as this Mountain View

Query by City
http://www.google.com/ig/api?weather=Mountain+View   

Query by Coordinates
http://www.google.com/ig/api?weather=,,,30670000,104019996 

To get an XML response like this:


This is the php code to get a widget like shown above. Line 20 defines the location for the widget.
Either you can use postal code, city or coordinates multiplied by 1000000 (Check Line No 21,22,23,25)

1:  <?php  
2:  function convert($temp)  
3:  {  
4:    // Converting Fahrenheit To Celsius, vice versa  
5:    global $config;  
6:    $temperature = $temp;  
7:    if( strtoupper($config['base-temp-unit']) == 'F' && strtoupper($config['display-temp-unit']) == 'C' )  
8:    {  
9:      // Converting Fahrenheit To Celsius  
10:      $temperature = round((5/9)*($temp-32));  
11:    }  
12:    if( strtoupper($config['base-temp-unit']) == 'C' && strtoupper($config['display-temp-unit']) == 'F' )  
13:    {  
14:      // Converting Celsius to Fahrenheit  
15:      $temperature = round((9/5)*$temp+32);  
16:    }  
17:    return $temperature;  
18:  }  
19:  $url = "http://www.google.com";  
20:  $location = "colombo"; // <city>,<country code>  
21:  $lat;  
22:  $lng;  
23:  //$location = ",,,30670000,104019996"; // Coordinates
24:  $weather_url = "{$url}/ig/api?weather={$location}";  
25:  //$weather_url = "{$url}/ig/api?weather=,,,{$lat},{$lng}";  
26:  $config['base-temp-unit'] = 'F'; // F=Fahrenheit, C=Celsius  
27:  $config['display-temp-unit'] = 'C'; // F=Fahrenheit, C=Celsius  
28:  if( $xmlData = file_get_contents($weather_url) )  
29:  {  
30:    $xml = new SimpleXMLElement($xmlData);  
31:    $eol = "\r\n";  
32:    // Display basic information  
33:       echo("<table width='70%' border='0' cellspacing='0' cellpadding='5'>");  
34:       echo("<tr>");  
35:       echo("<td width='11%' rowspan='4' align='center' valign='middle'>");  
36:       echo("<img src='{$url}{$xml->weather->current_conditions->icon->attributes()}' alt='' width='60' height='60' border='0' style='margin-right: 3px; vertical-align: top;>'");  
37:       echo("</td>");  
38:       echo("<td width='33%' align='left' valign='top'>{$xml->weather->current_conditions->temp_c->attributes()} C</td>");  
39:       echo("<td width='56%' rowspan='4' align='left' valign='top'><table width='100%' border='0' cellspacing='0' cellpadding='5' style='border-left:1px solid #CCCCCC'>");  
40:       echo("<tr>");  
41:       foreach( $xml->weather->forecast_conditions as $i => $result )  
42:    {  
43:       echo("<td align='center'>{$result->day_of_week->attributes()}</td>");  
44:       }  
45:       echo("</tr><tr>");  
46:       foreach( $xml->weather->forecast_conditions as $i => $result )  
47:    {  
48:       echo("<td align='center'><img src='{$url}{$result->icon->attributes()}'></td>");  
49:       }  
50:       echo("</tr><tr>");  
51:       foreach( $xml->weather->forecast_conditions as $i => $result )  
52:    {  
53:       echo("<td align='center'><table width='100%' border='0' cellspacing='0' cellpadding='5'><tr><td align='center'>".convert($result->high->attributes())." ".strtoupper($config['display-temp-unit'])."</td><td align='center'>".convert($result->low->attributes())." ".strtoupper($config['display-temp-unit'])."</td></tr></table></td>");  
54:       }  
55:       echo("</tr></table></td></tr><tr>");  
56:       echo("<td>{$xml->weather->current_conditions->condition->attributes()}</td>");  
57:       echo("</tr><tr>");  
58:       echo("<td>{$xml->weather->current_conditions->wind_condition->attributes()}</td>");  
59:       echo("</tr><tr>");  
60:       echo("<td>{$xml->weather->current_conditions->humidity->attributes()}</td>");  
61:       echo("</tr></table>");  
62:  }  
63:  ?>  

Thursday, July 14, 2011

Android MySQL Connectivity (MySQL Connector)



Hope this method works. However its not recommended to use JDBC Connectivity for connections over wifi or 3g. So the best way to connect MySQL from android is to use JSON or XML Parsings

Step 1 Including MySQL Connector
Add this jar to the classpath. In Eclipse Right Click in the Project>BuildPath>Configure Build Path. Then a window should popup, click the libraries tab at the top, click add external jar and navigate to File System/usr/share/java/mysql-connector-java.jar

Step 2 Coding Part

JDBC, simply allows you to connect to your server from java.

1:  import java.sql.Connection;  
2:  import java.sql.DriverManager;  
3:  import java.sql.ResultSet;  
4:  import java.sql.Statement;  
5:  public class DB {  
6:  private static final String url = “jdbc:mysql://localhost/android”;  
7:  private static final String user = “root”;  
8:  private static final String password = “MySql Password”;  
9:  public static void main(String args[]) {  
10:  try {  
11:  Class.forName(“com.mysql.jdbc.Driver”);  
12:  Connection con = DriverManager.getConnection(url, user, password);  
13:  Statement st = con.createStatement();  
14:  ResultSet rs = st.executeQuery(“select * from User”);  
15:  while(rs.next()) {  
16:  Log.v("DB", rs.getString(2) )  
17:  }  
18:  } catch (Exception e) {  
19:  }  
20:  }  
21:  }  

Wednesday, July 13, 2011

Download Android New Market V3.0.26 (Movies,Books, Multiple Account Support

The new Android Market has started rolling out to some user. If you haven't received it. Download here and install it using File managers

Please note that movies cannot be played on rooted devices, just as before.


Tuesday, June 28, 2011

Guide: Amazon Appstore for Non US users



Amazon few months ago launched its own web and mobile version of the own Android Marketplace called as the "Amazon Appstore".


The Amazon Android App Store gives away a paid application free for a day.But unfortunately it's limited to US customers only for the time being.

Modaco.com site admin Paul found a way to trick Amazon to get the Amazon Appstore.
All credits goes to him.

Step 1 - Create a Amazon account

First you need to create an Amazon.com account. Even if you have an amazon account its better to create a new one. Visit the Amazon.com sign in page and select 'No, I am a new customer'.

Step 2 - Setting up your billing address

Next you need to set up a US address, you do this on the Manage Address Book page. This MUST be a valid US address.

I used Google's HQ Address which is
'1600 Amphitheatre Parkway Mountain View, CA 94043'

Step 3 - Setting up your phone number

Since I have a Google Voice account. I used that number. You could type any number starting with +1. Easier than that.

Step 4 - Setting up your payment card

Use a test card number from one of the credit card providers, I used one of the PayPal test CC number

Step 5 - Install the AppStore on your device

After successfully creating the Amazon account. Amazon will mail you with the link to download the apk. Install the apk and Enjoy the free app a day

If anything goes wrong

  • Visit the Digital Orders Page page and you will see your pending purchases
  • Choose the option to retry the purchases, this time using your non-US card
  • The payments will complete and you will be able to download the apps on your device

Thursday, June 9, 2011

Guide on Getting Google Music outside United States


This is how i got my Google Music Beta Invitation. Took me less than and 5 minutes to configure it.Before everything you need an Android phone( Requires a rooted phone) to do this,. and all thank goes to Paul O Brian for the great guide he provided.



Step 1 - Requesting for an invitation
Go to http://music.google.com/about/ via a US proxy and request for an initation. I used http://www.hidemyass.com/

Step 2 - Get the New Google Music Android App 3.0.1

Check market for the New Google Music Beta App. If its not there, Use Market Enabler to fake the provide to some US provider(probably T- Mobile US) and recheck the market. Also you can manually download the apk and install It.

Step 3 - Last and the Hardest Part

You have to edit your phones build properties to get it quickly. Click Here
Copy the system/build.prop file to your computer and edit the build prop to match the one above in the link. Make sure to take a backup of your build.prob before editing. I used Root Explorer to replace the file. And Restart the phone, and keep in online (connected with the internet for 1 hour). Also go to the Downloaded Music Beta App, Visit Market app etc to make Google think that you are using a Motorola Xoom (Google exclusively rolls out invitation for Motorola Xoom Users). Thats It, after about one hour replace you build.prop with the original one.

Viola Thats It. Wait for the invitation. I got mine in one hour.