Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
swdev:android:database_mysql [2018/05/02 15:08]
smayr [References]
swdev:android:database_mysql [2018/05/02 17:22] (current)
smayr
Line 1: Line 1:
 = Database: MySQL = = Database: MySQL =
 +== Using RESTful API ==
 +
 +== Using Java Connector (no API) ==
 ==== DB Connector ==== ==== DB Connector ====
 Download the appropriate Java database connector: Download the appropriate Java database connector:
Line 29: Line 32:
  
 ==== Manifest ==== ==== Manifest ====
-Add permission to access the Internet.  Go to ''app'' > ''manifests'' > ''AndroidManifest.xml'':+Add permission to access the Internet and Network State.  Go to ''app'' > ''manifests'' > ''AndroidManifest.xml'':
 <code xml> <code xml>
 <manifest...> <manifest...>
     <uses-permission android:name="android.permission.INTERNET"/>     <uses-permission android:name="android.permission.INTERNET"/>
 +    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
          
     <application...>     <application...>
Line 47: Line 51:
 public class DbStrings public class DbStrings
 { {
-  static final String DATABASE_URL  = "192.168.0.1:3306"; +    static final String DATABASE_URL  = "192.168.0.1:3306"; 
-  static final String DATABASE_NAME = "mydatabase"; +    static final String DATABASE_NAME = "mydatabase"; 
-  static final String USERNAME      = "dbuser"; +    static final String USERNAME      = "dbuser"; 
-  static final String PASSWORD      = "dbsecret";+    static final String PASSWORD      = "dbsecret";
 } }
 </code> </code>
Line 83: Line 87:
         map = m;         map = m;
         products = new ArrayList<String>(map.keySet());         products = new ArrayList<String>(map.keySet());
-        prices   = new ArrayList<Double>(map.keySet());+        prices   = new ArrayList<Double>(map.values());
                  
         mInflater = (LayoutInflater) cx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);         mInflater = (LayoutInflater) cx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Line 141: Line 145:
     ListView lstProducts;     ListView lstProducts;
     TextView lblProgress;     TextView lblProgress;
-    Map<String, Double> mapProducts = new LinkedHashMap<String, Double>();+    Map<String,Double> mapProducts = new LinkedHashMap<String,Double>();
    
     @Override     @Override
Line 175: Line 179:
              
       // Example: 192.168.0.2:3306       // Example: 192.168.0.2:3306
-      static final String DB_URL = "jdbc:mysql://"++      static final String DB_URL = "jdbc:mysql://" +
           DbStrings.DATABASE_URL + "/" +           DbStrings.DATABASE_URL + "/" +
           DbStrings.DATABASE_NAME;           DbStrings.DATABASE_NAME;
Line 194: Line 198:
                Class.forName(JDBC_DRIVER);                Class.forName(JDBC_DRIVER);
                conn = DriverManager.getConnection(DB_URL, DbStrings.USERNAME, DbStrings.PASSWORD);                conn = DriverManager.getConnection(DB_URL, DbStrings.USERNAME, DbStrings.PASSWORD);
-               stmt = conn.createStatement(); +                
-               String sql = "SELECT * FROM products";+               stmt         = conn.createStatement(); 
 +               String sql   = "SELECT * FROM products";
                ResultSet rs = stmt.executeQuery(sql);                ResultSet rs = stmt.executeQuery(sql);
 +               
                while(rs.next()) {                while(rs.next()) {
-                   String name = rs.getString("name");+                   String name  = rs.getString("name");
                    double price = rs.getDouble("price");                    double price = rs.getDouble("price");
                                        
Line 211: Line 217:
                                
            } catch (SQLException connError) {            } catch (SQLException connError) {
-              msg = "Exception was thrown for JDBC."; +               msg = "Exception was thrown for JDBC."; 
-              connError.printStackTrace();+               connError.printStackTrace();
            } catch (ClassNotFoundException ex) {            } catch (ClassNotFoundException ex) {
-              msg = "A 'Class not Found' exception was thrown."; +               msg = "A 'Class not Found' exception was thrown."; 
-              ex.printStackTrace();+               ex.printStackTrace();
            } finally {            } finally {
                try {                try {
                    if (stmt != null) { stmt.close(); }                    if (stmt != null) { stmt.close(); }
                } catch (SQLException ex) {                } catch (SQLException ex) {
-                   stmt.close();+                   ex.printStackTrace();
                }                }
                try {                try {
                    if (conn != null) { conn.close(); }                    if (conn != null) { conn.close(); }
                } catch (SQLException ex) {                } catch (SQLException ex) {
-                   conn.close();+                   ex.printStackTrace();
                }                }
            }            }
