Outline 1. Set up Android Studio Android development Tiberiu Vilcu Prepared for EECS 411 Sugih Jamin 15 September 2017 2. Create sample app 3. Add UI to see how the design interface works 4. Add some code to give the app functionality 5. Run and test to verify and debug 1 2 Android Studio Setting up Android Studio Modern IDE for Java, XML, C++ https://developer.android.com/studio/index.html Built-in Java environment Built-in debugger and Android Debug Bridge 1. Install and select Recommended installation 2. Download and install all components it asks Android product emulators Capable of version control (git) Cross-platform (Windows and macos) 3 4
Warnings about Android Studio Outline Android compatibility is fragile Different API versions have widely different use percentages Code may sometimes be underlined while correct as it takes time to refactor Build often to view errors 1. Set up Android Studio 2. Create sample app 3. Add UI to see how the design interface works 4. Add some code to give the app functionality 5. Run and test to verify and debug 5 6 Sample project: Chatter Setting up an Android project Has view to write a post and submit to server Has timeline view to see posts Is cheaply inspired by Twitter Has a live web API already: http://165.227.114.17/getchatts/ http://165.227.114.17/addchatt/ (we will create this in a later lecture as well) 1. Start a new Android Studio Project 2. Set the application name, domain, and location (domain like example.com) 3. Select phone and tablet (only) and API version 17 4. Add an empty activity 5. Pick a good activity name and title 6. Make sure it generates a layout and has backwards compatibility 7 8
Android Studio window Left: project directory, structure, and capture panes Right: design and text editor Bottom: debugging output, terminal, version control panes Adding GitHub remote 1. VCS > Enable Version Control Integration (select Git) 2. File > Other Settings > Default Settings > Version Control > GitHub (add your login and password) 3. VCS > Import into Version Control > Share Project on GitHub 4. Select a new repo name and share (select all subdirectories) 9 10 Android project structure AndroidManifest.xml: general app settings and activity list /java: activity class code and more /res/layout: activity interface XML documents /res/values: constants for strings and designs Gradle: build scripts Outline 1. Set up Android Studio 2. Create sample app 3. Add UI to see how the design interface works 4. Add some code to give the app functionality 5. Run and test to verify and debug 11 12
Adding to the timeline layout 1. Delete the default TextView 2. Drag and drop a FloatingActionButton 3. Select a drawable icon, name postchattactionbutton 4. Add constraints to bottom and right of the button Creating a new activity 1. Select java/com.example.chatter/ directory 2. Right click, New > Activity > Empty Activity 3. Name PostActivity, select Generate Layout File and Backwards Compatibility but not launcher Activity 5. Drag and drop a ListView, name chattlistview 6. Set the width/height to match_parent, add 0 constraints around 13 14 Adding to the post activity 1. Add a TextView for the username and constrain to top center 2. Add a Multiline Text for the message, constrain left 3. Add a Button, constrain to right of message TextView 4. Make width and height of MultilineText wrap_content, give ID Creating a list cell layout 1. Select res/layout/ directory 2. Right click New > Layout resource file 3. Name file chatt_item 4. Make Root element ConstraintLayout 5. Change button text and give ID 15 16
Adding to the Chatt list cell layout 1. Add a TextView for the username, constrain to top left 2. Add a TextView for the timestamp, constrain to top right 3. Add a TextView for the message, make full-width with match_parent and height wrap_content, constrain to bottom 4. Name all widgets Outline 1. Set up Android Studio 2. Create sample app 3. Add UI to see how the design interface works 4. Add some code to give the app functionality 5. Run and test to verify and debug 17 18 Android app activity lifecycle Android app activity lifecycle oncreate(): activity first loads up onstart(): activity becomes visible to the user onresume(): activity comes to foreground and user interacts onpause(): user is leaving activity (but not destroying) onstop(): activity is no longer visible to user ondestroy(): activity being destroyed by user or system 19 20
Adding navigation between activities In TimelineActivity.java: Adding navigation between activities In AndroidManifest.xml: public void postchatt(view view) { Intent intent = new Intent(this, PostActivity.class); startactivity(intent); For the action button, make onclick postchatt() [alt+enter (macos) to auto-import classes] <activity android:name=".postactivity" android:parentactivityname=".timelineactivity" > <!-- The meta-data tag is required if you support API level 15 and lower --> <meta-data android:name="android.support.parent_activity" android:value=".timelineactivity" /> </activity> Adds the back arrow in the PostActivity 21 22 Setting up HTTP connections In AndroidManifest.xml manifest: <uses-permission android:name="android.permission.internet"/> In build.gradle dependencies: compile 'com.android.volley:volley:1.0.0' Volley is a library used to make HTTP requests Making an HTTP POST request public void submitchatt(view view) { RequestQueue queue = Volley.newRequestQueue(this); String url = "http://165.227.114.17/addchatt/"; TextView usernametextview = (TextView) findviewbyid(r.id.usernametextview); TextView messagetextview = (TextView) findviewbyid(r.id.messageedittext); String username = usernametextview.gettext().tostring(); String message = messagetextview.gettext().tostring(); HashMap<String, String> params = new HashMap<String, String>(); params.put("username", username); params.put("message", message); JsonObjectRequest postrequest = new JsonObjectRequest(url, new JSONObject(params), new Response.Listener<JSONObject>() { public void onresponse(jsonobject response) { finish();, new Response.ErrorListener() { ); public void onerrorresponse(volleyerror error) { finish(); queue.add(postrequest); Add the onclick listener to the submitbutton 23 24
Adding a custom Java class 1. Select java/com.example.chatter directory 2. Right click > New > Java Class 3. Name Chatt and leave default options Adding a custom Java class for Chatt public class Chatt { public String username; public String message; public String timestamp; public Chatt(String username, String message, String timestamp) { this.username = username; this.message = message; this.timestamp = timestamp; 25 26 Adding a list adapter Create a new Java class ChattAdapter the same as before List adapters used to link elements in lists to ListViews Adding a list adapter public class ChattAdapter extends ArrayAdapter<Chatt> { public ChattAdapter(Context context, ArrayList<Chatt> users) { super(context, 0, users); public View getview(int position, View convertview, ViewGroup parent) { Chatt chatt = getitem(position); if (convertview == null) { convertview = LayoutInflater.from(getContext()).inflate(R.layout.chatt_item, parent, false); TextView usernametextview = (TextView) convertview.findviewbyid(r.id.usernametextview); TextView messagetextview = (TextView) convertview.findviewbyid(r.id.messagetextview); TextView timestamptextview = (TextView) convertview.findviewbyid(r.id.timestamptextview); usernametextview.settext(chatt.username); messagetextview.settext(chatt.message); timestamptextview.settext(chatt.timestamp); return convertview; 27 28
Setting up the list adapter Adding a function to refresh private ArrayList<Chatt> chattarraylist; private ChattAdapter chattadapter; protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_timeline); chattarraylist = new ArrayList<Chatt>(); chattadapter = new ChattAdapter(this, chattarraylist); ListView lview = (ListView) findviewbyid(r.id.chattlistview); lview.setadapter(chattadapter); Call function in oncreate() as well private void refreshtimeline() { chattadapter.clear(); RequestQueue queue = Volley.newRequestQueue(this); final String url = "http://165.227.114.17/getchatts/"; queue.add(getrequest); 29 30 HTTP GET request and adding to list Pull-to-refresh the timeline JsonObjectRequest getrequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { public void onresponse(jsonobject response) { try { JSONArray array = response.getjsonarray("chatts"); for (int i = 0; i < array.length(); i++) { String username = array.getjsonarray(i).getstring(0); String message = array.getjsonarray(i).getstring(1); String timestamp = array.getjsonarray(i).getstring(2); chattadapter.add(new Chatt(username, message, timestamp)); catch (JSONException e) {, new Response.ErrorListener() { public void onerrorresponse(volleyerror error) { ); Around ListView in activity_timeline.xml: <android.support.v4.widget.swiperefreshlayout xmlns:android="http:// schemas.android.com/apk/res/android" android:id="@+id/refreshcontainer" android:layout_width="wrap_content" android:layout_height="wrap_content"> </android.support.v4.widget.swiperefreshlayout> 31 32
Pull-to-refresh the timeline Outline private SwipeRefreshLayout refreshcontainer; Set up in oncreate(): refreshcontainer = (SwipeRefreshLayout) findviewbyid(r.id.refreshcontainer); refreshcontainer.setonrefreshlistener(new SwipeRefreshLayout.OnRefreshListener() { public void onrefresh() { refreshtimeline(); ); To stop refreshing animation whenever needed 1. Set up Android Studio 2. Create sample app 3. Add UI to see how the design interface works 4. Add some code to give the app functionality 5. Run and test to verify and debug refreshcontainer.setrefreshing(false); 33 34 Running on an Android emulator 1. Hit the green play button 2. Create New Virtual Device 3. Pick a device and system image (Nexus 5X and O x86 are good) 4. Give it a name and leave the default settings 5. Use same selection for future launches and hit OK Possible improvements Error handling Using constant string values Automatically add new post to timeline without refreshing Don t delete and refresh the entire timeline 6. Use yellow lightning icon in Android Studio to quickly rebuild and refresh app 7. Close emulator entirely with Cmd+Q 35 36
Tips before you begin Learn how to use Java and XML as you go Plan your activities and how they interact ahead of time Name your widgets and variables carefully; refactoring can cause problems Don t waste too much time on icons Resources Sample project repo: https://github.com/um-eecs-441/android-project-samplef17 Android Studio: https://developer.android.com/studio/index.html Android programming tutorial: https://developer.android.com/training/index.html App activity lifecycle: https://developer.android.com/guide/components/ activities/activity-lifecycle.html Google Play developer account: https://support.google.com/googleplay/androiddeveloper/answer/6112435?hl=en 37 38