· 5 years ago · Feb 26, 2020, 08:02 PM
1
2:: Andy ::
3
4#PRACTICAL No. 1
51. Introduction to Android, Introduction to Android
6Studio IDE, Application Fundamentals: Creating a
7Project, Android Components, Activities, Services,
8Content Providers, Broadcast Receivers, Interface
9overview, Creating Android Virtual device, USB
10debugging mode, Android Application Overview.
11Simple "Hello World" program.
12
13Solution:
14
15Activity_Main.Kt
16package com.raj.hello
17import android.support.v7.app.AppCompatActivity
18import android.os.Bundle
19class MainActivity : AppCompatActivity() {
20 override fun onCreate(savedInstanceState: Bundle?) {
21 super.onCreate(savedInstanceState)
22 setContentView(R.layout.activity_main)
23 }
24}
25
26Activity_Main.xml
27<?xml version="1.0" encoding="utf-8"?>
28<android.support.constraint.ConstraintLayout
29 xmlns:android="http://schemas.android.com/apk/res/android"
30 xmlns:tools="http://schemas.android.com/tools"
31 xmlns:app="http://schemas.android.com/apk/res-auto"
32 android:layout_width="match_parent"
33 android:layout_height="match_parent"
34 tools:context=".MainActivity">
35 <TextView
36 android:layout_width="wrap_content"
37 android:layout_height="wrap_content"
38 android:text="Hello World!"
39 app:layout_constraintBottom_toBottomOf="parent"
40 app:layout_constraintLeft_toLeftOf="parent"
41 app:layout_constraintRight_toRightOf="parent"
42 app:layout_constraintTop_toTopOf="parent"/>
43</android.support.constraint.ConstraintLayout>
44
45BroadcastActivity:
46How to receiving Broadcast
47Apps can receive and android BroadcastReceiver in two ways:
48through manifest-declared receivers and context-registered
49receivers. In this example, we are approaching
50manifest-declared Receiver. Learn step by step to the
51kotlin broadcast receiver example works.
52
53Step 1. Create an android app, For creating an Android
54app with kotlin read this tutorial.
55Step 2. Creating Broadcast Receiver
56Create and extend Subclass and BroadcastReceiver implement.
57onReceive(Context, Intent) where onReceive method each
58message is received as an Intent object parameter.
59MyReceiver.kt:
60import android.content.BroadcastReceiver
61import android.content.Context
62import android.content.Intent
63import android.widget.Toast
64
65class MyReceiver : BroadcastReceiver() {
66 override fun onReceive(context: Context, intent: Intent) {
67 Toast.makeText(context, "Broadcast : Flight mode changed.",
68 Toast.LENGTH_LONG).show()
69 }
70}
713.Declare a broadcast receiver in the manifest file
72add the element<receiver> in your app's manifest.
73
74
75<?xml version="1.0" encoding="utf-8"?>
76<manifest xmlns:android="http://schemas.android.com/apk/res/android"
77 package="in.eyehunt.androidbroadcasts">
78 <application
79 android:allowBackup="true"
80 android:icon="@mipmap/ic_launcher"
81 android:label="@string/app_name"
82 android:roundIcon="@mipmap/ic_launcher_round"
83 android:supportsRtl="true"
84 android:theme="@style/AppTheme">
85 <activity android:name=".MainActivity">
86 <intent-filter>
87 <action android:name="android.
88 intent.action.MAIN" />
89 <category android:name="android.
90 intent.category.LAUNCHER" />
91 </intent-filter>
92 </activity>
93
94 <receiver
95 android:name=".MyReceiver"
96 android:enabled="true"
97 android:exported="true">
98 <intent-filter>
99 <action android:name="android.intent.
100 action.AIRPLANE_MODE"/>
101 </intent-filter>
102 </receiver>
103 </application>
104
105</manifest>
106
107Step 4. MainActivity code, no needs to do anything
108MainActivity.kt:
109import android.support.v7.app.AppCompatActivity
110import android.os.Bundle
111class MainActivity : AppCompatActivity() {
112 override fun onCreate(savedInstanceState: Bundle?) {
113 super.onCreate(savedInstanceState)
114 setContentView(R.layout.activity_main)
115 }
116}
117
118Step 5. Add following code in main_activity.xml
119add <ImageView> and <TextView>widget layout file.
120main_activity.xml:
121
122<?xml version="1.0" encoding="utf-8"?>
123<android.support.constraint.ConstraintLayout xmlns:android=
124 "http://schemas.android.com/apk/res/android"
125 xmlns:app="http://schemas.android.com/apk/res-auto"
126 xmlns:tools="http://schemas.android.com/tools"
127 android:layout_width="match_parent"
128 android:layout_height="match_parent"
129 android:background="@color/colorPrimary"
130 tools:context="in.eyehunt.androidbroadcasts.MainActivity">
131
132 <ImageView
133 android:id="@+id/imageView"
134 android:layout_width="40dp"
135 android:layout_height="40dp"
136 android:layout_margin="8dp"
137 android:layout_marginTop="16dp"
138 app:layout_constraintStart_toStartOf="parent"
139 app:layout_constraintTop_toTopOf="parent"
140 app:srcCompat="@mipmap/baseline_airplanemode_active_white_24" />
141
142 <TextView
143 android:id="@+id/textView"
144 android:layout_width="300dp"
145 android:layout_height="36dp"
146 android:layout_marginEnd="8dp"
147 android:layout_marginStart="8dp"
148 android:gravity="center_vertical"
149 android:text="Flight Mode"
150 android:textColor="@color/colorWhite"
151 android:textSize="24dp"
152 app:layout_constraintEnd_toEndOf="parent"
153 app:layout_constraintStart_toEndOf="@+id/imageView"
154 app:layout_constraintTop_toTopOf="@+id/imageView" />
155</android.support.constraint.ConstraintLayout>
156
157Create and manage virtual devices:
158To open the AVD Manager, do one of the following:
159* Select Tools > AVD Manager.
160* Click AVD Manager AVD Manager icon in the toolbar.
161
162
163
164
165############################################################
166
167
168
169
170#PRACTICAL No. 2
171#Programming Resources
172Android Resources:
173(Color, Theme, String, Drawable, Dimension, Image).
174Color:
175
176Color.xml
177<?xml version="1.0" encoding="utf-8"?>
178<resources>
179 <color name="colorPrimary">#008577</color>
180 <color name="colorPrimaryDark">#00574B</color>
181 <color name="colorAccent">#D81B60</color>
182</resources>
183
184Theme:
185Style.xml
186<resources>
187 <!-- Base application theme. -->
188 <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
189 <!-- Customize your theme here. -->
190 <item name="colorPrimary">@color/colorPrimary</item>
191 <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
192 <item name="colorAccent">@color/colorAccent</item>
193 </style>
194</resources>
195
196String:
197String.xml:
198<resources>
199 <string name="app_name">hello</string>
200 <string name="numbers">
201 <item>1</item>
202 <item>2</item>
203 <item>3</item>
204 </item>
205 </string>
206</resources>
207
208Drawable:
2091. Right click on drawable folder
2102. Copy the image if you want to create image drawable
2113. Paste that image file inside the drawable folder
212
213Dimension, Image:
214Main_Activity.kt:
215package com.rohit.drwable
216
217import android.support.v7.app.AppCompatActivity
218import android.os.Bundle
219
220class MainActivity : AppCompatActivity() {
221
222 override fun onCreate(savedInstanceState: Bundle?) {
223 super.onCreate(savedInstanceState)
224 setContentView(R.layout.activity_main)
225 }
226}
227
228activity_main.xml:
229<?xml version="1.0" encoding="utf-8"?>
230<LinearLayout
231 xmlns:android="http://schemas.android.com/apk/res/android"
232 xmlns:tools="http://schemas.android.com/tools"
233 xmlns:app="http://schemas.android.com/apk/res-auto"
234 android:layout_width="match_parent"
235 android:layout_height="match_parent"
236 tools:context=".MainActivity"
237 android:background="@drawable/one">
238
239 <TextView
240 android:layout_width="wrap_content"
241 android:layout_height="wrap_content"
242 android:text="Hello World!"
243 app:layout_constraintBottom_toBottomOf="parent"
244 app:layout_constraintLeft_toLeftOf="parent"
245 app:layout_constraintRight_toRightOf="parent"
246 app:layout_constraintTop_toTopOf="parent"/>
247
248</LinearLayout>
249
250
251
252
253############################################################
254
255
256
257
258
259#PRACTICAL No. 3
260#Programming Activities and fragments
261Activity Life Cycle, Activity methods, Multiple
262Activities, Life Cycle of fragments and multiple
263fragments.
264
265Activity Lifecycle:
266
267* onCreate(): Called by the OS when the activity is first
268created. This is where you initialize any UI elements or
269data objects. You also have the savedInstanceState of the
270activity that contains its previously saved state, and
271you can use it to recreate that state.\
272
273fun onCreate(savedInstanceState: Bundle?) {
274 super.onCreate(savedInstanceState)
275 setContentView(R.layout.activity_task_description)
276
277* onStart(): Just before presenting the user with an
278activity, this method is called. It's always followed
279by onResume(). In here, you generally should start UI
280animations, audio based content or anything else that
281requires the activity's contents to be on screen.
282* onResume(): As an activity enters the foreground,
283this method is called. Here you have a good place to
284restart animations, update UI elements, restart camera
285previews, resume audio/video playback or initialize any
286components that you release during onPause().
287* onPause(): This method is called before sliding into
288the background. Here you should stop any visuals or audio
289associated with the activity such as UI animations, music
290playback or the camera. This method is followed by onResume()
291 if the activity returns to the foreground or by onStop()
292 if it becomes hidden.
293
294* onStop(): This method is called right after onPause(),
295 when the activity is no longer visible to the user, and
296 it's a good place to save data that you want to commit to
297 the disk. It's followed by either onRestart(), if this
298 activity is coming back to the foreground, or onDestroy()
299 if it's being released from memory.
300
301* onRestart(): Called after stopping an activity, but
302just before starting it again. It's always followed by
303onStart().
304
305* onDestroy(): This is the final callback you'll receive
306 from the OS before the activity is destroyed. You can
307 trigger an activity's desctruction by calling finish(),
308 or it can be triggered by the system when the system
309 needs to recoup memory. If your activity includes any
310 background threads or other long-running resources,
311 destruction could lead to a memory leak if they're not
312 released, so you need to remember to stop these
313 processes here as well.
314
315EXAMPLE:
316import android.os.Bundle
317import android.support.design.widget.Snackbar
318import android.support.v7.app.AppCompatActivity
319import android.view.Menu
320import android.view.MenuItem
321import android.util.Log
322
323import kotlinx.android.synthetic.main.activity_state_change.*
324
325class StateChangeActivity : AppCompatActivity() {
326
327 val TAG = "StateChange"
328
329 override fun onCreate(savedInstanceState: Bundle?) {
330 super.onCreate(savedInstanceState)
331 setContentView(R.layout.activity_state_change)
332 setSupportActionBar(toolbar)
333
334 fab.setOnClickListener { view ->
335 Snackbar.make(view, "Replace with your own action",
336 Snackbar.LENGTH_LONG)
337 .setAction("Action", null).show()
338 }
339 Log.i(TAG, "onCreate")
340 }
341}
342override fun onStart() {
343 super.onStart()
344 Log.i(TAG, "onStart")
345}
346
347override fun onResume() {
348 super.onResume()
349 Log.i(TAG, "onResume")
350}
351
352override fun onPause() {
353 super.onPause()
354 Log.i(TAG, "onPause")
355}
356
357override fun onStop() {
358 super.onStop()
359 Log.i(TAG, "onStop")
360}
361
362override fun onRestart() {
363 super.onRestart()
364 Log.i(TAG, "onRestart")
365}
366
367override fun onDestroy() {
368 super.onDestroy()
369 Log.i(TAG, "onDestroy")
370}
371
372override fun onSaveInstanceState(outState: Bundle?) {
373 super.onSaveInstanceState(outState)
374 Log.i(TAG, "onSaveInstanceState")
375}
376
377override fun onRestoreInstanceState(savedInstanceState: Bundle?) {
378 super.onRestoreInstanceState(savedInstanceState)
379 Log.i(TAG, "onRestoreInstanceState")
380}
381
382
383Multiple Activities:
384activity_first.xml code:
385<?xml version="1.0" encoding="utf-8"?>
386<RelativeLayout
387xmlns:android="http://schemas.android.com/apk/res/android"
388xmlns:tools="http://schemas.android.com/tools"
389xmlns:app="http://schemas.android.com/apk/res-auto"
390android:layout_width="match_parent"
391android:layout_height="match_parent"
392tools:context="ganeshannt.frist.FristActivity">
393
394<Button
395android:id="@+id/button2"
396android:layout_width="wrap_content"
397android:layout_height="wrap_content"
398android:onClick="Ganesh"
399android:text="click third activity"
400android:textColor="@color/colorPrimary"
401app:layout_constraintTop_toTopOf="parent"
402tools:layout_editor_absoluteX="168dp"
403android:layout_alignParentBottom="true"
404android:layout_toEndOf="@+id/text"
405android:layout_marginBottom="196dp" />
406
407<TextView
408android:layout_width="wrap_content"
409android:layout_height="wrap_content"
410android:text="This s my first app!"
411android:id="@+id/text"
412tools:layout_editor_absoluteY="8dp"
413tools:layout_editor_absoluteX="8dp" />
414<Button
415android:layout_width="wrap_content"
416android:layout_height="wrap_content"
417android:id="@+id/button"
418android:text="click second activity"
419android:textColor="@color/colorPrimary"
420android:onClick="Ganesh"
421tools:layout_editor_absoluteX="168dp"
422app:layout_constraintTop_toTopOf="parent"
423android:layout_above="@+id/button2"
424android:layout_alignStart="@+id/button2"
425android:layout_marginBottom="40dp" />
426
427</RelativeLayout>
428
429activity_second.xml code:
430<?xml version="1.0" encoding="utf-8"?>
431<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
432android:orientation="vertical" android:layout_width="match_parent"
433android:layout_height="match_parent">
434
435<TextView
436android:layout_width="wrap_content"
437android:layout_height="wrap_content"
438android:layout_margin="20pt"
439android:text="second acticity is working...."
440android:textAllCaps="true"
441android:textColor="@color/colorPrimaryDark"/>
442
443</LinearLayout>
444
445activity_third.xml code:
446<?xml version="1.0" encoding="utf-8"?>
447<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
448android:orientation="vertical" android:layout_width="match_parent"
449android:layout_height="match_parent">
450
451<TextView
452android:layout_width="wrap_content"
453android:layout_height="wrap_content"
454android:layout_margin="20pt"
455android:text="Third activity is working ........."
456android:textAllCaps="true"
457android:textColor="@color/colorPrimary"
458/>
459
460</LinearLayout>
461
462Activity_first.kt
463package rohit.technobeat
464
465import android.content.Intent
466import android.support.v7.app.AppCompatActivity
467import android.os.Bundle
468import kotlinx.android.synthetic.main.activity_login.*
469import kotlinx.android.synthetic.main.activity_main.*
470import kotlinx.android.synthetic.main.activity_register.*
471import rohit.technobeat.R.id.login
472import rohit.technobeat.R.id.newaccount
473
474class MainActivity : AppCompatActivity() {
475
476 override fun onCreate(savedInstanceState: Bundle?) {
477 super.onCreate(savedInstanceState)
478 setContentView(R.layout.activity_main)
479 second.setOnClickListener {
480 val intent = Intent(this, Activity_second::class.java)
481 startActivity(intent)
482 }
483
484 third.setOnClickListener {
485 val intent = Intent(this, Activity_third::class.java)
486 startActivity(intent)
487 }
488
489
490 }
491}
492
493
494
495############################################################
496
497
498
499
500
501#PRACTICAL No. 4
502#Programs related to different Layouts
503Coordinate, Linear, Relative, Table,
504Absolute, Frame, List View, Grid View.
505
5061. linear layout:
507<?xml version="1.0" encoding="utf-8"?>
508<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
509android:layout_width="fill_parent"
510android:layout_height="fill_parent"
511android:orientation="vertical" >
512
513<Button android:id="@+id/btnStartService"
514android:layout_width="270dp"
515android:layout_height="wrap_content"
516android:text="start_service"/>
517
518<Button android:id="@+id/btnPauseService"
519android:layout_width="270dp"
520android:layout_height="wrap_content"
521android:text="pause_service"/>
522
523<Button android:id="@+id/btnStopService"
524android:layout_width="270dp"
525android:layout_height="wrap_content"
526android:text="stop_service"/>
527
528</LinearLayout>
529
5302. Relative:
531
532<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
533android:layout_width="fill_parent"
534android:layout_height="fill_parent"
535android:paddingLeft="16dp"
536android:paddingRight="16dp" >
537
538<EditText
539android:id="@+id/name"
540android:layout_width="fill_parent"
541android:layout_height="wrap_content"
542android:hint="@string/reminder" />
543
544<LinearLayout
545android:orientation="vertical"
546android:layout_width="fill_parent"
547android:layout_height="fill_parent"
548android:layout_alignParentStart="true"
549android:layout_below="@+id/name">
550
551<Button
552android:layout_width="wrap_content"
553android:layout_height="wrap_content"
554android:text="New Button"
555android:id="@+id/button" />
556
557<Button
558android:layout_width="wrap_content"
559android:layout_height="wrap_content"
560android:text="New Button"
561android:id="@+id/button2" />
562
563</LinearLayout>
564
565</RelativeLayout>
566
5673. Table:
568Activity_main.xml
569<?xml version="1.0" encoding="utf-8"?>
570<LinearLayout
571 xmlns:android="http://schemas.android.com/apk/res/android"
572 xmlns:tools="http://schemas.android.com/tools"
573 xmlns:app="http://schemas.android.com/apk/res-auto"
574 android:layout_width="match_parent"
575 android:layout_height="match_parent"
576 tools:context=".MainActivity">
577
578 <TableLayout android:layout_width="wrap_content"
579 android:layout_height="wrap_content"
580 android:layout_marginLeft="50dp"
581 android:layout_marginTop="150dp">
582 <TableRow>
583 <Button
584 android:id="@+id/btn1"
585 android:text="1"
586 android:layout_gravity="center"
587 />
588 <Button
589 android:id="@+id/btn2"
590 android:text="2"
591 android:layout_gravity="center"
592 />
593 <Button
594 android:id="@+id/btn3"
595 android:text="3"
596 android:layout_gravity="center"
597 />
598 </TableRow>
599 <TableRow>
600 <Button
601 android:id="@+id/btn4"
602 android:text="4"
603 android:layout_gravity="center"
604 />
605 <Button
606 android:id="@+id/btn5"
607 android:text="5"
608 android:layout_gravity="center"
609 /><Button
610 android:id="@+id/btn6"
611 android:text="6"
612 android:layout_gravity="center"
613 />
614 </TableRow>
615 <TableRow>
616 <Button
617 android:id="@+id/btn7"
618 android:text="7"
619 android:layout_gravity="center"
620 />
621 <Button
622 android:id="@+id/btn8"
623 android:text="8"
624 android:layout_gravity="center"
625 /><Button
626 android:id="@+id/btn9"
627 android:text="9"
628 android:layout_gravity="center"
629 />
630 </TableRow>
631 </TableLayout>
632
633</LinearLayout>
634
635Activity_main.kt
636package com.r.table_view
637import android.support.v7.app.AppCompatActivity
638import android.os.Bundle
639import kotlinx.android.synthetic.main.activity_main.*
640import org.jetbrains.anko.toast
641
642class MainActivity : AppCompatActivity() {
643
644 override fun onCreate(savedInstanceState: Bundle?) {
645 super.onCreate(savedInstanceState)
646 setContentView(R.layout.activity_main)
647
648 btn1.setOnClickListener {
649 toast("1")
650 }
651 btn2.setOnClickListener {
652 toast("2")
653 }
654 btn3.setOnClickListener {
655 toast("3")
656 }
657 btn4.setOnClickListener {
658 toast("4")
659 }
660 btn5.setOnClickListener {
661 toast("5")
662 }
663 btn6.setOnClickListener {
664 toast("6")
665 }
666 btn7.setOnClickListener {
667 toast("7")
668 }
669 btn8.setOnClickListener {
670 toast("8")
671 }
672 btn9.setOnClickListener {
673 toast("9")
674 }
675
676
677 }
678}
679
6804. Frame:
681
682Activity_main.xml
683<?xml version="1.0" encoding="utf-8"?>
684<FrameLayout
685 xmlns:android="http://schemas.android.com/apk/res/android"
686 xmlns:tools="http://schemas.android.com/tools"
687 android:layout_width="match_parent"
688 android:layout_height="match_parent"
689 tools:context=".MainActivity">
690
691 <ImageView android:layout_width="match_parent"
692 android:layout_height="match_parent"
693 android:src="@drawable/red"
694 android:scaleType="centerCrop"/>
695 <TextView
696 android:textSize="100dp"
697 android:layout_width="wrap_content"
698 android:layout_height="wrap_content"
699 android:text="Hello World!"
700 android:gravity="center"
701 android:textColor="@color/rohit"
702 android:layout_marginTop="220dp"
703 />
704
705</FrameLayout>
706
707Activity_main.kt
708
709package com.rohit.frame_layout
710
711import android.support.v7.app.AppCompatActivity
712import android.os.Bundle
713class MainActivity : AppCompatActivity() {
714 override fun onCreate(savedInstanceState: Bundle?) {
715 super.onCreate(savedInstanceState)
716 setContentView(R.layout.activity_main)
717 }
718}
719
7205. List View:
721
722Activity_main.xml
723<?xml version="1.0" encoding="utf-8"?>
724<LinearLayout
725 xmlns:android="http://schemas.android.com/apk/res/android"
726 xmlns:tools="http://schemas.android.com/tools"
727 xmlns:app="http://schemas.android.com/apk/res-auto"
728 android:layout_width="match_parent"
729 android:layout_height="match_parent"
730 tools:context=".MainActivity">
731
732 <Button android:layout_width="wrap_content"
733 android:layout_height="wrap_content"
734 android:id="@+id/btn"
735 android:text="Click me to view list"
736 android:layout_marginTop="200dp"
737 android:layout_marginLeft="90dp"/>
738</LinearLayout>
739
740String.xml
741<resources>
742 <string name="app_name">list</string>
743
744 <array name="insert_list">
745 <item>one</item>
746 <item>two</item>
747 <item>three</item>
748 <item>four</item>
749 <item>five</item>
750 <item>six</item>
751 <item>seven</item>
752 <item>eight</item>
753 <item>nine</item>
754 <item>ten</item>
755 </array>
756</resources>
757
758Activity_list_view.xml:
759<?xml version="1.0" encoding="utf-8"?>
760<ListView
761 xmlns:android="http://schemas.android.com/apk/res/android"
762 xmlns:tools="http://schemas.android.com/tools"
763 xmlns:app="http://schemas.android.com/apk/res-auto"
764 android:layout_width="match_parent"
765 android:layout_height="match_parent"
766 tools:context=".list_view" android:entries="@array/insert_list">
767
768</ListView>
769
770List_view.kt:
771package com.rohit.list
772
773import android.support.v7.app.AppCompatActivity
774import android.os.Bundle
775
776class list_view : AppCompatActivity() {
777
778 override fun onCreate(savedInstanceState: Bundle?) {
779 super.onCreate(savedInstanceState)
780 setContentView(R.layout.activity_list_view)
781 }
782}
783
784main_Activity.kt
785package com.rohit.list
786
787import android.content.Intent
788import android.support.v7.app.AppCompatActivity
789import android.os.Bundle
790import kotlinx.android.synthetic.main.activity_main.*
791
792class MainActivity : AppCompatActivity() {
793
794 override fun onCreate(savedInstanceState: Bundle?) {
795 super.onCreate(savedInstanceState)
796 setContentView(R.layout.activity_main)
797
798 btn.setOnClickListener {
799 val intent =Intent(this, list_view::class.java)
800 startActivity(intent)
801 }
802
803 }
804}
805
8067. <?xml version="1.0" encoding="utf-8"?>
807<GridLayout
808 xmlns:android="http://schemas.android.com/apk/res/android"
809 xmlns:tools="http://schemas.android.com/tools"
810 xmlns:app="http://schemas.android.com/apk/res-auto"
811 android:layout_width="match_parent"
812 android:layout_height="match_parent"
813 tools:context=".MainActivity"
814 android:rowCount="3"
815 android:columnCount="3"
816 android:padding="20dp">
817
818 <Button
819 android:layout_width="110dp"
820 android:layout_height="100dp"
821 android:text="1"/>
822
823 <Button
824 android:layout_width="110dp"
825 android:layout_height="100dp"
826 android:text="2"/>
827 <Button
828 android:layout_width="110dp"
829 android:layout_height="100dp"
830 android:text="3"/>
831 <Button
832 android:layout_width="110dp"
833 android:layout_height="100dp"
834 android:text="4"/>
835
836 <Button
837 android:layout_width="110dp"
838 android:layout_height="100dp"
839 android:text="5"/>
840 <Button
841 android:layout_width="110dp"
842 android:layout_height="100dp"
843 android:text="6"/>
844 <Button
845 android:layout_width="110dp"
846 android:layout_height="100dp"
847 android:text="7"/>
848
849 <Button
850 android:layout_width="110dp"
851 android:layout_height="100dp"
852 android:text="8"/>
853 <Button
854 android:layout_width="110dp"
855 android:layout_height="100dp"
856 android:text="9"/>
857
858</GridLayout>
859
860mainActvity.kt:
861package com.rohit.grid_layout
862
863import android.support.v7.app.AppCompatActivity
864import android.os.Bundle
865
866class MainActivity : AppCompatActivity() {
867
868 override fun onCreate(savedInstanceState: Bundle?) {
869 super.onCreate(savedInstanceState)
870 setContentView(R.layout.activity_main)
871 }
872}
873
874
875###################################################
876
877
878#PRACTICAL No. 5
879#Programming UI elements
880Design App With UI:
881mainActivity.kt:
882package rohit.technobeat
883
884import android.content.Intent
885import android.support.v7.app.AppCompatActivity
886import android.os.Bundle
887import kotlinx.android.synthetic.main.activity_login.*
888import kotlinx.android.synthetic.main.activity_main.*
889import kotlinx.android.synthetic.main.activity_register.*
890import rohit.technobeat.R.id.login
891import rohit.technobeat.R.id.newaccount
892
893class MainActivity : AppCompatActivity() {
894
895 override fun onCreate(savedInstanceState: Bundle?) {
896 super.onCreate(savedInstanceState)
897 setContentView(R.layout.activity_main)
898 login.setOnClickListener {
899 val intent = Intent(this, LoginActivity::class.java)
900 startActivity(intent)
901 }
902 newaccount.setOnClickListener {
903 val intent = Intent(this, RegisterActivity::class.java)
904 startActivity(intent)
905 }
906 }
907}
908
909activity_main.xml
910<?xml version="1.0" encoding="utf-8"?>
911<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
912 xmlns:tools="http://schemas.android.com/tools"
913 android:layout_width="match_parent"
914 android:layout_height="match_parent"
915 android:gravity="center_horizontal"
916 android:orientation="vertical"
917 android:paddingBottom="@dimen/activity_vertical_margin"
918 android:paddingLeft="@dimen/activity_horizontal_margin"
919 android:paddingRight="@dimen/activity_horizontal_margin"
920 android:paddingTop="@dimen/activity_vertical_margin"
921 android:background="@drawable/home"
922 tools:context=".MainActivity">
923
924 <ScrollView
925 android:id="@+id/login_form"
926 android:layout_width="match_parent"
927 android:layout_height="match_parent">
928 <LinearLayout
929 android:layout_width="match_parent"
930 android:layout_height="wrap_content"
931 android:orientation="vertical"
932 android:gravity="center">
933 <android.support.v7.widget.AppCompatTextView
934 android:layout_width="wrap_content"
935 android:layout_height="wrap_content"
936 android:layout_marginTop="210dp"
937 android:alpha="0.7"
938 android:text="TECHNOBEAT"
939 android:textColor="#000000"
940 android:textSize="33dp"
941 android:textStyle="bold"
942 tools:layout_marginLeft="85dp" />
943 <Button
944 android:id="@+id/login"
945 style="?android:textAppearanceSmall"
946 android:layout_width="match_parent"
947 android:layout_height="wrap_content"
948 android:layout_marginTop="16dp"
949 android:text="Login"
950 android:background="@drawable/round_button"
951 android:alpha="0.8"
952 android:textStyle="bold" />
953 <Button
954 android:id="@+id/newaccount"
955 style="?android:textAppearanceSmall"
956 android:layout_width="match_parent"
957 android:layout_height="wrap_content"
958 android:layout_marginTop="16dp"
959 android:text="REGISTER"
960 android:background="@drawable/round_button"
961 android:alpha="0.8"
962 android:textStyle="bold" />
963 </LinearLayout>
964 </ScrollView>
965</LinearLayout>
966
967
968
969###########################################################
970
971
972
973#PRACTICAL No. 6
974#Programming menus, dialog, dialog fragments
975Alert:
976val alertDialog: AlertDialog? = activity?.let {
977 val builder = AlertDialog.Builder(it)
978 builder.apply {
979 setPositiveButton(R.string.ok,
980 DialogInterface.OnClickListener { dialog, id ->
981 })
982 setNegativeButton(R.string.cancel,
983 DialogInterface.OnClickListener { dialog, id ->
984 })
985 }
986 ...
987
988 builder.create()
989}
990
991output:
992
993
994Menu:
995menu.xml:
996<?xml version="1.0? encoding="utf-8??>
997<menu xmlns:android="http://schemas.android.com/apk/res/android”
998xmlns:app="http://schemas.android.com/apk/res-auto">
999
1000<item
1001android:id="@+id/menu_1?
1002android:icon="@drawable/ic_menu_1?
1003android:title="Menu 1?
1004app:showAsAction="always" />
1005
1006<item
1007android:id="@+id/menu_2?
1008android:icon="@drawable/ic_menu_2?
1009android:title="Menu 2? />
1010
1011<item
1012android:id="@+id/menu_3?
1013android:icon="@drawable/ic_menu_3?
1014android:title="Menu 3? />
1015
1016<item
1017android:id="@+id/menu_4?
1018android:icon="@drawable/ic_menu_4?
1019android:title="Menu 4? />
1020
1021</menu>
1022
1023MainActivity.kt:
1024package rohit.com
1025import android.os.Bundle
1026import android.support.v7.app.AppCompatActivity
1027import android.view.Menu
1028import android.view.MenuItem
1029import android.widget.Toast
1030class MainActivity : AppCompatActivity() {
1031 override fun onCreate(savedInstanceState: Bundle?) {
1032 super.onCreate(savedInstanceState)
1033 setContentView(R.layout.activity_main)
1034 }
1035
1036 override fun onCreateOptionsMenu(menu: Menu): Boolean {
1037 menuInflater.inflate(R.menu.main, menu)
1038 return true
1039 }
1040 override fun onOptionsItemSelected(item: MenuItem): Boolean {
1041 when (item.itemId) {
1042 R.id.menu_1 -> {
1043 Toast.makeText(this, "Menu 1 is selected", Toast.LENGTH_SHORT).show()
1044 return true
1045 }
1046 R.id.menu_2 -> {
1047 Toast.makeText(this, "Menu 2 is selected", Toast.LENGTH_SHORT).show()
1048 return true
1049 }
1050 R.id.menu_3 -> {
1051 Toast.makeText(this, "Menu 3 is selected", Toast.LENGTH_SHORT).show()
1052 return true
1053 }
1054 R.id.menu_4 -> {
1055 Toast.makeText(this, "Menu 4 is selected", Toast.LENGTH_SHORT).show()
1056 return true
1057 }
1058 else -> return super.onOptionsItemSelected(item)
1059 }
1060 }
1061}
1062Output:
1063
1064
1065
1066
1067###################################################
1068
1069
1070
1071
1072#PRACTICAL No. 7
1073#Programs on Intents, Events Listeners and Adapters
1074
1075Note: Refer Table layout code for Events Listeners and for Intent GUI code
1076
1077
1078
1079###################################################
1080
1081
1082
1083#PRACTICAL No. 8
1084Programs on Services, notification and broadcast receivers
1085
10861. Programs on Services:
1087Services are commands which are used by kotlin in
1088functions to execute the task. They are :
1089IntentService, onStartCommand(),onHandleIntent() etc.
1090
10912. notification and broadcast receivers:
1092Step 1. Create an android app, For creating an
1093 Android app with kotlin read this tutorial.
1094Step 2. Creating Broadcast Receiver Create and
1095extend Subclass and BroadcastReceiver implement.
1096onReceive(Context, Intent) where onReceive method
1097each message is received as an Intent object parameter.
1098
1099MyReceiver.kt:
1100package `in`.eyehunt.androidbroadcasts
1101import android.content.BroadcastReceiver
1102import android.content.Context
1103import android.content.Intent
1104import android.widget.Toast
1105class MyReceiver : BroadcastReceiver() {
1106 override fun onReceive(context: Context, intent: Intent) {
1107 Toast.makeText(context, "Broadcast : Flight mode changed.",
1108 Toast.LENGTH_LONG).show()
1109 }
1110}
1111
1112Step 3. Declare a broadcast receiver in the manifest
1113file add the element<receiver> in your app's manifest.
1114
1115AndroidManifest.xml:
1116<?xml version="1.0" encoding="utf-8"?>
1117<manifest xmlns:android="http://schemas.android.com/apk/res/android"
1118package="in.eyehunt.androidbroadcasts">
1119
1120<application
1121android:allowBackup="true"
1122android:icon="@mipmap/ic_launcher"
1123android:label="@string/app_name"
1124android:roundIcon="@mipmap/ic_launcher_round"
1125android:supportsRtl="true"
1126android:theme="@style/AppTheme">
1127<activity android:name=".MainActivity">
1128<intent-filter>
1129<action android:name="android.intent.action.MAIN" />
1130
1131<category android:name="android.intent.category.LAUNCHER" />
1132</intent-filter>
1133</activity>
1134
1135<receiver
1136android:name=".MyReceiver"
1137android:enabled="true"
1138android:exported="true">
1139<intent-filter>
1140<action android:name="android.intent.action.AIRPLANE_MODE"/>
1141</intent-filter>
1142</receiver>
1143</application>
1144
1145</manifest>
1146
1147Step 4. MainActivity code, no needs to do anything
1148
1149MainActivity.kt:
1150package `in`.eyehunt.androidbroadcasts
1151
1152import android.support.v7.app.AppCompatActivity
1153import android.os.Bundle
1154
1155class MainActivity : AppCompatActivity() {
1156
1157 override fun onCreate(savedInstanceState: Bundle?) {
1158 super.onCreate(savedInstanceState)
1159 setContentView(R.layout.activity_main)
1160 }
1161}
1162
1163Step 5. Add following code in main_activity.xml
1164add <ImageView> and <TextView>widget layout file.
1165
1166main_activity.xml:
1167<?xml version="1.0" encoding="utf-8"?>
1168<android.support.constraint.ConstraintLayout xmlns:android=
1169"http://schemas.android.com/apk/res/android"
1170xmlns:app="http://schemas.android.com/apk/res-auto"
1171xmlns:tools="http://schemas.android.com/tools"
1172android:layout_width="match_parent"
1173android:layout_height="match_parent"
1174android:background="@color/colorPrimary"
1175tools:context="in.eyehunt.androidbroadcasts.MainActivity">
1176
1177<ImageView
1178android:id="@+id/imageView"
1179android:layout_width="40dp"
1180android:layout_height="40dp"
1181android:layout_margin="8dp"
1182android:layout_marginTop="16dp"
1183app:layout_constraintStart_toStartOf="parent"
1184app:layout_constraintTop_toTopOf="parent"
1185app:srcCompat="@mipmap/baseline_airplanemode_active_white_24" />
1186
1187<TextView
1188android:id="@+id/textView"
1189android:layout_width="300dp"
1190android:layout_height="36dp"
1191android:layout_marginEnd="8dp"
1192android:layout_marginStart="8dp"
1193android:gravity="center_vertical"
1194android:text="Flight Mode"
1195android:textColor="@color/colorWhite"
1196android:textSize="24dp"
1197app:layout_constraintEnd_toEndOf="parent"
1198app:layout_constraintStart_toEndOf="@+id/imageView"
1199app:layout_constraintTop_toTopOf="@+id/imageView" />
1200</android.support.constraint.ConstraintLayout>
1201
1202Output:
1203
1204
1205###############################################
1206
1207
1208
1209#PRACTICAL No. 9
1210#Database Programming with SQLite
1211activity_main.xml:
1212<?xml version="1.0" encoding="utf-8"?>
1213<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
1214xmlns:app="http://schemas.android.com/apk/res-auto"
1215xmlns:tools="http://schemas.android.com/tools"
1216android:layout_width="match_parent"
1217android:layout_height="wrap_content"
1218android:orientation="vertical"
1219android:gravity="center"
1220tools:context="com.tutorialkart.sqlitetutorial.MainActivity">
1221
1222<TextView
1223android:layout_width="wrap_content"
1224android:layout_height="wrap_content"
1225android:text="SQLite Tutorial - User Management"
1226android:textSize="20dp"
1227android:padding="10dp" />
1228
1229<LinearLayout
1230android:layout_width="match_parent"
1231android:layout_height="wrap_content"
1232android:orientation="vertical">
1233<EditText
1234android:id="@+id/edittext_userid"
1235android:hint="User ID"
1236android:gravity="center"
1237android:layout_width="match_parent"
1238android:layout_height="wrap_content" />
1239<EditText
1240android:id="@+id/edittext_name"
1241android:hint="User Name"
1242android:gravity="center"
1243android:layout_width="match_parent"
1244android:layout_height="wrap_content" />
1245<EditText
1246android:id="@+id/edittext_age"
1247android:hint="User Age"
1248android:gravity="center"
1249android:layout_width="match_parent"
1250android:layout_height="wrap_content" />
1251</LinearLayout>
1252
1253<LinearLayout
1254android:layout_width="match_parent"
1255android:layout_height="wrap_content"
1256android:orientation="horizontal">
1257<Button
1258android:id="@+id/button_add_user"
1259android:layout_width="wrap_content"
1260android:layout_height="wrap_content"
1261android:layout_weight="1"
1262android:onClick="addUser"
1263android:text="Add" />
1264
1265<Button
1266android:id="@+id/button_delete_user"
1267android:layout_width="wrap_content"
1268android:layout_height="wrap_content"
1269android:layout_weight="1"
1270android:onClick="deleteUser"
1271android:text="Delete" />
1272
1273<Button
1274android:id="@+id/button_show_all"
1275android:layout_width="wrap_content"
1276android:layout_height="wrap_content"
1277android:layout_weight="1"
1278android:onClick="showAllUsers"
1279android:text="Show All" />
1280</LinearLayout>
1281<TextView
1282android:id="@+id/textview_result"
1283android:layout_width="match_parent"
1284android:layout_height="wrap_content" />
1285<LinearLayout
1286android:id="@+id/ll_entries"
1287android:padding="15dp"
1288android:orientation="vertical"
1289android:layout_width="match_parent"
1290android:layout_height="wrap_content"></LinearLayout>
1291</LinearLayout>
1292
1293
1294UserModel.kt:
1295package com.tutorialkart.sqlitetutorial
1296
1297class UserModel(val userid: String, val name: String, val age: String)
1298
1299DBContract.kt
1300package com.tutorialkart.sqlitetutorial
1301
1302import android.provider.BaseColumns
1303
1304object DBContract {
1305
1306 /* Inner class that defines the table contents */
1307 class UserEntry : BaseColumns {
1308 companion object {
1309 val TABLE_NAME = "users"
1310 val COLUMN_USER_ID = "userid"
1311 val COLUMN_NAME = "name"
1312 val COLUMN_AGE = "age"
1313 }
1314 }
1315}
1316
1317UserDBHelper.kt:
1318package com.tutorialkart.sqlitetutorial
1319
1320import android.content.ContentValues
1321import android.content.Context
1322import android.database.Cursor
1323import android.database.sqlite.SQLiteConstraintException
1324import android.database.sqlite.SQLiteDatabase
1325import android.database.sqlite.SQLiteException
1326import android.database.sqlite.SQLiteOpenHelper
1327
1328import java.util.ArrayList
1329
1330class UsersDBHelper(context: Context) : SQLiteOpenHelper
1331(context, DATABASE_NAME, null, DATABASE_VERSION) {
1332 override fun onCreate(db: SQLiteDatabase) {
1333 db.execSQL(SQL_CREATE_ENTRIES)
1334 }
1335
1336 override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
1337 db.execSQL(SQL_DELETE_ENTRIES)
1338 onCreate(db)
1339 }
1340
1341 override fun onDowngrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
1342 onUpgrade(db, oldVersion, newVersion)
1343 }
1344
1345 @Throws(SQLiteConstraintException::class)
1346 fun insertUser(user: UserModel): Boolean {
1347 val db = writableDatabase
1348
1349 val values = ContentValues()
1350 values.put(DBContract.UserEntry.COLUMN_USER_ID, user.userid)
1351 values.put(DBContract.UserEntry.COLUMN_NAME, user.name)
1352 values.put(DBContract.UserEntry.COLUMN_AGE, user.age)
1353 val newRowId = db.insert(DBContract.UserEntry.TABLE_NAME, null, values)
1354
1355 return true
1356 }
1357
1358 @Throws(SQLiteConstraintException::class)
1359 fun deleteUser(userid: String): Boolean {
1360 val db = writableDatabase
1361 val selection = DBContract.UserEntry.COLUMN_USER_ID + " LIKE ?"
1362 val selectionArgs = arrayOf(userid)
1363 db.delete(DBContract.UserEntry.TABLE_NAME, selection, selectionArgs)
1364
1365 return true
1366 }
1367
1368 fun readUser(userid: String): ArrayList<UserModel> {
1369 val users = ArrayList<UserModel>()
1370 val db = writableDatabase
1371 var cursor: Cursor? = null
1372 try {
1373 cursor = db.rawQuery("select * from " + DBContract.UserEntry.TABLE_NAME+
1374" WHERE " + DBContract.UserEntry.COLUMN_USER_ID + "='" + userid + "'", null)
1375 } catch (e: SQLiteException) {
1376 db.execSQL(SQL_CREATE_ENTRIES)
1377 return ArrayList()
1378 }
1379
1380 var name: String
1381 var age: String
1382 if (cursor!!.moveToFirst()) {
1383 while (cursor.isAfterLast == false) {
1384 name = cursor.getString(cursor.getColumnIndex
1385 (DBContract.UserEntry.COLUMN_NAME))
1386 age = cursor.getString(cursor.getColumnIndex
1387 (DBContract.UserEntry.COLUMN_AGE))
1388
1389 users.add(UserModel(userid, name, age))
1390 cursor.moveToNext()
1391 }
1392 }
1393 return users
1394 }
1395
1396 fun readAllUsers(): ArrayList<UserModel> {
1397 val users = ArrayList<UserModel>()
1398 val db = writableDatabase
1399 var cursor: Cursor? = null
1400 try {
1401 cursor = db.rawQuery("select * from " +
1402 DBContract.UserEntry.TABLE_NAME, null)
1403 } catch (e: SQLiteException) {
1404 db.execSQL(SQL_CREATE_ENTRIES)
1405 return ArrayList()
1406 }
1407
1408 var userid: String
1409 var name: String
1410 var age: String
1411 if (cursor!!.moveToFirst()) {
1412 while (cursor.isAfterLast == false) {
1413 userid = cursor.getString(cursor.getColumnIndex
1414 (DBContract.UserEntry.COLUMN_USER_ID))
1415 name = cursor.getString(cursor.getColumnIndex
1416 (DBContract.UserEntry.COLUMN_NAME))
1417 age = cursor.getString(cursor.getColumnIndex
1418 (DBContract.UserEntry.COLUMN_AGE))
1419
1420 users.add(UserModel(userid, name, age))
1421 cursor.moveToNext()
1422 }
1423 }
1424 return users
1425 }
1426
1427 companion object {
1428 val DATABASE_VERSION = 1
1429 val DATABASE_NAME = "FeedReader.db"
1430
1431 private val SQL_CREATE_ENTRIES =
1432 "CREATE TABLE " + DBContract.UserEntry.TABLE_NAME + " (" +
1433 DBContract.UserEntry.COLUMN_USER_ID +
1434 " TEXT PRIMARY KEY," +
1435 DBContract.UserEntry.COLUMN_NAME + " TEXT," +
1436 DBContract.UserEntry.COLUMN_AGE + " TEXT)"
1437
1438 private val SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS" +
1439 DBContract.UserEntry.TABLE_NAME
1440 }
1441
1442}
1443
1444MainActivity.kt:
1445package com.tutorialkart.sqlitetutorial
1446
1447import android.support.v7.app.AppCompatActivity
1448import android.os.Bundle
1449import android.view.View
1450import android.widget.TextView
1451import kotlinx.android.synthetic.main.activity_main.*
1452
1453class MainActivity : AppCompatActivity() {
1454
1455 lateinit var usersDBHelper : UsersDBHelper
1456
1457 override fun onCreate(savedInstanceState: Bundle?) {
1458 super.onCreate(savedInstanceState)
1459 setContentView(R.layout.activity_main)
1460
1461 usersDBHelper = UsersDBHelper(this)
1462 }
1463
1464 fun addUser(v:View){
1465 var userid = this.edittext_userid.text.toString()
1466 var name = this.edittext_name.text.toString()
1467 var age = this.edittext_age.text.toString()
1468 var result = usersDBHelper.insertUser(UserModel
1469(userid = userid,name = name,age = age))
1470 this.edittext_age.setText("")
1471 this.edittext_name.setText("")
1472 this.edittext_userid.setText("")
1473 this.textview_result.text = "Added user : "+result
1474 this.ll_entries.removeAllViews()
1475 }
1476
1477 fun deleteUser(v:View){
1478 var userid = this.edittext_userid.text.toString()
1479 val result = usersDBHelper.deleteUser(userid)
1480 this.textview_result.text = "Deleted user : "+result
1481 this.ll_entries.removeAllViews()
1482 }
1483
1484 fun showAllUsers(v:View){
1485 var users = usersDBHelper.readAllUsers()
1486 this.ll_entries.removeAllViews()
1487 users.forEach {
1488 var tv_user = TextView(this)
1489 tv_user.textSize = 30F
1490 tv_user.text = it.name.toString() + " - " + it.age.toString()
1491 this.ll_entries.addView(tv_user)
1492 }
1493 this.textview_result.text = "Fetched " + users.size + " users"
1494 }
1495}
1496
1497output:
1498
1499
1500
1501#######################################################
1502
1503
1504
1505
1506#PRACTICAL No. 12
1507#Programming Security and permissions
1508Extra Packages requied in ManagePermission.kt (Class File)
1509import android.app.Activity
1510import android.content.pm.PackageManager
1511import android.support.v4.app.ActivityCompat
1512import android.support.v4.content.ContextCompat
1513import android.support.v7.app.AlertDialog
1514Extra Packages requied in MainActivity.kt
1515import android.Manifest
1516import android.content.Context
1517import android.os.Build
1518import android.widget.Toast
1519import kotlinx.android.synthetic.main.activity_main.*
1520
1521For Multple Permission Access,need to add following
1522line in class MainActivity
1523
1524private val PermissionsRequestCode = 123
1525
15261. Create a new project in android studio
1527
15282. An app must publicize the permissions it requires
1529by including <uses-permission> tags in the app manifest.
1530
1531<uses-permission android:name="android.permission.INTERNET" />
1532<uses-permission android:name="android.permission.CAMERA"/>
1533<uses-permission android:name="android.permission.READ_CONTACTS"/>
1534<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
1535<uses-permission android:name="android.permission.SEND_SMS"/>
1536<uses-permission android:name="android.permission.READ_CALENDAR"/>
1537
1538
1539
15403. MainActivity.kt
1541package com.example.admin.permissionappdemo
1542
1543import android.Manifest
1544import android.content.Context
1545import android.os.Build
1546import android.support.v7.app.AppCompatActivity
1547import android.os.Bundle
1548import android.widget.Toast
1549import kotlinx.android.synthetic.main.activity_main.*
1550
1551
1552class MainActivity : AppCompatActivity() {
1553 private val PermissionsRequestCode = 123
1554 private lateinit var managePermissions: ManagePermissions
1555
1556 override fun onCreate(savedInstanceState: Bundle?) {
1557 super.onCreate(savedInstanceState)
1558 setContentView(R.layout.activity_main)
1559
1560 val list = listOf<String>(
1561 Manifest.permission.CAMERA,
1562 Manifest.permission.READ_CONTACTS,
1563 Manifest.permission.READ_EXTERNAL_STORAGE,
1564 Manifest.permission.SEND_SMS,
1565 Manifest.permission.READ_CALENDAR
1566 )
1567
1568 managePermissions = ManagePermissions(this,list,PermissionsRequestCode)
1569
1570 button.setOnClickListener{
1571 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
1572 managePermissions.checkPermissions()
1573 }
1574 }
1575 override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>,
1576 grantResults: IntArray) {
1577 when (requestCode) {
1578 PermissionsRequestCode ->{
1579 val isPermissionsGranted = managePermissions
1580 .processPermissionsResult(requestCode,permissions,grantResults)
1581
1582 if(isPermissionsGranted){
1583 toast("Permissions granted.")
1584 }else{
1585 toast("Permissions denied.")
1586 }
1587 return
1588 }
1589 }
1590 }
1591}
1592fun Context.toast(message: String) {
1593 Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
1594}
15954. Create a New Kotlin Class
1596app->src->main->java->com.example.admin.permissionappdemo
1597
15985. Write the following code in the Class File
1599import android.app.Activity
1600import android.content.pm.PackageManager
1601import android.support.v4.app.ActivityCompat
1602import android.support.v4.content.ContextCompat
1603import android.support.v7.app.AlertDialog
1604
1605
1606class ManagePermissions(val activity: Activity,val list: List<String>,val code:Int) {
1607
1608 fun checkPermissions() {
1609 if (isPermissionsGranted() != PackageManager.PERMISSION_GRANTED) {
1610 showAlert()
1611 } else {
1612 activity.toast("Permissions already granted.")
1613 }
1614 }
1615 private fun isPermissionsGranted(): Int {
1616 var counter = 0;
1617 for (permission in list) {
1618 counter += ContextCompat.checkSelfPermission(activity, permission)
1619 }
1620 return counter
1621 }
1622 private fun deniedPermission(): String {
1623 for (permission in list) {
1624 if (ContextCompat.checkSelfPermission(activity, permission)
1625 == PackageManager.PERMISSION_DENIED) return permission
1626 }
1627 return ""
1628 }
1629
1630
1631 private fun showAlert() {
1632 val builder = AlertDialog.Builder(activity)
1633 builder.setTitle("Need permission(s)")
1634 builder.setMessage("Some permissions are required to do the task.")
1635 builder.setPositiveButton("OK", { dialog, which -> requestPermissions() })
1636 builder.setNeutralButton("Cancel", null)
1637 val dialog = builder.create()
1638 dialog.show()
1639 }
1640
1641
1642 private fun requestPermissions() {
1643 val permission = deniedPermission()
1644 if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) {
1645 activity.toast("Should show an explanation.")
1646 } else {
1647 ActivityCompat.requestPermissions(activity, list.toTypedArray(), code)
1648 }
1649 }
1650
1651
1652 fun processPermissionsResult(requestCode: Int, permissions: Array<String>,
1653 grantResults: IntArray): Boolean {
1654 var result = 0
1655 if (grantResults.isNotEmpty()) {
1656 for (item in grantResults) {
1657 result += item
1658 }
1659 }
1660 if (result == PackageManager.PERMISSION_GRANTED) return true
1661 return false
1662 }
1663}
1664
1665
1666
1667
1668#########################################################
1669
1670
1671
1672
1673#PRACTICAL No. 13
1674#Programming Network Communications and Services (JSON)
16751. Handling connectivity errors in Android apps with Kotlin:
1676
1677Open your build.gradle file and add the following dependencies:
1678
1679 implementation 'com.android.support:design:27.1.1'
1680 implementation 'com.squareup.retrofit2:retrofit:2.3.0'
1681 implementation 'com.squareup.retrofit2:converter-scalars:2.3.0'
1682
1683Open your AndroidManifest.xml file and add the permissions like so:
1684
1685 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
1686package="com.example.android.internetconnectivity">
1687
1688<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
1689<uses-permission android:name="android.permission.INTERNET"/>
1690
1691[...]
1692
1693</manifest>
1694
1695When there is a network connection, we will fetch data
1696from an API. Let's set up an interface to hold the
1697endpoints we will access. Create a new Kotlin file
1698named ApiService and paste this:
1699import retrofit2.Call
1700import retrofit2.http.GET
1701
1702interface ApiService {
1703 @GET(".")
1704 fun getFeeds(): Call<String>
1705}
1706
1707import android.support.v7.widget.RecyclerView
1708import android.view.LayoutInflater
1709import android.view.View
1710import android.view.ViewGroup
1711import android.widget.TextView
1712
1713class RecyclerAdapter : RecyclerView.Adapter<RecyclerAdapter.ViewHolder>() {
1714
1715 private var list = ArrayList<String>()
1716
1717 fun setItems(newList: ArrayList<String>){
1718 this.list = newList
1719 this.notifyDataSetChanged()
1720 }
1721
1722 override fun getItemCount() = list.size
1723
1724 override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
1725 val view = LayoutInflater.from(parent.context)
1726 .inflate(android.R.layout.simple_list_item_1, parent, false)
1727
1728 return ViewHolder(view)
1729 }
1730
1731 override fun onBindViewHolder(holder: ViewHolder, position: Int) {
1732 holder.textView.text = list[position]
1733 }
1734
1735 inner class ViewHolder(itemView: View?): RecyclerView.ViewHolder(itemView) {
1736 var textView: TextView = itemView!!.findViewById(android.R.id.text1)
1737 }
1738
1739}
1740
1741<?xml version="1.0" encoding="utf-8"?>
1742<android.support.constraint.ConstraintLayout
1743xmlns:android="http://schemas.android.com/apk/res/android"
1744xmlns:app="http://schemas.android.com/apk/res-auto"
1745xmlns:tools="http://schemas.android.com/tools"
1746android:layout_width="match_parent"
1747android:layout_height="match_parent"
1748tools:context=".MainActivity">
1749
1750<android.support.v7.widget.RecyclerView
1751android:layout_width="match_parent"
1752android:layout_height="match_parent"
1753android:id="@+id/recyclerView"
1754app:layout_constraintBottom_toBottomOf="parent"
1755app:layout_constraintLeft_toLeftOf="parent"
1756app:layout_constraintRight_toRightOf="parent"
1757app:layout_constraintTop_toTopOf="parent" />
1758
1759<ImageView
1760android:id="@+id/imageView"
1761android:layout_width="match_parent"
1762android:layout_height="wrap_content"
1763android:src="@drawable/no_internet_connection" />
1764
1765</android.support.constraint.ConstraintLayout>
1766
1767import android.content.BroadcastReceiver
1768import android.content.Context
1769import android.content.Intent
1770import android.content.IntentFilter
1771import android.net.ConnectivityManager
1772import android.support.v7.app.AppCompatActivity
1773import android.os.Bundle
1774import android.support.v7.widget.LinearLayoutManager
1775import android.util.Log
1776import android.view.View
1777import kotlinx.android.synthetic.main.activity_main.*
1778import okhttp3.OkHttpClient
1779import org.json.JSONObject
1780import retrofit2.Call
1781import retrofit2.Callback
1782import retrofit2.Response
1783import retrofit2.Retrofit
1784import retrofit2.converter.scalars.ScalarsConverterFactory
1785
1786class MainActivity : AppCompatActivity() {
1787
1788 private val arrayList = ArrayList<String>()
1789 private val adapter = RecyclerAdapter()
1790 private val retrofit = Retrofit.Builder()
1791 .baseUrl("https://api.reddit.com/")
1792 .addConverterFactory(ScalarsConverterFactory.create())
1793 .client(OkHttpClient.Builder().build())
1794 .build()
1795
1796 private var broadcastReceiver: BroadcastReceiver = object : BroadcastReceiver() {
1797 override fun onReceive(context: Context, intent: Intent) {
1798 val notConnected = intent.getBooleanExtra(ConnectivityManager
1799 .EXTRA_NO_CONNECTIVITY, false)
1800 if (notConnected) {
1801 disconnected()
1802 } else {
1803 connected()
1804 }
1805 }
1806 }
1807
1808 override fun onCreate(savedInstanceState: Bundle?) {
1809 super.onCreate(savedInstanceState)
1810 setContentView(R.layout.activity_main)
1811 setupRecyclerView()
1812 }
1813
1814}
1815
1816arrayList - we will add fetched items to this list.
1817adapter - this is the instance of the adapter class.
1818retrofit - a Retrofit instance.
1819broadcastReciever - this instance implements the
1820onRecieve callback. This callback method is called
1821when the system has notified us of a change in the
1822network connection. In the callback, we then check
1823to know the connectivity status thereby calling either
1824a private connected or disconnected function.
1825MainActivity:
1826
1827override fun onStart() {
1828 super.onStart()
1829 registerReceiver(broadcastReceiver, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION))
1830}
1831
1832override fun onStop() {
1833 super.onStop()
1834 unregisterReceiver(broadcastReceiver)
1835}
1836private fun setupRecyclerView(){
1837 with(recyclerView){
1838 layoutManager = LinearLayoutManager(this@MainActivity)
1839 adapter = this@MainActivity.adapter
1840 }
1841}
1842
1843private fun disconnected() {
1844 recyclerView.visibility = View.INVISIBLE
1845 imageView.visibility = View.VISIBLE
1846}
1847
1848private fun connected() {
1849 recyclerView.visibility = View.VISIBLE
1850 imageView.visibility = View.INVISIBLE
1851 fetchFeeds()
1852}
1853private fun fetchFeeds() {
1854 retrofit.create(ApiService::class.java)
1855 .getFeeds()
1856 .enqueue(object : Callback<String> {
1857 override fun onFailure(call: Call<String>, t: Throwable) {
1858 Log.e("MainActivityTag", t.message)
1859 }
1860 override fun onResponse(call: Call<String>?, response: Response<String>) {
1861 addTitleToList(response.body()!!)
1862 }
1863 })
1864}
1865private fun addTitleToList(response: String) {
1866 val jsonObject = JSONObject(response).getJSONObject("data")
1867 val children = jsonObject.getJSONArray("children")
1868
1869 for (i in 0..(children.length()-1)) {
1870 val item = children.getJSONObject(i).getJSONObject("data").getString("title")
1871 arrayList.add(item)
1872 adapter.setItems(arrayList)
1873 }
1874}