Lab10 Android Networking AsyncTask

In this lab, we make use of the folowing methods: 


Networking AsyncTask 
        private class NetworkTask extends AsyncTask<String, Void, String>{

addTextChangedListener
        etAmount.addTextChangedListener(new TextWatcher()..........

setOnItemSelectedListener
         sp.setOnItemSelectedListener(new OnItemSelectedListener()..............

GUI- tabs 
  TabHost tabs =(TabHost) this.findViewById(R.id.CCtabhost);
  tabs.setup();
           
  TabSpec ts1 = tabs.newTabSpec("FC to SGD");
  ts1.setIndicator("Convert to SGD");
  ts1.setContent(R.id.content1);
  tabs.addTab(ts1);
           
  TabSpec ts2 = tabs.newTabSpec("Get from server");
  ts2.setIndicator("Rates from server");
  ts2.setContent(R.id.content2);
  tabs.addTab(ts2);

Get Current Time
String currentTime24 = getCurrentTime();

and a method

String getCurrentTime()
{
 String currentTime24="", currentDate="";
 
 try {
        String now = new SimpleDateFormat("hh:mm aa").format(new java.util.Date().getTime());
        currentTime24 = new SimpleDateFormat("HHmm").format(new SimpleDateFormat("hh:mm aa").parse(now));
        System.out.println("time in 24 hour format : " + currentTime24);
        
     SimpleDateFormat sdf = new SimpleDateFormat("dMMMyyyy" );
     currentDate  = sdf.format(new java.util.Date());
     
     System.out.println("time in 24 hour format : "+currentDate +" "+ currentTime24);
     
     return currentDate +" "+ currentTime24;
    } catch (Exception e) {
        System.out.println("Exception : " + e.getMessage());
    }
 return currentDate +" "+ currentTime24;
 
}




LAB 10: Mobile Device Application 

Objective: Mobile Device App with Networking and Persistent Data Storage


1. Create an Android project, CurrencyConverter, in Eclipse, package name as mdad.lab10 and activity name as MainActivity. 

2. Replace the contents of the activity_main.xml with the contents of the given activity _ main.xml file. 


3. Drag and drop the arrays.xml file (from OLIVE) into the res/values folder of the project 

4. Replace the contents of MainActivity.java with the contents of MainActivity.txt (from OLIVE). 


5. In the AndroidManifest.xml file, add the uses-permission tag to allow for internet access. 



6. Create a new Tomcat Project called MyServer in c:\webapps\MDAD without closing the current Android Project. 

7. Replace the contents of the web.xml file in the WEB-INF folder with the file given in OLIVE. 

8. Create 2 servlets, ReadServlet.java and WriteServlet.java (package name is lab10) in the Tomcat project. Replace their contents with files, ReadServlet.txt and WriteServlet.txt, downloaded from OLIVE. 





9. Switch from Java perspective to Database Development perspective, create/use a MySQL connection to allow access to MySQL database. 

10. Use the given lab10.sql file to create the table, xchg_rates.  

SQL


drop table if exists xchg_rates;
create table xchg_rates (usd varchar(8), euro varchar(8), rmb varchar(8));
insert into xchg_rates values('1.24', '1.62', '0.20');

drop table if exists userRecords;
create table userRecords (currentDateTime varchar(20), currency varchar(8), amountEntered varchar(100), convertedAmt varchar(100) );













11. Start Tomcat. Switch back to Java perspective and launch the Android App CurrencyConverter in the AVD and test the application. 

You should see the following:



































































Part 2: Read values from User and Insert into the table userRecords 

To write the SQL insert statement into the WriteServlet to enable data to be inserted into the MySql DB Expected Output 

































AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="mdad.lab10"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="18"
        android:targetSdkVersion="21" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="mdad.lab10.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


activity_main.xml


<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/CCtabhost" android:layout_width="match_parent"
 android:layout_height="match_parent">
 <TabWidget android:id="@android:id/tabs"
  android:layout_width="match_parent" android:layout_height="60dp" />
 <FrameLayout android:id="@android:id/tabcontent"
  android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingTop="60dp">

  <LinearLayout
      android:id="@+id/content1"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:orientation="vertical" >

      <EditText
          android:id="@+id/etAmount"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:ems="8"
          android:inputType="numberDecimal"
          android:text="1.00" >

          <requestFocus />
      </EditText>

      <Spinner
          android:id="@+id/spinnerCurrency"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:entries="@array/currency" />

      <TextView
          android:id="@+id/tvConvertedAmt"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text=" " />

      <TextView
          android:id="@+id/tvFromServer"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text=" " />

      <Button
          android:id="@+id/btnSendToServer"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="Send to Server" />

  </LinearLayout>

  <LinearLayout android:id="@+id/content2"
   android:orientation="vertical" android:layout_width="match_parent"
   android:layout_height="match_parent">
   
   <Button
       android:id="@+id/btnShowRates"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Show Rates" >
</Button>

<TextView
    android:id="@+id/tvDisplay"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >
</TextView>
</LinearLayout>
 </FrameLayout>
</TabHost>

MainActivity
package mdad.lab10;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import android.widget.Toast;
  
public class MainActivity extends Activity {
EditText etAmount;
TextView tvFromServer, tv2, tvConvertedAmt;
Button btnShowRates, btnSendToServer;
Spinner sp;
String[] currencies;
 
int  currencySelectedIndex=0;
String currentTime24 ="";
static boolean toggleColor=false;

float usd=1.2f, euro=1.6f, rmb=0.19f; //initial values

String getCurrentTime()
{
 String currentTime24="", currentDate="";
 
 try {
        String now = new SimpleDateFormat("hh:mm aa").format(new java.util.Date().getTime());
        currentTime24 = new SimpleDateFormat("HHmm").format(new SimpleDateFormat("hh:mm aa").parse(now));
        System.out.println("time in 24 hour format : " + currentTime24);
        
     SimpleDateFormat sdf = new SimpleDateFormat("dMMMyyyy" );
     currentDate  = sdf.format(new java.util.Date());
     
     System.out.println("time in 24 hour format : "+currentDate +" "+ currentTime24);
     
     return currentDate +" "+ currentTime24;
    } catch (Exception e) {
        System.out.println("Exception : " + e.getMessage());
    }
 return currentDate +" "+ currentTime24;
 
}


String calConversion(int index)
{
 
 double sgd=0;
 
 String amt =etAmount.getText().toString();
 double fc = 0;
 
 if (amt.equals("")) fc=0; else fc=Double.parseDouble(amt);
 if(index==0)
  sgd=fc*usd; //usd to sgd    
 else if(index==1)
  sgd=fc*euro; //euro to sgd
 else 
  sgd=fc*rmb;  //rmb to sgd
 String s=String.format("%.2f",sgd);
 
 return s;
 
}


 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);


  TabHost tabs =(TabHost) this.findViewById(R.id.CCtabhost);
  tabs.setup();
           
  TabSpec ts1 = tabs.newTabSpec("FC to SGD");
  ts1.setIndicator("Convert to SGD");
  ts1.setContent(R.id.content1);
  tabs.addTab(ts1);
           
  TabSpec ts2 = tabs.newTabSpec("Get from server");
  ts2.setIndicator("Rates from server");
  ts2.setContent(R.id.content2);
  tabs.addTab(ts2);
  
  etAmount = (EditText)findViewById(R.id.etAmount);
  sp = (Spinner)findViewById(R.id.spinnerCurrency);
  
  currencies=getResources().getStringArray(R.array.currency);
   
  
  btnShowRates = (Button)findViewById(R.id.btnShowRates);
  btnSendToServer = (Button)findViewById(R.id.btnSendToServer);
  tvFromServer = (TextView)findViewById(R.id.tvFromServer);
  tvConvertedAmt = (TextView)findViewById(R.id.tvConvertedAmt);
  
  
  tv2 = (TextView)findViewById(R.id.tvDisplay);
  
        btnShowRates.setOnClickListener(new OnClickListener(){
   public void onClick(View v) {
    new NetworkTask().execute("http://10.0.2.2:8080/MDAD/read/lab10.ReadServlet");

   }
         
        });
  
        btnSendToServer.setOnClickListener(new OnClickListener(){
   public void onClick(View v) {
    
   btnSendToServer.setEnabled(false);
   new NetworkTask2().execute("http://10.0.2.2:8080/MDAD/write/lab10.WriteServlet");

   }
         
        });
        
   
        
        etAmount.addTextChangedListener(new TextWatcher() {

   @Override
   public void afterTextChanged(Editable s) {
    // TODO Auto-generated method stub
    
   }

   @Override
   public void beforeTextChanged(CharSequence s, int start, int count,
     int after) {
    // TODO Auto-generated method stub
    
   }

   @Override
   public void onTextChanged(CharSequence s, int start, int before,
     int count) {
    // TODO Auto-generated method stub
    String convertValues =calConversion(currencySelectedIndex);
    tvConvertedAmt.setText("SGD "+convertValues);
    btnSendToServer.setEnabled(true);
    
   }
  
  
          });
        
        
        
        
        
  sp.setOnItemSelectedListener(new OnItemSelectedListener(){
   public void onItemSelected(AdapterView<?> arg0, View arg1,
     int arg2, long arg3) {
     double sgd=0;
    double fc = Double.parseDouble(etAmount.getText().toString());
    int index= sp.getSelectedItemPosition();
     
    currencySelectedIndex = index;
    System.out.println("The currency  is "+ currencies[currencySelectedIndex]);
    btnSendToServer.setEnabled(true);
    
     
    String convertValues =calConversion(currencySelectedIndex);
    tvConvertedAmt.setText("SGD "+convertValues);
   }

   public void onNothingSelected(AdapterView<?> arg0) { 
   }
   
  });
 
 }//end onCreate

//AsyncTask to read from servlet the rates
 private class NetworkTask extends AsyncTask<String, Void, String>{
 
   String[] s = new String[3];
  protected String doInBackground(String... params) {
   String address=params[0];
   try{
   URL url = new URL(address);
       HttpURLConnection con = (HttpURLConnection)url.openConnection();
       con.setRequestMethod("POST");
  
         BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
   String line;
   int i=0;
   while((line=br.readLine())!=null)   //Read 3 values from Server
   {
      s[i]=line;
      i++; 
       }
   
   float f1= Float.parseFloat(s[0]);
   float f2= Float.parseFloat(s[1]);
   float f3= Float.parseFloat(s[2]);
   
   SharedPreferences myPrefs = getSharedPreferences("rates",0);
   SharedPreferences.Editor myEditor = myPrefs.edit();
   myEditor.putFloat("usd", f1);
   myEditor.putFloat("euro",f2);
   myEditor.putFloat("rmb", f3);
   myEditor.commit();
   
   usd = myPrefs.getFloat("usd", 0);
   euro = myPrefs.getFloat("euro",0);
   rmb = myPrefs.getFloat("rmb",0);
   }
  catch(IOException e){Log.e("error", "error in reading", e); }
     return "USD:"+s[0]+"\nEURO:"+s[1]+"\nRMB:"+s[2];
 }
  protected void onPostExecute(String result) {
         tv2.setText(result);
    }
 }
 public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }
//AsyncTask to write to servlet the converted value
 private class NetworkTask2 extends AsyncTask<String, Void, String>{
  String line="";
  protected String doInBackground(String... params) {
   String address=params[0];
   try{
   URL url = new URL(address);
       HttpURLConnection con = (HttpURLConnection)url.openConnection();
       con.setRequestMethod("POST");
       OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
       currentTime24 = getCurrentTime();
       
       //Send to Server
       out.write(currentTime24+"\n");//get current time
       out.write(currencies[currencySelectedIndex]+"\n");//get selected currency
       out.write(etAmount.getText().toString()+"\n");//get amount value
       out.write(tvConvertedAmt.getText().toString()+"\n");//get converted value
       out.flush();
       out.close();
       
       BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
   line=br.readLine();// read back response from server
   }
   catch(IOException e){Log.e("error", "error in reading", e); }
  
   return line; 
  }
  protected void onPostExecute(String result) {
   
   toggleColor = !toggleColor;
   
   if (toggleColor) 
   { 
    tvFromServer.setTextColor(Color.BLUE);
   }
   else
   {
    tvFromServer.setTextColor(Color.RED);
   }
   
   tvFromServer.setText(result);
   }
    
 }
}


 MyServer

