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:start [2018/04/29 08:08]
smayr [Resources]
swdev:android:start [2018/05/22 14:15] (current)
smayr [Resources]
Line 5: Line 5:
     * [[https://developer.android.com/index.html|Android Development Resources]]     * [[https://developer.android.com/index.html|Android Development Resources]]
     * [[https://developer.android.com/studio/index.html|Android Studio (IDE)]]     * [[https://developer.android.com/studio/index.html|Android Studio (IDE)]]
 +    * [[https://flutter.io/get-started/codelab/|Flutter (IDE)]]
     * [[https://www.visualstudio.com|Visual Studio (IDE) + Xamarin]] - Select //Community Edition//     * [[https://www.visualstudio.com|Visual Studio (IDE) + Xamarin]] - Select //Community Edition//
  
Line 127: Line 128:
 if (intentDialNumber.resolveActivity(getPackageManager()) != null) { if (intentDialNumber.resolveActivity(getPackageManager()) != null) {
     startActivity(intentDialNumber);     startActivity(intentDialNumber);
 +}
 +
 +// Call contacts to handle contact selection
 +Intent intentSelectContact = new Intent(Intent.ACTION_DIAL, new Uri("content://contacts"));
 +if (intentSelectContact.resolveActivity(getPackageManager()) != null) {
 +    startActivity(intentSelectContact);
 } }
  
Line 166: Line 173:
                 intentDataHandler.putExtra("Key2", "Value2");  // data payload (optional)                 intentDataHandler.putExtra("Key2", "Value2");  // data payload (optional)
                 intentDataHandler.putExtra("com.acme.myapp.Key3", "Value3");  // use full path with key (recommended)                 intentDataHandler.putExtra("com.acme.myapp.Key3", "Value3");  // use full path with key (recommended)
-                startActivity();+                intentDataHandler.putExtra("Key4.TEAM_OBJ", aTeamObj); // parcelable object (eg. object of type Team) 
 +                startActivity(intentDataHandler);
                 break;                 break;
         }         }
Line 176: Line 184:
 <code java> <code java>
 //... //...
-public class ActivityTargetSample extends AppCompatActivity +public class TargetActivity extends AppCompatActivity 
 { {
     @Override     @Override
Line 182: Line 190:
     {     {
         super.onCreate(saveInstanceState);         super.onCreate(saveInstanceState);
-        setContentView(R.layout.activity_target_sample);+        setContentView(R.layout.activity_target);
                  
-        Bundle bundle = getIntent().getExtras();   // get data payload (if available)+        //----------------------------------- 
 +        // Get data payload (if available) 
 +        //----------------------------------- 
 +        // Method 1 
 +        Bundle bundle = getIntent().getExtras();   
         String str = bundle.getString("Key1");         String str = bundle.getString("Key1");
-         
         Toast.makeText(this, str, Toast.LENGTH_SHORT).show();         Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
                  
-        // Better yet +        // Method 2 
-        if (getIntent().hasExtra("Key2")) { +        Intent intent = getIntent()
-            str = getIntent().getExtras().getString("Key2");+        if (intent.hasExtra("Key2")) { 
 +            str = intent.getExtras().getString("Key2");
             Toast.makeText(this, str, Toast.LENGTH_SHORT).show();             Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
 +        } 
 +         
 +        // Method 3 
 +        if (getIntent().hasExtra("Key3")) { 
 +            str = getIntent().getExtras().getString("Key3"); 
 +            Toast.makeText(this, str, Toast.LENGTH_SHORT).show(); 
 +        } 
 +         
 +        // Parcelable data 
 +        Team objTeam; 
 +        if (intent.hasExtra("Key4.TEAM_OBJ")) { 
 +            Log.d("MyApp", "Retrieving intent extras..."); 
 +            objTeam = intent.getParcelableExtra("Key4.TEAM_OBJ"); 
 +            Toast.makeText(this, "Team Name: "+ objTeam.name, Toast.LENGTH_SHORT).show();
         }         }
     }     }
Line 199: Line 224:
 </code> </code>
  
 +A parcelable extra must be of a type supporting parcelable.  For example:
 +<code java>
 +package com.acme.myapp;
 +
 +import android.os.Parcel;
 +import android.os.Parcelable;
 +
 +public class Team implements Parcelable
 +{
 +    public long id = 0;
 +    public String name = "";
 +    public String number = "";
 +    public int ranking = 0;
 +
 +    // Default constructor
 +    Team()
 +    {
 +
 +    }
 +
 +    // In constructor, read variables from Parcel. 
 +    // Important: Read them in the same sequence in which they were written in Parcel.
 +    public Team(Parcel in) {
 +        id = in.readLong();
 +        name = in.readString();
 +        number = in.readString();
 +        ranking = in.readInt();
 +    }
 +
 +    @Override
 +    public int describeContents() {
 +        return 0;
 +    }
 +
 +    // Write member variables in Parcel. 
 +    // Write in any order. Not required to write all members in Parcel.
 +    @Override
 +    public void writeToParcel(Parcel dest, int flags) {
 +        // Write data in any order
 +        dest.writeLong(id);
 +        dest.writeString(name);
 +        dest.writeString(number);
 +        dest.writeInt(ranking);
 +    }
 +
 +    // De-serialize the object
 +    public static final Parcelable.Creator<Team> CREATOR = new Parcelable.Creator<Team>(){
 +        public Team createFromParcel(Parcel in) {
 +            return new Team(in);
 +        }
 +
 +        public Team[] newArray(int size) {
 +            return new Team[size];
 +        }
 +    };
 +}
 +</code>
 === Intent Examples === === Intent Examples ===
 For example, in the ''MainActivity'', you can define an intent: For example, in the ''MainActivity'', you can define an intent:
Line 229: Line 311:
             case R.id.btnDialNumber:             case R.id.btnDialNumber:
                 Intent intentDialNumber = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:4071233500"));                 Intent intentDialNumber = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:4071233500"));
-                startActivity(intentDialNumber);+                if (intentDialNumber.resolveActivity(getPackageManager()) != null) { 
 +                    startActivity(intentDialNumber); 
 +                }
                 break;                 break;
                                  
             case R.id.btnViewWebsite:             case R.id.btnViewWebsite:
                 Intent intentViewWebsite = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.acme.com"));                 Intent intentViewWebsite = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.acme.com"));
-                startActivity(intentViewWebsite);+                if (intentViewWebsite.resolveActivity(getPackageManager()) != null) { 
 +                    startActivity(intentViewWebsite); 
 +                }
                 break;                 break;
                                  
Line 240: Line 326:
                 Intent intentShowLocation = new Intent(Intent.ACTION_VIEW,                  Intent intentShowLocation = new Intent(Intent.ACTION_VIEW, 
                     Uri.parse("geo:28.6027902,-81.4232732,14z"   // lat,long,zoom                     Uri.parse("geo:28.6027902,-81.4232732,14z"   // lat,long,zoom
-                ));   +                )); 
-                startActivity(intentShowLocation);+                if (intentShowLocation.resolveActivity(getPackageManager()) != null) { 
 +                    startActivity(intentShowLocation); 
 +                }
                 break;                 break;
                                  
Line 247: Line 335:
                 // Display all activities supporting Action View that can handle intent                 // Display all activities supporting Action View that can handle intent
                 Intent intentShowAllActivities = new Intent(Intent.ACTION_VIEW);                 Intent intentShowAllActivities = new Intent(Intent.ACTION_VIEW);
-                startActivity(intentShowAllActivities);+                if (intentShowAllActivities.resolveActivity(getPackageManager()) != null) { 
 +                    startActivity(intentShowAllActivities); 
 +                }
                 break;                 break;
                                  
Line 254: Line 344:
                     SampleActivity.class   // target activity                     SampleActivity.class   // target activity
                 );                 );
-                startActivity(intentShowToast);+                if (intentShowToast.resolveActivity(getPackageManager()) != null) { 
 +                    startActivity(intentShowToast); 
 +                }
                 break;                 break;
                          
             case R.id.btnShowSampleActivity:             case R.id.btnShowSampleActivity:
                 Intent intentShowSampleActivity = new Intent("com.acme.myapp.SampleActivity");                              Intent intentShowSampleActivity = new Intent("com.acme.myapp.SampleActivity");             
-                startActivity(intentShowSampleActivity);+                if (intentShowSampleActivity.resolveActivity(getPackageManager()) != null) { 
 +                    startActivity(intentShowSampleActivity); 
 +                }
                 break;                 break;
         }         }
Line 789: Line 883:
  
 == Database Connection == == Database Connection ==
-==== DB Connector ==== +  * [[swdev:android:Database MySQL]] 
-Download the appropriate Java database connector: +  * [[swdev:android:Database SQLite]]
-  * [[https://dev.mysql.com/downloads/connector/j/3.0.html|Download JDBC library]] (select 'Platform Independent' version) +
-  * Add as module: ''app'', right-click then ''New'' > ''Module'', then select 'Import .JAR/.AAR Package', and find jar file. +
-  * See also:[[swdev:java:Connecting to MYSQL Database]] +
- +
-==== Manifest ==== +
-Add permission to access the Internet.  Go to ''app'' > ''manifests'' > ''AndroidManifest.xml'': +
-<code xml> +
-<manifest...> +
-    <uses-permission android:name="android.permission.INTERNET"/> +
-     +
-    <application...> +
-    </application> +
-</manifest> +
-</code> +
- +
-==== Database Strings ==== +
-Create a class to hold the database strings: +
-File ''DbStrings.java'': +
-<code java> +
-package com.acme.myapp; +
- +
-public class DbStrings +
-+
-  static final String DATABASE_URL  = "192.168.0.1:3306"; +
-  static final String DATABASE_NAME = "mydatabase"; +
-  static final String USERNAME      = "dbuser"; +
-  static final String PASSWORD      = "dbsecret"; +
-+
-</code> +
- +
- +
-==== ItemAdapter ==== +
-Create class ItemAdapter +
-  * Go to project tree, select ''app'' > ''java'' > //''<your app package name>''//. Right-click and select ''New'' > ''Java Class''+
-  * Name: ''ItemAdapter'' +
-  * Kind: ''Class'' +
-  * Superclass: ''android.widget.BaseAdapter'' +
- +
-<code java> +
-import android.view.ViewGroup; +
-import android.widget.BaseAdapter; +
- +
-public class ItemAdapter extends BaseAdapter +
-+
-    LayoutInflater mInflater; +
-    Map<String, Double> map;  // products & prices +
-     +
-    List<String> products; +
-    List<String> prices; +
-     +
-    public ItemAdapter(Context cx, Map m) +
-    { +
-        map = m; +
-        products = new ArrayList<String>(map.keySet()); +
-        prices   = new ArrayList<String>(map.keySet()); +
-         +
-        mInflater = (LayoutInflater) cx.getSystemService(Context.LAYOUT_INFLATER_SERVICE); +
-    } +
- +
-    @Override +
-    public int getCount() +
-    { +
-        return map.size(); +
-    } +
-     +
-    @Override +
-    public Object getItem(int idx) +
-    { +
-        return products.get(idx); +
-    } +
-     +
-    @Override +
-    public long getItemId(int idx) +
-    { +
-        return idx; +
-    } +
-     +
-    @Override +
-    public View getView(int idx, View view, ViewGroup viewGroup) +
-    { +
-        // Use layout inflater.  Use listview_detail.xml layout +
-         +
-        View vw = mInflater.inflate(R.layout.listview_detail, null); +
-        TextView lblProduct = (TextView) vw.findViewById(R.id.lblProduct); +
-        TextView lblPrice   = (TextView) vw.findViewById(R.id.lblPrice); +
-         +
-        String strProduct = arrProducts.get(idx); +
-        String strPrice   = "$" + arrPrices.get(idx).toString(); +
-         +
-        lblProduct.setText(strProduct); +
-        lblPrice.setText(strPrice); +
-         +
-        return vw; +
-    } +
-+
-</code> +
- +
- +
-=== MainActivity === +
-<code java> +
-package com.acme.myapp; +
-  +
-import android.support.v7.app.AppCompatActivity; +
-import android.os.Bundle; +
-  +
-public class MainActivity extends AppCompatActivity  +
-+
-    // Properties +
-    ItemAdapter itemAdapter; +
-    Context thisContext; +
-    ListView lstProducts; +
-    TextView lblProgress; +
-    Map<String, Double> mapProducts = new LinkedHashMap<String, Double>(); +
-  +
-    @Override +
-    protected void onCreate(Bundle savedInstanceState)  +
-    { +
-        super.onCreate(savedInstanceState); +
-        setContentView(R.layout.activity_main); +
-  +
-        Resources res = getResources(); +
-        lstItems      = (ListView) findViewById(R.id.lstItems); +
-        lblProgress   = (TextView) findViewById(R.id.lblProgress); +
-        thisContext   = this; +
-         +
-        lblProgress.setText(""); +
-         +
-        Button bntConnect = (Button) findViewById(R.id.btnConnect); +
-        btnConnect.setOnClickListener(new View.OnClickListener() { +
-            @Override +
-            public void onClick(View vw) { +
-                GetData retrieveData = new GetDate(); +
-                retrieveData.execute(""); +
-            } +
-        }); +
-    }  +
-     +
-    private class GetData extends AsyncTask<String,String,String>  +
-    { +
-      // Properties +
-      String msg = "";   // progress textview +
-       +
-      // JDBC driver name and database URL +
-      static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; +
-       +
-      // Example: 192.168.0.2:3306 +
-      static final String DB_URL = "jdbc:mysql://"+
-          DbStrings.DATABASE_URL + "/"+
-          DbStrings.DATABASE_NAME; +
-           +
-       @Override +
-       protected void onPreExecute()  +
-       { +
-           lblProgress.setText("Connecting to database..."); +
-       } +
-        +
-       @Override +
-       protected String doInBackground(String... params)  +
-       { +
-           Connection conn = null; +
-           Statement stmt = null; +
-            +
-           try { +
-               Class.forName(JDBC_DRIVER); +
-               conn = DriverManager.getConnection(DB_URL, DbStrings.USERNAME, DbStrings.PASSWORD); +
-               stmt = conn.createStatement(); +
-               String sql = "SELECT * FROM products"; +
-               ResultSet rs = stmt.executeQuery(sql); +
-               while(rs.next()) { +
-                   String name = rs.getString("name"); +
-                   double price = rs.getDouble("price"); +
-                    +
-                   mapProducts.put(name, price); +
-               } +
-                +
-               msg = "Process complete."; +
-                +
-               rs.close(); +
-               stmt.close(); +
-               conn.close(); +
-                +
-           } catch (SSQLException connError) { +
-              msg = "Exception was thrown for JDBC."; +
-              connError.printStackTrace(); +
-           } catch (ClassNotFoundException ex) { +
-              msg = "A class not foudnn exception was thrown."; +
-              ex.printStackTrace(); +
-           } finally { +
-               try { +
-                   if (stmt != null) { stmt.close();+
-               } catch (SQLException ex) { +
-                   stmt.close(); +
-               } +
-               try { +
-                   if (conn != null) { conn.close();+
-               } catch (SQLException ex) { +
-                   conn.close(); +
-               } +
-           } +
-           return null; +
-       } +
-        +
-       @Override +
-       protected void onPostExecute(String msg) { +
-           lblProgress.setText(this.msg); +
-           if (mapProducts.size() > 0) { +
-               itemAdapter = new ItemAdapter(thisContext, mapProducts); +
-               lstProducts.setAdapter(itemAdapter()); +
-           } +
-       } +
-    } +
-+
-</code>+