Android app connects to live website database

Problems with WiFi, SQLite ,Bluetooth, WiMax, Proxies, etc...

Android app connects to live website database

Postby hightech » Sat Dec 05, 2009 3:44 am

Hi,

I'm new to develop an Android application to connect to a database on my website.

Which languages that would be the best to develop in database on my live website for Android application? And what languages that I should build a website that would be easy for Android app to POST data into that website database?

I need to know how to build Android app to connect database on my live website but I don't want to have localhost database. Does anybody know of a link to an example/tutorial or you could provide an exmaple in which this kind of operation is performed? I would be happy to know about it.

Thanks!
hightech
Freshman
Freshman
 
Posts: 5
Joined: Sat Dec 05, 2009 2:52 am

Top

Postby dinneratmyplace » Fri Dec 11, 2009 12:07 am

I don't know if this will work for you, but I use a combination MySqL, PHP, XML for the website / database, and then on android I use SAXParser and AsyncTasks to manage everything.

There is a great tutorial on SAXParser in the tutorial section but I'll post some code to explain what I'm doing.

First set up Android, we're going to set up a SAXParser (XMLHandler) to read the XML, and a parsedDataSet to hold on to the read and parsed data.

Then we are going to set up an AsyncTask to send the request to your website.

Lastly we'll set up the website to recieve a request and respond with an xml document.

(this is going to be quick and dirty but it will give you an outline)

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2.  
  3.  
  4.  
  5.  
  6. import org.xml.sax.Attributes;
  7.  
  8. import org.xml.sax.SAXException;
  9.  
  10. import org.xml.sax.helpers.DefaultHandler;
  11.  
  12.  
  13.  
  14.  
  15.  
  16. public class XMLHandler extends DefaultHandler{
  17.  
  18.  
  19.  
  20.      // ===========================================================
  21.  
  22.      // Fields
  23.  
  24.      // ===========================================================
  25.  
  26.      
  27.  
  28.      private boolean in_test = false;
  29.  
  30.      
  31.  
  32.      
  33.  
  34.      private ParsedDataSet myParsedDataSet = new ParsedDataSet();
  35.  
  36.  
  37.  
  38.      // ===========================================================
  39.  
  40.      // Getter & Setter
  41.  
  42.      // ===========================================================
  43.  
  44.  
  45.  
  46.      public ParsedDataSet getParsedData() {
  47.  
  48.           return this.myParsedDataSet;
  49.  
  50.      }
  51.  
  52.  
  53.  
  54.      // ===========================================================
  55.  
  56.      // Methods
  57.  
  58.      // ===========================================================
  59.  
  60.      @Override
  61.  
  62.      public void startDocument() throws SAXException {
  63.  
  64.           this.myParsedDataSet = new ParsedDataSet();
  65.  
  66.      }
  67.  
  68.  
  69.  
  70.      @Override
  71.  
  72.      public void endDocument() throws SAXException {
  73.  
  74.           // Nothing to do
  75.  
  76.      }
  77.  
  78.  
  79.  
  80.      /** Gets be called on opening tags like:
  81.  
  82.       * <tag>
  83.  
  84.       * Can provide attribute(s), when xml was like:
  85.  
  86.       * <tag attribute="attributeValue">*/
  87.  
  88.      @Override
  89.  
  90.      public void startElement(String namespaceURI, String localName,
  91.  
  92.                String qName, Attributes atts) throws SAXException {
  93.  
  94.            if (localName.equals("test")) {
  95.  
  96.                this.in_test= true;
  97.  
  98.           }
  99.  
  100.      }
  101.  
  102.      
  103.  
  104.      /** Gets be called on closing tags like:
  105.  
  106.       * </tag> */
  107.  
  108.      @Override
  109.  
  110.      public void endElement(String namespaceURI, String localName, String qName)
  111.  
  112.                throws SAXException {
  113.  
  114.           if (localName.equals("test")) {
  115.  
  116.                this.in_test= false;
  117.  
  118.           }
  119.  
  120.      }
  121.  
  122.      
  123.  
  124.      /** Gets be called on the following structure:
  125.  
  126.       * <tag>characters</tag> */
  127.  
  128.      @Override
  129.  
  130.     public void characters(char ch[], int start, int length) {
  131.  
  132.           if(this.in_test){
  133.  
  134.                   myParsedDataSet.addExtractedTest(new String(ch, start, length));
  135.  
  136.           }
  137.  
  138.     }
  139.  
  140. }
  141.  
  142.  
Parsed in 0.037 seconds, using GeSHi 1.0.8.4


then set up your parsed data set

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2.  
  3.  
  4. import java.util.ArrayList;
  5.  
  6. import java.util.List;
  7.  
  8.  
  9.  
  10. public class ParsedDataSet {
  11.  
  12.     private List<String> tests = new ArrayList<String>();
  13.  
  14.  
  15.  
  16.     public void addExtractedTest(String test){
  17.  
  18.                 this.tests.add(test);
  19.  
  20.         }
  21.  
  22. }
  23.  
  24.  
Parsed in 0.032 seconds, using GeSHi 1.0.8.4


now you need to set up an asyncTask to fetch data from your website: (this will be a subclass in whatever activity is going to be retrieving data)


TO BE CONTINUED.... !!!! (sorry duty calls)
dinneratmyplace
Freshman
Freshman
 
Posts: 5
Joined: Thu Dec 10, 2009 6:53 pm

Postby dinneratmyplace » Fri Dec 11, 2009 12:28 am

...Part 2