Line 233: Line 239:
        @Override        @Override
        protected void onPostExecute(String msg) {        protected void onPostExecute(String msg) {
 +
            lblProgress.setText(this.msg);            lblProgress.setText(this.msg);
 +           
            if (mapProducts.size() > 0) {            if (mapProducts.size() > 0) {
                itemAdapter = new ItemAdapter(thisContext, mapProducts);                itemAdapter = new ItemAdapter(thisContext, mapProducts);
-               lstProducts.setAdapter(itemAdapter());+               lstProducts.setAdapter(itemAdapter);
            }            }
        }        }
Line 242: Line 250:
 } }
 </code> </code>
 +
 +=== Example Quick Connection ===
 +''activity_main.xml'':
 +<code xml>
 +<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 +    xmlns:tools="http://schemas.android.com/tools"
 +    android:layout_width="match_parent"
 +    android:layout_height="match_parent"
 +    tools:context=".MainActivity" >
 +
 +    <TextView
 +        android:id="@+id/textView0"
 +        android:layout_width="wrap_content"
 +        android:layout_height="wrap_content"
 +        android:layout_centerHorizontal="true"
 +        android:layout_centerVertical="true"
 +        android:text="@string/hello_world" />
 +
 +</RelativeLayout>
 +</code>
 +
 +''MainActivity.java'':
 +<code java>
 +package com.example.andmysql;
 +
 +import java.sql.Connection;
 +import java.sql.DriverManager;
 +import java.sql.PreparedStatement;
 +import java.sql.ResultSet;
 +import java.sql.SQLException;
 +
 +
 +import android.os.Bundle;
 +import android.os.Handler;
 +import android.os.Message;
 +import android.app.Activity;
 +import android.widget.TextView;
 +
 +public class MainActivity extends Activity implements Runnable
 +{
 +    private String hiduke = "";
 +    private int price     = 0;
 +    private String errmsg = "";
 +    
 +    public void run() 
 +    {
 +        System.out.println("Select Records Example by using the Prepared Statement!");
 +        int count = 0;
 +        
 +        try {
 +            Class.forName("com.mysql.jdbc.Driver");
 +            Connection conn = DriverManager.getConnection ("jdbc:mysql://10.0.2.2:3306/stock","root","secret");
 +            
 +            try {
 +                String sql;
 +                //sql = "SELECT title,year_made FROM movies WHERE year_made >= ? AND year_made <= ?";
 +                sql = "SELECT hiduke, jikan, code, price FROM table_stock";
 +                PreparedStatement qry = conn.prepareStatement(sql);
 +                //qry.setInt(1,1980);
 +                //qry.setInt(2,2004);
 +                ResultSet rs = qry.executeQuery();
 +                while (rs.next()) {
 +                    hiduke = rs.getString(1);
 +                    price  = rs.getInt(4);
 +                    count++;
 +                    System.out.println(hiduke + "\t" + "- " + price);
 +                }
 +                System.out.println("Number of records: " + count);
 +                qry.close();
 +                conn.close();
 +            } catch (SQLException ex) {
 +                System.out.println("SQL statement is not executed!");
 +                errmsg = errmsg + ex.getMessage();
 +            }
 +        } catch (Exception ex) {
 +            ex.printStackTrace();
 +            errmsg = errmsg + ex.getMessage();
 +        }
 +
 +        handler.sendEmptyMessage(0);
 +    }
 +    
 +    private Handler handler = new Handler() 
 +    {
 +        public void handleMessage(Message msg) {
 +            TextView textView = (TextView) findViewById(R.id.textView0);  
 +            textView.setText("hiduke = " + hiduke + " price = " + price  + " " + errmsg);  
 +        }
 +    };
 +
 +    
 +    @Override
 +    protected void onCreate(Bundle savedInstanceState) 
 +    {
 +        super.onCreate(savedInstanceState);
 +        setContentView(R.layout.activity_main);
 +        
 +        Thread thread = new Thread(this);
 +        thread.start();   
 +    }
 +
 +}
 +</code>
 +
 +See: [[https://gist.github.com/cofearabi/5039135]]
 +
  
 == References == == References ==
 See also: See also:
-  * [[swdev:java:Connecting to MYSQL Database]] +  * [[swdev:java:Connecting to MySQL Database]] 
-  * [[https://developer.android.com/training/data-storage/sqlite|Data StorageSQLite]] +  * [[https://www.youtube.com/watch?v=bu5Y3uZ6LLM|ButterfieldStudio For Beginners Part 4: Connecting to MySQL]] 
-  * [[https://developer.android.com/training/data-storage/room|Data Storage: Room]] +  * [[https://www.simplifiedcoding.net/android-mysql-tutorial-to-perform-basic-crud-operation|Android MySQL Tutorial to Perform Basic CRUD Using API]] 
-  * [[https://www.simplifiedcoding.net/android-mysql-tutorial-to-perform-basic-crud-operation|Android MySQL Tutorial with CRUD]]+  * [[http://www.helloandroid.com/tutorials/connecting-mysql-database|Connecting MySQL Database with API]] 
 +  * [[http://androidbash.com/connecting-android-app-to-a-database-using-php-and-mysql|Connecting Android App to MySQL Database]]