Contents of My Android experience in February 2017
public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_test1) { Toast.makeText(this, "in test1", Toast.LENGTH_LONG).show(); return true; } if (id == R.id.action_test2) { TextView tv = (TextView)findViewById(R.id.textview); String s = tv.getText().toString(); Toast.makeText(this, "s = " + s, Toast.LENGTH_LONG).show(); tv.setText("updated"); return true; } return super.onOptionsItemSelected(item); } note-1: After you type Toast, hit enter, you'll see android.widget , hit again to import the library. note-2: In Android, a view is a ui control, like TextView. note-3: In this demo, you can see to interact with a view. note-4: Toast is like alert in javascript, easy for debug. note-5: You can use java switch language construct. That is not a must. note-6: You can set a text in a strings.xml. That is not a must. You can take care later.
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; }
private String dogName; private int dogWeight;
Dog dog1 = new Dog(); dog1.setDogName("Tairo"); dog1.setDogWeight(28); String name = dog1.getDogName(); int weight = dog1.getDogWeight(); Toast.makeText(this, name + weight, Toast.Length_LONG().show(); // Concatenatin a String with a integer, results in a String.
in AndroidManifest.xml, add the following code before app tag.
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(); } }
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; } } } } }
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); } }
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