Ok, now you need to set up some facility to request data from your server, we're going to subclass asyncTask. In this case we will try to download 3 times just to make sure nothing times out / gets bad data

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. private class DownloadStuff extends AsyncTask<Void, Void, Boolean> {
  3.  
  4.             protected Boolean doInBackground(Void... params) {
  5.  
  6.                 int i = 0;
  7.  
  8.                 boolean success = false;
  9.  
  10.                 while(!success && i < 3){
  11.  
  12.                         success = downloadAttempt();
  13.  
  14.                         i++;
  15.  
  16.                 }
  17.  
  18.                 return success;
  19.  
  20.             }
  21.  
  22.             protected void onPreExecute(){
  23.  
  24.                 //Show progress dialog if you'd like...
  25.  
  26.             }
  27.  
  28.             protected void onPostExecute(Boolean success) {
  29.  
  30.                 //remove progress dialog if you set one up...
  31.  
  32.                 if(success){
  33.  
  34.                         Message m = new Message();
  35.  
  36.                         m.what = DOWNLOAD_ID;
  37.  
  38.                         messageHandler.sendMessage(m);
  39.  
  40.                 }
  41.  
  42.                 else{
  43.  
  44.                        Message m = new Message();
  45.  
  46.                        m.what = ERRORIDENTIFIER;
  47.  
  48.                        messageHandler.sendMessage(m);
  49.  
  50.                 }
  51.  
  52.              }
  53.  
  54.             private boolean downloadAttempt(){
  55.  
  56.                 try{
  57.  
  58.                   StringBuilder tempURL = new StringBuilder();
  59.  
  60.                   tempURL.append("http://www.yourserver.com/android/process.php?android=gimmesomedata");
  61.  
  62.                   URL url = new URL(tempURL.toString());
  63.  
  64.                       SAXParserFactory spf = SAXParserFactory.newInstance();
  65.  
  66.                       SAXParser sp = spf.newSAXParser();
  67.  
  68.                       XMLReader xr = sp.getXMLReader();
  69.  
  70.                       XMLHandler myHandler = new XMLHandler();
  71.  
  72.                       xr.setContentHandler(myHandler);
  73.  
  74.                       URLConnection con = url.openConnection();
  75.  
  76.                           con.setConnectTimeout(4000);
  77.  
  78.                           con.setReadTimeout(4000);
  79.  
  80.                           xr.parse(new InputSource(con.getInputStream()));
  81.  
  82.                           ParsedDataSet parsedDataSet = myHandler.getParsedData();
  83.  
  84.                           //here might be a good place to do something with your data
  85.  
  86.                           return true;
  87.  
  88.             }catch(Exception e) {
  89.  
  90.                 return false;
  91.  
  92.             }
  93.  
  94.             }
  95.  
  96.         };
  97.  
  98.  
Parsed in 0.041 seconds, using GeSHi 1.0.8.4


now the task is going to fire off a message we need to catch it and do something with it. This is also going to be a subclass


Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. private Handler messageHandler = new Handler() {
  3.  
  4.               @Override
  5.  
  6.               public void handleMessage(Message msg) {  
  7.  
  8.                   switch(msg.what) {
  9.  
  10.                   case(DOWNLOAD_ID):
  11.  
  12.                   //download was successful, you could do something with your data now
  13.  
  14.                       break;
  15.  
  16.                   case (ERRORIDENTIFIER):
  17.  
  18.                           //download was unsuccessful... hella sad face
  19.  
  20.                           break;
  21.  
  22.                   }
  23.  
  24.               }
  25.  
  26.           };
  27.  
  28.  
  29.  
  30.  
Parsed in 0.037 seconds, using GeSHi 1.0.8.4


TO BE CONTINUED.... (AGAIN)
dinneratmyplace
Freshman
Freshman
 
Posts: 5
Joined: Thu Dec 10, 2009 6:53 pm

Postby dinneratmyplace » Fri Dec 11, 2009 12:40 am

Ok, and the last step is to setup your web server so that it can handle the request and respond to it. So on your webserver your process.php might look something like this:

Code: Select all
<?
require_once('include/database.php');

class Process
{
   function Process(){
     if(isset($_GET['android'])){
         global $database;
       $status = $_GET["android"];
       $xml .="<root>";
      
      
      if ($status == "gimmesomedata"){
         $data = $database->getSomeData();
         $xml .= "<count>" . $data. "</count>";
      }

                $xml .="</root>";
      header('Content-type: text/xml');
      echo $xml;
     }
   }
};

/* Initialize process */
$process = new Process;

?>



and your database.php file should look something like this:

Code: Select all

<?
include("constants.php");
     
class MySQLDB
{
   var $connection;         //The MySQL database connection

   /* Class constructor */
   function MySQLDB(){
      /* Make connection to database */
      $this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS) or die(mysql_error());
      mysql_select_db(DB_NAME, $this->connection) or die(mysql_error());

   }
   function getSomeData(){
   /*retrieve some data from your database and send it back*/
   $query="select data from table where field = 'blah'";
         $result=mysql_query($query, $this->connection) or die($query);
         if(mysql_num_rows($result) > 0){
            $data = true;
         }
         else{
            $data = false
         }

   }

};

/* Create database connection */
$database = new MySQLDB;


?>



whew... that was a lot and it was probably pretty confusing... If anyone would like I can write a much more detailed tutorial. And as always there are many different ways to solve every problem and this might not be the best approach....
dinneratmyplace
Freshman
Freshman
 
Posts: 5
Joined: Thu Dec 10, 2009 6:53 pm

Top

Return to Networking & Database Problems

Who is online

Users browsing this forum: Exabot [Bot] and 8 guests