android

home

Contents of My Android experience in February 2017

1. hello world - lab

  hello world - study steps

  hello world - study more

2. Setup tests for Java code in Android Studio

3. convert a json array in String to JSONArray

In ios swift, the data model for this scenario to display is [Dictionary<String, String>] Aray of dictionary, each has key-value pair. It is much more flexible to define types.
if (id == R.id.action_test1) { JSONArray ar; // [{"name":"Tairo","weight":28},{"name":"Emi","weight":30}] String content = "[{\"name\":\"Tairo\",\"weight\":28},{\"name\":\"Emi\",\"weight\":30}]"; try { ar = new JSONArray(content); Toast.makeText(this, "convert to JSONArray is good", Toast.LENGTH_LONG).show(); for (int i = 0; i < ar.length(); i++){ String name = ar.getJSONObject(i).getString("name"); String strWeight = ar.getJSONObject(i).getString("weight"); Toast.makeText(this, name + "/" + strWeight, Toast.LENGTH_LONG).show(); // JSONArray is not the model data type for ListView, further conversion is needed. List<String> dogNames = new ArrayList<>(); for (int i = 0; i < num; i++) { String name = ar.getJSONObject(i).getString("name"); String strWeight = ar.getJSONObject(i).getString("weight"); Toast.makeText(this, "name, weight "+ name + "," + strWeight, Toast.LENGTH_LONG).show(); // populate name to List dogNames.add(name); } Toast.makeText(this, "the second dog name in the list is " + dogNames.get(1), Toast.LENGTH_LONG).show(); } } catch (JSONException e) { Toast.makeText(this, "convert to JSONArray is bad", Toast.LENGTH_LONG).show(); e.printStackTrace(); } return true; }

4. convert a json in String to JSONObject

Some rest services provides data, not as an array.

    if (id == R.id.action_test3) {
        JSONObject obj;
        //  {dogs: [{"name":"Tairo","weight":28},{"name":"Emi","weight":30}]}
        String content = "{dogs: [{\"name\":\"Tairo\",\"weight\":28},{\"name\":\"Emi\",\"weight\":30}]}";
        try {
            obj = new JSONObject(content);
            JSONArray ar = obj.getJSONArray("dogs");
            int num = ar.length();
            String strNum = Integer.toString(num);
            Toast.makeText(this, "number of dogs is " + strNum, Toast.LENGTH_LONG).show();  
        } catch (JSONException e) {
            Toast.makeText(this, "convert to JSONObject is bad", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
        return true;
    }
            

5. A Simple Java Class

6. ArrayAdapter, ListView, Activity

----------- 6.1 ArrayAdapter -----------

// in onCreate, add code as below List<String> dogNames = new ArrayList<>(); dogNames.add("Tairo"); dogNames.add("Emi"); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, items3 );

----------- 6.2 ListView ---------------


----------- 6.3 Activity ---------------

*passing data from MainActivity to Main2Activity using static data in MainActivity - create a static variable public static List<String> dogNames2; - set its value from some method. in Main2Activity, inside onCreate, code as below: List<String> dogNames3 = MainActivity.dogNames2; String dogName = dogNames3.get(0); Toast.makeText(this, dogName, toast.LENGTH_LONG).show(); run, click menu item for navigation, to see the first dog name.

8. RelativeLayout

layout

9. Class AsyncTask

---- 9.1 intro ------------
// --- code --- MyTask task = new MyTask(); task.execute("have a nice day"); Toast.makeText(this, "in ui thread", Toast.LENGTH_LONG).show(); } // onCreate private class MyTask extends AsyncTask<String, String, String>{ @Override protected String doInBackground(String... params){ String p1 = params[0]; try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } return p1; } @Override protected void onPostExecute(String result) { TextView tv = (TextView)findViewById(R.id.tv); tv.setText(result); } // --- code reveiw --- 1. class signature AsyncTask <Params, Progress, Result> Params: The type of the parameters,sent to task, upon execution, The data will be passed from the task execution method to doInBackground Three dots means the size is flexible. In rest scenario, one is used for uri. The type is String Progress: The type for messages passing from ui thread to network thread during the process. Result: the type of the data, return from method doBackground to method doPost and return from method doPost to UI thread. In rest scenario, the type is String. It is fit for JSON data in string format. 2. The toast message demonstrates that the ui thread is not blocked. 3. The greeting message is used for input and output the async task. 4. In method onPostExecute, demonstrates the communication with UI thread at the end.

10. REST Client

--- part 1, rest get ----

in AndroidManifest.xml, add the following code before app tag.

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET" /

in MainActivity.java, add a instance helper method as below:

        protected boolean isOnline(){
            ConnectivityManager cm
                    = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            if (netInfo != null && netInfo.isConnectedOrConnecting()){
                return true;
            } else {
                return false;
            }
        }

        // create a instance variable as below:
        private String uri = "http://www.mj-go-test.com/test_6_select.php";
        
        // in onCreate, modifying the code as below
        .....
        if (isOnline()) {
            
                MyTask task = new MyTask();
                task.execute(uri);
                Toast.makeText(this, "network is available", Toast.LENGTH_LONG).show();
            
        } else {
                Toast.makeText(this, "network isn't available", Toast.LENGTH_LONG).show();
            }
        }
            

--- connection, reader, read ---

        package com.example.peterkao.app02272017;

        import java.io.BufferedReader;
        import java.io.IOException;
        import java.io.InputStreamReader;
        import java.net.HttpURLConnection;
        import java.net.URL;

        public class HttpHelper {
            public static String getData(String uri){
                BufferedReader reader = null;

                try {
                    URL url = new URL(uri);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();

                    StringBuilder sb = new StringBuilder();
                    reader = new BufferedReader(new InputStreamReader(con.getInputStream()));

                    String line;
                    while ((line = reader.readLine()) != null){
                        sb.append(line + "\n");
                    }
                    return sb.toString();

                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                } finally {
                    if (reader != null){
                        try {
                            reader.close();;
                        } catch (IOException e){
                            e.printStackTrace();
                            return null;
                        }
                    }
                }

            }
        }
            

code review - getData

start rest get

        private class MyTask extends AsyncTask{
            @Override
            protected String doInBackground(String... params){
                String contents = "";
                try {
                    contents = HttpHelper.getData(params[0]);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return contents;
            }

            @Override
            protected void onPostExecute(String result) {
                TextView tv = (TextView)findViewById(R.id.tv);
                tv.setText(result);  
            }
        }
            

preparing php rest service - get

<?php $data1 = "['a4', 'b', 'c' ]"; $data2 = "{'name' : 'tairo'}"; $data3 = "{'name' : 'emi', 'weight' : 32}"; $data4 = '"dogs":[{"name":"Tairo", "weight": 32},{"name":"Emi", "weight": 29]}'; //header('Content-Type: application/json'); //echo json_encode($data3); echo $data4; ?> php rest arc tests

--- part 2, rest post ----

intro

service code

http://www.mj-go-test.com/post_echoback.php <?php echo file_get_contents("php://input"); ?> - step 1, the method reads the input - step 2, the method converts the input data into string. - step 3, echo the string - The method argument is PHP's convention.

create the app for post

        in MainActivity, code the menu item handler
                   
        if (online()){
            MyTask = new MyTask();
            task.execute();
        } else {
            // output error
        }
            
        private class MyTask extends AsyncTask {
            @Override
            protected String doInBackground(String... p) {
                BufferedReader reader = null;
                try {
                    //-------- 1.  post                   ----------------------
                    String strUri = "http://www.mj-go-test.com/post_echoback.php";
                    URL url = new URL(strUri);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    con.setRequestMethod("POST");
            
            JSONObject obj = new JSONObject();
            obj.put("weight", new Integer(29));
            obj.put("name", "Emi kao");
            String myData = "params = " + obj.toString();

            con.setDoOutput(true);
            OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
            writer.write(myData);
            writer.flush();
            
                    //-------- 2.   get  the echo data back from the service -----------
                    StringBuilder sb = new StringBuilder();
                    reader = new BufferedReader(new InputStreamReader(con.getInputStream()));

                    String line;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    return sb.toString();
                    //--------      end --------------------------------------
                    //return "post and get done";
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                            return null;
                        }
                    }
                }
            }
            @Override
            protected void onPostExecute(String result) {
                Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
            }

        }   //----------------------    end of inner class