SQL

drop table if exists xchg_rates;
create table xchg_rates (usd varchar(8), euro varchar(8), rmb varchar(8));
insert into xchg_rates values('1.24', '1.62', '0.20');

drop table if exists userRecords;
create table userRecords (currentDateTime varchar(20), currency varchar(8), amountEntered varchar(100), convertedAmt varchar(100) );

Web.xml  (mapping)

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

  <display-name>My Web Application</display-name>
  <description>
     My Servlet definition
  </description>

<servlet>
<servlet-name>ReadServlet</servlet-name>
<servlet-class>lab10.ReadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ReadServlet</servlet-name>
<url-pattern>/read/*</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>WriteServlet</servlet-name>
<servlet-class>lab10.WriteServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>WriteServlet</servlet-name>
<url-pattern>/write/*</url-pattern>
</servlet-mapping>
</web-app>

WriteServlet.java
package lab10;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class WriteServlet extends HttpServlet {
 
 String currentTime ="";
 String currencySelected ="";
 String amount="";
 String comvertedAmt ="";
 String data [] = new String[4];
   
 

 private static final String db_server = "localhost:3306/";
   private static final String db_name = "test";
   private Connection con = null;
   
 public void init(ServletConfig config) throws ServletException
   {
     try {
       Class.forName("com.mysql.jdbc.Driver").newInstance();
     }
     catch (Exception e) { System.out.println(e.toString());    }

     try {
       con = DriverManager.getConnection("jdbc:mysql://"+ db_server + db_name , "root", "" );
     }
     catch (Exception e) { System.out.println(e.toString());    }
   } // End init()
 
 public void doPost(HttpServletRequest req, HttpServletResponse resp) 
   throws ServletException, IOException {
 BufferedReader reader = new BufferedReader( new InputStreamReader(req.getInputStream() ) );  
        String res;  int i=0;
        while((res = reader.readLine())!= null)  //read from mobile device
         {  
            data[i++] = res;
            System.out.println(res);
         }


     int status =0;

     //#Part 2: Write to MySQL database table userRecords
     try{
 
      Statement stmt;
      stmt = con.createStatement();

          //#Part 2: SQL insert statement
String sql="____________________________________________________________________"; System.out.println(sql); status = stmt.executeUpdate(sql); System.out.println("Status is "+status); } catch (Exception e) { System.out.println(e.toString()); } //#Part 2: Write to MySQL database table userRecords PrintWriter out= resp.getWriter(); if (status> 0) out.println(" server received"); else out.println(" Error in updating data to DB"); }//end doPost }


ReadServlet.java
package lab10;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ReadServlet extends HttpServlet {
 private static final String db_server = "localhost:3306/";
   private static final String db_name = "test";
   private Connection con = null;

   public void init(ServletConfig config) throws ServletException
   {
     try {
       Class.forName("com.mysql.jdbc.Driver").newInstance();
     }
     catch (Exception e) { System.out.println(e.toString());    }

     try {
       con = DriverManager.getConnection("jdbc:mysql://"+ db_server + db_name , "root", "" );
     }
     catch (Exception e) { System.out.println(e.toString());    }
   } // End init()
   
 public void doPost(HttpServletRequest req, HttpServletResponse resp) 
   throws ServletException, IOException {
  Statement stmt;
    ResultSet rs=null;
       String r_usd="1", r_euro="1", r_rmb="1";
     try {
       stmt = con.createStatement();
       rs = stmt.executeQuery("SELECT * FROM xchg_rates");
       while(rs.next()){
       r_usd=rs.getString(1);
       r_euro=rs.getString(2);
       r_rmb=rs.getString(3);
       }
     }
     catch (Exception e) { System.out.println(e.toString());    }
     try {       rs.close();     }    catch (SQLException e) {   System.out.println(e.toString());   }
     
  PrintWriter out = resp.getWriter();
  out.println(r_usd); //Send to Mobile Device Client 
  out.println(r_euro); //Send to Mobile Device Client
  out.println(r_rmb); //Send to Mobile Device Client
 }
}










String sql="insert into userRecords values ('"+data[0]+"','"+data[1]+"','"+data[2]+"','"+data[3]+"')";