Advertisement
coldigniter

Android Refresh

Nov 17th, 2019
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 10.77 KB | None | 0 0
  1.   //1 ANDROID:
  2.  
  3. Learn Basic kotlin
  4. Architecture components
  5. Coroutine/RX
  6. MVVM/livedata
  7. clean architecture
  8. Modular
  9. Unit testing Junit5
  10. Ui Testing espresso/ui automator
  11. ci cd jenkins/circle ci/bitrise
  12.  
  13.  
  14. Kotlin:
  15. -Statically typed, resolves on compilation,
  16. - runs on jvm, open jdk,
  17. - jvm compat compiles down to java bytecode
  18. -interoperatable with java
  19. -official language of Android, developed by jetbrains
  20.  
  21. Features:
  22. Concise - 40% less code than java
  23. Interoperable - works well with java
  24. Opensource - Under apache 2.0
  25. Trustworthy - Made by jetbrains and backed by google
  26. Easy - easier than java
  27. Less error - Compile time only error
  28.  
  29. IDES supported:
  30. Eclipse, IntelliJ, Android Studio
  31.  
  32. ###################################################CODE GENETICS#################
  33.  
  34. //variables: var or val. val is constant var is variable hence variable.
  35. val GRAVITY_MARS = 3.711
  36. /*
  37. visibility modifiers:
  38. private - visible (can be accessed) from inside the class only.
  39. public - visible everywhere. (default if no modifier is stated)
  40. protected - visible to the class and its subclass.
  41. internal - any client inside the module can access them.
  42. */
  43.  
  44. //functions: fun short for function, parameter declaration is name:Data_type, return declaration is : data_type, $variable_name to //embed in string. If you dont want to return any value you can explicitly declare it as "Unit" or "Nothing". By default, methods
  45. //in kotlin use Unit as return if no return type is specified
  46. fun demandMoney(message : String, amount : Int) : String {
  47.     return "$message $";
  48. }
  49.  
  50. //To call function:
  51. robbery("Give me my damn ",5000);
  52.  
  53. //Class and Objects: All classes are final by default and "open" make it inheritable.
  54. //init block is called when an object of it is initialized
  55. //no constructor but in fact all classes have default no argument constructor
  56.  Class Animal{   }
  57.  
  58. //with 1 param "primary" constructor. When "()" is put after classname, it's considered as primary constructor with no body
  59. Class Animal(name : String) {   }
  60. //with 1 param constructor with init block and default value. Init blocks are the body of the primary constructor
  61. Class Animal(_name : String, _address : String = "HOME") {
  62.  var name : String = _name;
  63.  var address : String = _address;
  64.   init { println(name)  }  
  65. }
  66. //with multiple constructors using constructor keyword. "?" primarily means it can accept null values and is also used if you want to //assign a later value
  67. Class Animal{
  68.   private var name : String?
  69.   private var id : Int = 10;
  70.   constructor(_name : String){
  71.         name = _name;
  72.   }
  73.   constructor(_name : String, _id : Int){
  74.         name = _name;
  75.         id = _id;
  76.   }
  77. }
  78. //shortcut functions, code inside returns a string then whole "run block" runs the code and acts as a string which enable you to call
  79. //string functions and properties ##################RUN WITH LET APPLY ALSO ##############################
  80. run{
  81.     //executecode here and return something
  82.     if(x<18) "you are not allowed here" else "Enter"
  83. }.length
  84.  
  85. //similar to run is "with" keyword. Only, "with" along the object acts as receiver and makes it easier to manipulate that object
  86. //returns a new object not the original x
  87. with(x){
  88.     plus(1)
  89.     someMethodThatMultiplies(x) //this line wont do anything because it needs x as parameter. It only affects the receiver "x" if that
  90.     //method is declared within x or declared in Int if x is Int
  91.    
  92.     x
  93.     //the last line means the return of the with block
  94. }.hashCode()
  95. //theres also a way to have a "with" block of code using run keyword object.run also returns a new object not the original x
  96. x.run {
  97.     plus(1)
  98.     times(2)
  99. }.hashCode()
  100.  
  101. //let is similar but instead of receiver, it acts as argument. x is renamed as xy for semantic purposes and does the same thing
  102. //if not renamed however, you use "it" to access fields/methods e.g: it.plus...
  103. x.let{ xy->
  104.     xy.plus(1)
  105.     xy.times(2)
  106. }.hashCode()
  107.  
  108. //"also" is similar to let but it returns the original object instead of returning a new one
  109. x.also{xy->
  110.     xy.plus(1) //by executing this line, you change x value
  111. }
  112. //apply is similar to "also" for returning the original object but it uses "this" instead of "it". "this" can be ommited same as run //and with
  113. x.apply{
  114.     plus(1)
  115. }
  116.  
  117. //basic instantiation of class
  118. var x = Animal();
  119. x.someMethod();
  120. //basic instantiation of class with parameter
  121. var x = Animal("Giraffe");
  122. x.someMethod();
  123. //basic input
  124. var text : String? = readLine()
  125. var age : Int? = readLine()?.toInt()
  126. //basic null check. If text is null without !! it wont display errors
  127. println(text!!)
  128. //basic variable conversion, use toString() vice versa. Also toDouble() toFloat() etc.
  129. var serial : String="43";
  130. var id : Int = serial.toInt()
  131. //if statements are the same with java, however there is a when keyword similar to switch
  132. var x : Int =0;
  133. when(x){
  134.  1,11,111->println("range from 1 to 10")
  135.  in 2..5>->println("value is two")
  136.  !in 2..5>->println("not between 2 and 5")
  137.  else{
  138.    println("else called")
  139.  }
  140. }
  141. //you can also use if or when in initialization
  142. var num : Int = 8;
  143. var stuff : String = when(num){ 8->"eight" else->"just another number"}
  144.  
  145.  
  146. //basic loop use .. to specify range. format (any variable)..(any variable)
  147. var num : Int = 10
  148. for(item in 1..num){
  149.     println(item)
  150. }
  151.  
  152. var x = ArrayList<Int>(5){0}
  153. for(elements in x){
  154.  
  155. }
  156. //basic string functions
  157. var name : String = "home";
  158. println(name[1]) //prints h
  159. println(name.toUpperCase())//prints HOME
  160. println(name.split("h"))
  161.  
  162. //arrays and other collections. Use "to" keyword for maps
  163.  
  164. var b = Array<String>(5){""}; //regular array
  165. var x = ArrayList<String>(); //can have duplicates
  166. var p = HashSet<String>(); //no duplicates
  167. var m = HashMap<Int,String>(); //no duplicates, only 1 null key allowed
  168. var m = HashTable<Int,String>(); //preserves order
  169.  
  170. var f = HashMapOf(1 to "firstItem", 2 to "2nd");//can also be declared this way for convenience, add elements by f.put and so on
  171. var n = ArrayOf(1,2,3,)//same concept different presentation
  172. var l = listOf(1,2,3)//immutable
  173. var ll = mutableListOf//mutable version/editable
  174. var ll = setOf("asd","d")//immutable version/editable
  175. var ll = mutableSetOf("asd","d")//immutable version/editable
  176.  
  177. //basic inheritance with constructor chain using "this" keyword. prints the ff in order:
  178. 1. from entity
  179. 2. from human
  180. 3. empty constuctor from human
  181. //take note it calls super constructors first before itself
  182.  
  183. var d = entity();
  184.  
  185. open class entity{
  186.     var x : Int =0;
  187.    
  188.     constructor(z : Int){
  189.      println("from entity");
  190.      x = z;
  191.    }
  192. }
  193.  
  194. class human : entity {//take note that
  195.     var x : Int =0;
  196.    
  197.     constructor () : this(88){
  198.         println("empty constructor from human");
  199.     }
  200.    
  201.     constructor(z : Int) : super(99){
  202.         println("from human");
  203.         x = z;
  204.     }
  205.    
  206. }
  207. //tradional getter kotlin way
  208.  
  209. class Animal(var name:String){
  210.     fun getName():String{
  211.         return this.name;
  212.     }
  213. }
  214.  
  215. //getter and setter. Value is the parameter value like setter in java. field is getter variable. Here, we put logic if the setted value //is more than 3, field would be 9. final value would be 9
  216. var age : Int = 0
  217.     get() = field
  218.     set(value){
  219.         field = if (value > 3)
  220.             9
  221.         else
  222.             value
  223.     }
  224.  
  225.  
  226. //for singleton, use object instead of class.
  227. //to explicitly hide constructor, use "private constructor()" keyword
  228. //for usual pojos, use "data" keyword before class
  229. //static methods are of java but "companion object" are of kotlin
  230. //const keyword is compile time constant, val is runtime constant. Basically you cant assign method value to const values because //methods are evaluated at runtime
  231.  
  232. class A {
  233.     companion object {//static block
  234.         fun a() {}
  235.         fun b() {} //static but can be accessed by A.companion
  236.         @JvmStatic fun c(){} //equivalent to static method which can be accessed by A.c
  237.        
  238.         @JvmField val x = 42 //equivalent to static field which can be accessed by A.x
  239.         var y = "foo"
  240.     }
  241. }
  242.  
  243.  
  244. #########RETROFIT##########
  245. 1.2. Using Retrofit
  246. To work with Retrofit you basically need the following three classes:
  247.  
  248. ------------Model class which is used as a JSON model
  249.  
  250. class Pokemon(var id : Int, var name : String){
  251.     init{//do stuff here}
  252. }
  253.  
  254.  
  255. ------------Interfaces that define the possible HTTP operations
  256. e.g:
  257. append style for apis like "pokeapi.co/api/v2/pokemon/234"
  258. @POST("api/v2/pokemon/{num}")
  259.     fun retrieveList(@Path("num") num : Int):
  260. parameter style like "sample.org/api&name=master
  261. @POST("api")
  262.    fun retrieveList(@Query("num") num : Int):
  263. as multipart parameter
  264. @POST("api")
  265.    fun retrieveList(@Body product: Product):
  266.  
  267.  
  268.  
  269.  
  270.  
  271. ------------Retrofit.Builder class - Instance which uses the interface and the Builder API to allow defining the URL end point for the HTTP operations.
  272.  
  273. public class Controller implements Callback<List<Change>> {
  274.  
  275.    static final String BASE_URL = "https://git.eclipse.org/r/";
  276.  
  277.     public void start() {
  278.         Gson gson = new GsonBuilder()
  279.                 .setLenient()
  280.                 .create();
  281.  
  282.         Retrofit retrofit = new Retrofit.Builder()
  283.                 .baseUrl(BASE_URL)
  284.                 .addConverterFactory(GsonConverterFactory.create(gson))
  285.                 .build();
  286.  
  287.         GerritAPI gerritAPI = retrofit.create(GerritAPI.class);
  288.  
  289.         Call<List<Change>> call = gerritAPI.loadChanges("status:open");
  290.         call.enqueue(this);
  291.  
  292.     }
  293.  
  294.     @Override
  295.     public void onResponse(Call<List<Change>> call, Response<List<Change>> response) {
  296.         if(response.isSuccessful()) {
  297.             List<Change> changesList = response.body();
  298.             changesList.forEach(change -> System.out.println(change.subject));
  299.         } else {
  300.             System.out.println(response.errorBody());
  301.         }
  302.     }
  303.  
  304.     @Override
  305.     public void onFailure(Call<List<Change>> call, Throwable t) {
  306.         t.printStackTrace();
  307.     }
  308. }
  309.  
  310. then call by instantiating the object then calling create()
  311.  
  312. ----------------------------------------------------------
  313. QUICK REFERESH JSON:
  314. //paste this on json editor
  315. {
  316.  "a string":"this is string input",
  317.   "z hobbies":[1,true,"string",{"num":"0.d2","nums":"2.d2"}],
  318.   "c datum":{"type":"data","date":"12-09-19"}
  319. }
  320. {} is used for json objects
  321. : is used for value pairs
  322. [] is used for pairs.
  323. You cannot put value pairs in [] without {} (e.g: ["name":"game"] is wrong, should be [{"name:"game}]) this is because [] left hand elements are always numbers as indexes.
  324. You cannot put string without "", without "" your value should be either boolean or numeral
  325.  
  326. GSON parsing tips:
  327. Each time gson sees a {}, it creates a Map (actually a gson StringMap )
  328.  
  329. Each time gson sees a '', it creates a String
  330.  
  331. Each time gson sees a true or false, it creates a Boolean
  332.  
  333. Each time gson sees a number, it creates a Double
  334.  
  335. Each time gson sees a [], it creates an ArrayList
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement