Pages

Tuesday, December 13, 2016

Mengatasi Heap Space Java.lang.OutOfMemoryError pada Saat Run Eclipse

Selamat malam dan salam sejahtera. Ketika saya baru pertama kali belajar bahasa pemrograman android dengan bahasa java, saya juga tidak tahu tentang java heap atau heap space, hingga suatu ketika saya saya menemui error ini java.lang.OutOfMemoryError dan barulah saya menyadari tentang yang disebut Heap Space di dalam Java. Hal seperti ini, saya yakin tidak terjadi hanya pada saya, ataupun anda, namun juga pada sebagian besar programmer.
Belajar bahasa pemrograman memanglah mudah, namun mempelajari konsep dasarnya itu yang sulit, karena memang tidak ada proses formal yang dapat mengajarkan kita dasar-dasar pemrograman. Pengalaman memang guru yang terbaik untuk mengungkap rahasia dari setiap bahasa pemrograman. Untuk seorang java programmer, pengetahuan akan Java Heap, menetapkan berapa ukuran java heap, berurusan dengan error heap space OutOfMemoryError, menganalisis heap dump adalah sangatlah penting. Tutorial Java Heap ini diperuntukkan bagi para pemula yang baru mempelajari bahasa bahasa pemrograman java. Saya akan berusaha untuk memberikan informasi sebanyak mungkin tentang Heap di Java sepanjang pengetahuan saya. Tetapi jika kalian ingin berkontribusi dan berbagi pengetahuan tentang Java Heap, maka hal itu akan membantu kita semua. Apa itu Java Heap Space ?.
Ketika sebuah program Java dimulai, Java Virtual Machine mendapatkan sejumlah memori dari Sistem Operasi. Java Virtual Machine atau disingkat JVM menggunakan memori ini untuk semua kebutuhan. Sebagian dari memori ini disebut memori java heap. Heap di dalam java umumnya terletak ruang alamat paling bawah dan kemudian menaik keatas. Setiap kali kita membuat objek menggunakan operator baru atau dengan yang lain, berarti sebuah object dialokasikan dari memori Heap dan Ketika object tersebut telah mati dan dikumpulkan oleh Garbage collector, maka sejumlah memori ini dikembalikan ke heap space . Ukuran Heap Space Ukuran standar Heap space di Java umumnya adalah 128MB pada sebagian besar JVM Sun 32 bit, namun bisa sangat bervariasi dari satu jenis JVM ke JVM lain. Misalnya maximum heap space dan initial heap untuk Sistem Operasi 32-bit Solaris (Platform SPARC Edition) adalah-Xms = 3670K dan-Xmx = 64M dan nilai-nilai default dari parameter heap space pada sistem 64-bit telah meningkat sampai sekitar 30%. Juga jika Anda menggunakan garbage collector pada Java 1.5 ukuran maximum heap space JVM adalah Memori Fisik / 4 dan ukuran initial heap space adalah sama dengan ukuran Memori fisik/16 .
Cara lain untuk mendapatkan heap space default pada JVM adalah dengan menjalankan aplikasi dengan menggunakan parameter heap default dan memonitor dengan menggunakan JConsole yang tersedia di JDK 1,5 ke atas, pada tab VMSummary kita akan dapat melihat ukuran maximum heap Mulai Java 6 update 18 terdapat perubahan yang signifikan dalam bagaimana JVM menghitung ukuran standar tumpukan dalam mesin 32 dan 64 bit dan pada klien dan server modus JVM yakni, 1) Initial Heap Space dan maximum heap space berukuran menjadi lebih besar untuk meningkatkan kinerja. 2) maximum heap space secara default berukuran 1/2 dari memori fisik yang berukuran hingga 192 byte dan 1/4 dari memori fisik yang berukuran hingga 1GB. Jadi untuk mesin 1 GB, heap space maksimum adalah 256MB. Ukuran maximum heap space tidak akan digunakan hingga program java yang kita buat menciptakan objek yang cukup untuk mengisi initial heap space yang akan jauh lebih rendah setidaknya 8-MB atau 1/64 bagian dari ukuran memori fisik 1GB. 3) untuk Server JVM standar, maximum heap space adalah 1GB untuk memori fisik sebesar 4GB JVM 32-bit. Sedangkan untuk JVM 64 bit, adalah 32GB untuk memori fisik berukuran 128GB. Referensi lebih lengkap silahkan simak : http://www.oracle.com/technetwork/java/javase/6u18-142093.htm
Meningkatakan Heap Space Pada Eclipse Dengan cara Anda dapat meningkatkan ukuran java heap space berdasarkan kebutuhan aplikasi Anda dan saya selalu merekomendasikan hal ini untuk menghindari menggunakan nilai heap JVM default. jika aplikasi Anda besar dan banyak objek dibuat, Anda dapat mengubah ukuran ruang tumpukan dengan menggunakan JVM pilihan-Xms dan-Xmx. Xms menunjukkan ukuran mulai dari Heap sementara-Xmx menunjukkan ukuran maksimum Heap di java. Ada lagi parameter yang disebut-Xmn yang menunjukkan ukuran dari pembangkitan baru java heap space. Hanya hal yang Anda tidak dapat ubah adalah ukuran Heap di Java secara dinamis, Anda hanya dapat memberikan parameter ukuran Java Heap saat memulai JVM. 1) Mengubah File .ini di Eclipse: File .ini dapat ditemukan di folder yang sama dengan file eksekusi Eclipse. Kemudian kita akan melihat beberapa pilihan seperti ini.:
1
2
3
4
5
6
7
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
-vmargs
-Xms40m
-Xmx256m

Tampilan tersebut diatas menunjukkanminimum heap space (-Xms40m) yang diatur ke 40MB dan maximum heap space (-Xmx256m) diatur pada nilai 256MB. Mengubah 256M menjadi nilai yang lebih besar, misalnya 512M akan meningkatkan pasokan heap space pada Eclipse. Ketika saya membuka file .ini tersebut, secara aktual saya menunjukkan maximum heap space yang lebih besar daripada apa yang ditunjukkan dalam program saya. Catatan: untuk memeriksa maximum heap space yang tersedia di Java kita bisa menggunakan baris kode tersebut dalam java:
1
System.out.println(java.lang.Runtime.getRuntime().maxMemory());

Eclipse sebenarnya tidak membatasi heap space saya karena file .Ini yang saya buka barusan menunjukkan nilai maksimal 512MB sementara program saya hanya melaporkan 128MB. Jika ini terjadi, maka kita bisa mencoba cara kedua 2) Memasukkan argumen VM ke JRE kita: ketika Eclipse terbuka, buka Preferences (pada menu Window di Eclipse), kemudian pilih Section Java, klik Installed JREs , klik pada JRE yang digunakan (contoh jre6), klik pada button Edit …, dan masukkan sintaks berikut ke dalam default VM Arguments:
1
-Xms256M -Xmx512M

Format ini mirip dengan apa yang ada dalam file .ini dimana Xms adalah minimum heap space dan Xmx adalah maximum heap space. Masalahnya adalah bahwa JVM membatasi jumlah memori yang tersedia di heap sehingga argumen harus diteruskan ke VM untuk mengubahnya. Perintah-perintah ini dapat dilakukan melalui command line: eclipse [normal arguments] -vmargs -Xmx256M [more VM args]. Selamat mencoba.

Saturday, December 10, 2016

Membuat Sliding Menu Navigation Drawer dengan Android Studio

Selamat siang, apa anda sudah makan siang? jika belum makanlah dulu. kalau sudah makan baru buka android studio dan ikuti postingan ini. Pada tutorial kali ini saya akan membagikan cara membuat sliding menu navigation drawer pada android studio. Pernahkah anda melihat Menu Sliding Navigation drawer ini, pernah, menu ini ada pada aplikasi android antara lain BBM, Google Play Store, Google maps, dll. Pada tutorial ini kita akan membuat menu sliding navigation drawer menggunakan sofware android studio. Jika tidak ada, anda bisa mendownload disini.

 
Untuk membuat menu ini, anda harus mengikuti betul-betul tutorial ini jangan sampai kelewatan langkah-langkahnya. Ok sekarang kita mulai membuat menu sliding navigation drawer. Pertama-tama anda harus membuat project baru dan ikuti langkah dibawah ini. Pada folder res/layout buatlah file xml dengan nama file yang telah saya buat dibawah ini kemudian copy dan paste kan kode tersebut, selanjutnya cek pesan error. Pada file activity_main.xml merupakan file xml layout tapilan awal aplikasi yang akan kita buat.
activity_main.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">
 
    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
 
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />
 
</android.support.v4.widget.DrawerLayout>
Selanjutnya file layout app_bar_main.xml yaitu layout yang akan mengatur tampilan pada menu bar dalam tampilan menu sliding navigation.
app_bar_main.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.mr.navigationdrawer.activity.MainActivity">
 
    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">
 
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />
 
    </android.support.design.widget.AppBarLayout>
 
    <FrameLayout
        android:id="@+id/frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"></FrameLayout>
 
    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:backgroundTint="@color/colorPrimary"
        app:srcCompat="@android:drawable/ic_dialog_email" />
 
</android.support.design.widget.CoordinatorLayout>
Selanjutnya file xml layout nav_header_main.xml, file layout yang mengatur header dari sebuah menu utama aplikasi untuk menampilkan logo aplikasi dan nama aplikasi sendiri.
nav_header_main.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/view_container"
    android:layout_width="match_parent"
    android:layout_height="@dimen/nav_header_height"
    android:gravity="bottom"
    android:orientation="vertical"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">
 
    <ImageView
        android:id="@+id/img_header_bg"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="fitXY"
        android:src="@color/colorPrimary" />
 
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:orientation="vertical"
        android:padding="@dimen/activity_horizontal_margin">
 
        <ImageView
            android:id="@+id/img_profile"
            android:layout_width="@dimen/profile_width"
            android:layout_height="@dimen/profile_height"
            android:paddingTop="@dimen/nav_header_vertical_spacing"
            app:srcCompat="@android:drawable/sym_def_app_icon" />
 
        <TextView
            android:id="@+id/name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingTop="@dimen/nav_header_vertical_spacing"
            android:textAppearance="@style/TextAppearance.AppCompat.Body1" />
 
        <TextView
            android:id="@+id/website"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>
</RelativeLayout>
Selanjutnya file xml menu_dot.xml yang menandai menu dalam titik.
menu_dot.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_vertical"
    android:orientation="vertical">
 
    <LinearLayout
        android:layout_width="6dp"
        android:layout_height="6dp"
        android:background="@drawable/bg_circle"></LinearLayout>
 
</LinearLayout>
Selanjuntya file xml fragment home kita gunakan untuk menaampilan halaman jika di pilih menu home.
fragment_home.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.mr.navigationdrawer.fragment.HomeFragment">
 
    <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_gravity="center"
        android:alpha="0.3"
        android:src="@drawable/ic_home_black_24dp" />
 
</FrameLayout>
Selanjuntya file xml fragment photo kita gunakan untuk menaampilan halaman jika di pilih menu Photo
fragment_photos.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.mr.navigationdrawer.fragment.PhotosFragment">
 
    <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_gravity="center"
        android:alpha="0.3"
        android:src="@drawable/ic_photo_library_black_24dp" />
 
</FrameLayout>
Selanjuntnya pada folder res/menu tambahkan file activity main untuk menambahkan item menu yang akan kita gunakan dalam membuat sliding menu.
activity_main_drawer.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?xml version="1.0" encoding="utf-8"?>
 
    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_home"
            android:icon="@drawable/ic_home_black_24dp"
            android:title="@string/nav_home" />
        <item
            android:id="@+id/nav_photos"
            android:icon="@drawable/ic_photo_library_black_24dp"
            android:title="@string/nav_photos" />
        <item
            android:id="@+id/nav_movies"
            android:icon="@drawable/ic_local_movies_black_24dp"
            android:title="@string/nav_movies" />
 
        <item
            android:id="@+id/nav_notifications"
            android:icon="@drawable/ic_notifications_black_24dp"
            android:title="@string/nav_notifications" />
 
        <item
            android:id="@+id/nav_settings"
            android:icon="@drawable/ic_settings_black_24dp"
            android:title="@string/nav_settings" />
    </group>
 
    <item android:title="Other">
        <menu>
            <item
                android:id="@+id/nav_about_us"
                android:title="@string/nav_about_us" />
            <item
                android:id="@+id/nav_privacy_policy"
                android:title="@string/privacy_policy" />
        </menu>
    </item>
 
</menu>
Selanjutnya file main.xml ganti coding menjadi sebagai berikut.
1
2
3
4
5
6
7
8
9
<?xml version="1.0" encoding="utf-8"?>
    <item
        android:id="@+id/action_logout"
        android:orderInCategory="100"
        android:title="@string/action_logout"
        app:showAsAction="never" />
</menu>
Selanjuntnya pada folder res/values pada file strings xml anda ubah koding tersebut seperti dibawah ini.
strings.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<resources>
    <string name="app_name">Navigation Drawer</string>
 
    <string name="navigation_drawer_open">Open navigation drawer</string>
    <string name="navigation_drawer_close">Close navigation drawer</string>
    <string name="openDrawer">open_drawer</string>
    <string name="closeDrawer">close_drawer</string>
 
    <!-- Navigation Drawer menu labels -->
    <string name="nav_home">Import</string>
    <string name="nav_photos">Gallery</string>
    <string name="nav_movies">Slideshow</string>
    <string name="nav_notifications">Tools</string>
    <string name="nav_settings">Settings</string>
    <string name="nav_about_us">About Us</string>
 
    <!-- Toolbar titles when navigation menu item is selected -->
    <string-array name="nav_item_activity_titles">
        <item>Import</item>
        <item>Gallery</item>
        <item>Slideshow</item>
        <item>Tools</item>
        <item>Settings</item>
    </string-array>
 
    <string name="activity_title_about_us">About Us</string>
    <string name="activity_title_privacy_policy">Privacy Policy</string>
    <string name="action_clear_all">Clear All</string>
    <string name="action_logout">Logout</string>
    <string name="action_mark_all_read">Mark All as Read</string>
    <string name="privacy_policy">Privacy Policy</string>
</resources>
Selanjunta jika sudah selesai membuat file yang ada di res layout, menu, values, sekarang kita beralih pada folder java yang ada di src/nama_package kemudian buatlah nama file java baru MainActivity.java sebagai aktiviti utama.
MainActivity.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
package com.mr.navigationdrawer.activity;
 
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
 
 
import com.mr.navigationdrawer.R;
import com.mr.navigationdrawer.fragment.HomeFragment;
import com.mr.navigationdrawer.fragment.MoviesFragment;
import com.mr.navigationdrawer.fragment.NotificationsFragment;
import com.mr.navigationdrawer.fragment.PhotosFragment;
import com.mr.navigationdrawer.fragment.SettingsFragment;
 
public class MainActivity extends AppCompatActivity {
 
    private NavigationView navigationView;
    private DrawerLayout drawer;
    private View navHeader;
    private ImageView imgNavHeaderBg, imgProfile;
    private TextView txtName, txtWebsite;
    private Toolbar toolbar;
    private FloatingActionButton fab;
 
    // urls to load navigation header background image
    // and profile image
 
    // index to identify current nav menu item
    public static int navItemIndex = 0;
 
    // tags used to attach the fragments
    private static final String TAG_HOME = "Import";
    private static final String TAG_PHOTOS = "Gallery";
    private static final String TAG_MOVIES = "Slideshow";
    private static final String TAG_NOTIFICATIONS = "Tools";
    private static final String TAG_SETTINGS = "settings";
    public static String CURRENT_TAG = TAG_HOME;
 
    // toolbar titles respected to selected nav menu item
    private String[] activityTitles;
 
    // flag to load home fragment when user presses back key
    private boolean shouldLoadHomeFragOnBackPress = true;
    private Handler mHandler;
 
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
 
        mHandler = new Handler();
 
        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        navigationView = (NavigationView) findViewById(R.id.nav_view);
        fab = (FloatingActionButton) findViewById(R.id.fab);
 
        // Navigation view header
        navHeader = navigationView.getHeaderView(0);
        txtName = (TextView) navHeader.findViewById(R.id.name);
        txtWebsite = (TextView) navHeader.findViewById(R.id.website);
        imgNavHeaderBg = (ImageView) navHeader.findViewById(R.id.img_header_bg);
        imgProfile = (ImageView) navHeader.findViewById(R.id.img_profile);
 
        // load toolbar titles from string resources
        activityTitles = getResources().getStringArray(R.array.nav_item_activity_titles);
 
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
 
        // load nav menu header data
        loadNavHeader();
 
        // initializing navigation menu
        setUpNavigationView();
 
        if (savedInstanceState == null) {
            navItemIndex = 0;
            CURRENT_TAG = TAG_HOME;
            loadHomeFragment();
        }
    }
 
    /***
     * Load navigation menu header information
     * like background image, profile image
     * name, website, notifications action view (dot)
     */
    private void loadNavHeader() {
        // name, website
        txtName.setText("Mr R");
        txtWebsite.setText("www.oplive-mr-r.blogspot.com");
 
 
        // showing dot next to notifications label
        navigationView.getMenu().getItem(3).setActionView(R.layout.menu_dot);
    }
 
    /***
     * Returns respected fragment that user
     * selected from navigation menu
     */
    private void loadHomeFragment() {
        // selecting appropriate nav menu item
        selectNavMenu();
 
        // set toolbar title
        setToolbarTitle();
 
        // if user select the current navigation menu again, don't do anything
        // just close the navigation drawer
        if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
            drawer.closeDrawers();
 
            // show or hide the fab button
            toggleFab();
            return;
        }
 
        // Sometimes, when fragment has huge data, screen seems hanging
        // when switching between navigation menus
        // So using runnable, the fragment is loaded with cross fade effect
        // This effect can be seen in GMail app
        Runnable mPendingRunnable = new Runnable() {
            @Override
            public void run() {
                // update the main content by replacing fragments
                Fragment fragment = getHomeFragment();
                FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
                        android.R.anim.fade_out);
                fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
                fragmentTransaction.commitAllowingStateLoss();
            }
        };
 
        // If mPendingRunnable is not null, then add to the message queue
        if (mPendingRunnable != null) {
            mHandler.post(mPendingRunnable);
        }
 
        // show or hide the fab button
        toggleFab();
 
        //Closing drawer on item click
        drawer.closeDrawers();
 
        // refresh toolbar menu
        invalidateOptionsMenu();
    }
 
    private Fragment getHomeFragment() {
        switch (navItemIndex) {
            case 0:
                // home
                HomeFragment homeFragment = new HomeFragment();
                return homeFragment;
            case 1:
                // photos
                PhotosFragment photosFragment = new PhotosFragment();
                return photosFragment;
            case 2:
                // movies fragment
                MoviesFragment moviesFragment = new MoviesFragment();
                return moviesFragment;
            case 3:
                // notifications fragment
                NotificationsFragment notificationsFragment = new NotificationsFragment();
                return notificationsFragment;
 
            case 4:
                // settings fragment
                SettingsFragment settingsFragment = new SettingsFragment();
                return settingsFragment;
            default:
                return new HomeFragment();
        }
    }
 
    private void setToolbarTitle() {
        getSupportActionBar().setTitle(activityTitles[navItemIndex]);
    }
 
    private void selectNavMenu() {
        navigationView.getMenu().getItem(navItemIndex).setChecked(true);
    }
 
    private void setUpNavigationView() {
        //Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
 
            // This method will trigger on item Click of navigation menu
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {
 
                //Check to see which item was being clicked and perform appropriate action
                switch (menuItem.getItemId()) {
                    //Replacing the main content with ContentFragment Which is our Inbox View;
                    case R.id.home:
                        navItemIndex = 0;
                        CURRENT_TAG = TAG_HOME;
                        break;
                    case R.id.nav_photos:
                        navItemIndex = 1;
                        CURRENT_TAG = TAG_PHOTOS;
                        break;
                    case R.id.nav_movies:
                        navItemIndex = 2;
                        CURRENT_TAG = TAG_MOVIES;
                        break;
                    case R.id.nav_notifications:
                        navItemIndex = 3;
                        CURRENT_TAG = TAG_NOTIFICATIONS;
                        break;
                    case R.id.nav_settings:
                        navItemIndex = 4;
                        CURRENT_TAG = TAG_SETTINGS;
                        break;
                    case R.id.nav_about_us:
                        // launch new intent instead of loading fragment
                        startActivity(new Intent(MainActivity.this, AboutUsActivity.class));
                        drawer.closeDrawers();
                        return true;
                    case R.id.nav_privacy_policy:
                        // launch new intent instead of loading fragment
                        startActivity(new Intent(MainActivity.this, PrivacyPolicyActivity.class));
                        drawer.closeDrawers();
                        return true;
                    default:
                        navItemIndex = 0;
                }
 
                //Checking if the item is in checked state or not, if not make it in checked state
                if (menuItem.isChecked()) {
                    menuItem.setChecked(false);
                } else {
                    menuItem.setChecked(true);
                }
                menuItem.setChecked(true);
 
                loadHomeFragment();
 
                return true;
            }
        });
 
 
        ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.openDrawer, R.string.closeDrawer) {
 
            @Override
            public void onDrawerClosed(View drawerView) {
                // Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
                super.onDrawerClosed(drawerView);
            }
 
            @Override
            public void onDrawerOpened(View drawerView) {
                // Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
                super.onDrawerOpened(drawerView);
            }
        };
 
        //Setting the actionbarToggle to drawer layout
        drawer.setDrawerListener(actionBarDrawerToggle);
 
        //calling sync state is necessary or else your hamburger icon wont show up
        actionBarDrawerToggle.syncState();
    }
 
    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawers();
            return;
        }
 
        // This code loads home fragment when back key is pressed
        // when user is in other fragment than home
        if (shouldLoadHomeFragOnBackPress) {
            // checking if user is on other navigation menu
            // rather than home
            if (navItemIndex != 0) {
                navItemIndex = 0;
                CURRENT_TAG = TAG_HOME;
                loadHomeFragment();
                return;
            }
        }
 
        super.onBackPressed();
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
 
        // show menu only when home fragment is selected
        if (navItemIndex == 0) {
            getMenuInflater().inflate(R.menu.main, menu);
        }
 
        // when fragment is notifications, load the menu created for notifications
        if (navItemIndex == 3) {
            getMenuInflater().inflate(R.menu.notifications, menu);
        }
        return true;
    }
 
    @Override
    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_logout) {
            Toast.makeText(getApplicationContext(), "Logout user!", Toast.LENGTH_LONG).show();
            return true;
        }
 
        // user is in notifications fragment
        // and selected 'Mark all as Read'
        if (id == R.id.action_mark_all_read) {
            Toast.makeText(getApplicationContext(), "All notifications marked as read!", Toast.LENGTH_LONG).show();
        }
 
        // user is in notifications fragment
        // and selected 'Clear All'
        if (id == R.id.action_clear_notifications) {
            Toast.makeText(getApplicationContext(), "Clear all notifications!", Toast.LENGTH_LONG).show();
        }
 
        return super.onOptionsItemSelected(item);
    }
 
    // show or hide the fab
    private void toggleFab() {
        if (navItemIndex == 0)
            fab.show();
        else
            fab.hide();
    }
}
Selanjuntnya buat file baru dengan nama Home fragment untuk menampilkan halaman yang terpilih jika menu yang di pilih home.
HomeFragment.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package com.mr.navigationdrawer.fragment;
 
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
 
import com.mr.navigationdrawer.R;
 
/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link HomeFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
 
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
 
    private OnFragmentInteractionListener mListener;
 
    public HomeFragment() {
        // Required empty public constructor
    }
 
    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment HomeFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static HomeFragment newInstance(String param1, String param2) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }
 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_home, container, false);
    }
 
    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }
 
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
//        if (context instanceof OnFragmentInteractionListener) {
//            mListener = (OnFragmentInteractionListener) context;
//        } else {
//            throw new RuntimeException(context.toString()
//                    + " must implement OnFragmentInteractionListener");
//        }
    }
 
    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }
 
    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
Sama halnya dengan home fragment file java ini akan menampilkan halaman yang muncul jika di pilih menu photo.
PhotoFragment.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package com.mr.navigationdrawer.fragment;
 
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
 
import com.mr.navigationdrawer.R;
 
/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link PhotosFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link PhotosFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class PhotosFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
 
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
 
    private OnFragmentInteractionListener mListener;
 
    public PhotosFragment() {
        // Required empty public constructor
    }
 
    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment PhotosFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static PhotosFragment newInstance(String param1, String param2) {
        PhotosFragment fragment = new PhotosFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }
 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_photos, container, false);
    }
 
    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }
 
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
//        if (context instanceof OnFragmentInteractionListener) {
//            mListener = (OnFragmentInteractionListener) context;
//        } else {
//            throw new RuntimeException(context.toString()
//                    + " must implement OnFragmentInteractionListener");
//        }
    }
 
    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }
 
    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
Selanjunnya ini saatnya anda menjalankan aplikasi yang telah dibuat. anda harus mengubah file build.gradle menjadi seperti di bawah ini. Pada langkah ini anda akan kadang-kadang mengalami kesulitan untuk menjalan kan gradle.
1
2
3
4
5
6
7
8
9
10
11
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
 
    compile 'com.android.support:appcompat-v7:24.0.0-beta1'
    compile 'com.android.support:design:24.0.0-beta1'
    compile 'com.android.support:support-v4:24.0.0-beta1'
    testCompile 'junit:junit:4.12'
}

Jika gradle success dan tidak ada error, maka aplikasi akan berjalan lancar seperti yang kita harapkan. pada tutorial ini saya telah berhasih membuat menu sliding navigation drawer. jika saya berhasil kenapa anda tidak? OK demikian sedikit tutorial mengenai cara membuat menu sliding navigation drawer pada android studio.sampai jumpa...

     
Demikianlah Tutorial cara membuat menu sliding navigation drawer pada android studio.

Thursday, December 8, 2016

Tutorial Cara Membuat Menu Navigation Drawer pada Aplikasi Android dengan Eclipse

Selamat siang... panasnya siang ini seakan akan membakar apa yang ada dibumi. bertemankan sebuah laptop dan kipas angin pada siang yang berbahagia ini saya akan membagikan cara membuat menu navigation drawer pada aplikasi android. Menu ini biasa kita temukan pada aplikasi-aplikasi android seperti Gmail, Yahoo, dsb.


Baiklah tanpa memperpanjang mukadimah lagi langsung saja kita mulai. Pertama-tama anda harus membuat project baru dengan nama terserah anda. Pada folder res/layout buatlah file xml layout seperti koding dibawah ini.
activity_main.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
 
    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="wrap_content"
        android:layout_height="match_parent" >
    </FrameLayout>
 
    <ListView
        android:id="@+id/slider_list"
        android:layout_width="240dp"
        android:layout_height="wrap_content"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp" />
 
</android.support.v4.widget.DrawerLayout>

list_item.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="69dp"
    android:background="#1f2021" >
 
    <ImageView
        android:id="@+id/icon"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="2dp"
        android:layout_marginRight="2dp"
        android:contentDescription="desc" />
 
    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@+id/icon"
        android:gravity="center_vertical"
        android:height="40dp" />
 
</RelativeLayout>

home.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
 
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="home"
        android:textAppearance="?android:attr/textAppearanceLarge" />
 
</RelativeLayout>

profil.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
 
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Profil"
        android:textAppearance="?android:attr/textAppearanceLarge" />
 
</RelativeLayout>

visimisi.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
 
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Visi Misi"
        android:textAppearance="?android:attr/textAppearanceLarge" />
 
</RelativeLayout>

Setelah selesai membuat layout, saatnya membuat file java di src/namapackage. Buatlah file java seperti dibawah ini.
MainActivity.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
package com.stmik.promo;
 
import java.util.ArrayList;
import java.util.List;
 
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
 
import com.stmik.promo.cont.Home;
import com.stmik.promo.cont.Profil;
import com.stmik.promo.cont.Visi;
 
public class MainActivity extends Activity {
 
    String[] menutitles;
    TypedArray menuIcons;
 
    // nav drawer title
    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
 
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;
 
    private List<RowItem> rowItems;
    private CustomAdapter adapter;
 
    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        mTitle = mDrawerTitle = getTitle();
 
        menutitles = getResources().getStringArray(R.array.titles);
        menuIcons = getResources().obtainTypedArray(R.array.icons);
 
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.slider_list);
 
        rowItems = new ArrayList<RowItem>();
 
        for (int i = 0; i < menutitles.length; i++) {
            RowItem items = new RowItem(menutitles[i], menuIcons.getResourceId(
                    i, -1));
            rowItems.add(items);
        }
 
        menuIcons.recycle();
 
        adapter = new CustomAdapter(getApplicationContext(), rowItems);
 
        mDrawerList.setAdapter(adapter);
        mDrawerList.setOnItemClickListener(new SlideitemListener());
 
        // enabling action bar app icon and behaving it as toggle button
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);
        // getActionBar().setBackgroundDrawable(new
        // ColorDrawable(R.color.lime));
        // getActionBar().setBackgroundDrawable(new
        // ColorDrawable(Color.parseColor("#ffffff")));
 
        getActionBar().setBackgroundDrawable(
                getResources().getDrawable(R.drawable.header));
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_drawer, // nav menu toggle icon
                R.string.app_name, // nav drawer open - description for
                R.string.app_name // nav drawer close - description for
        // accessibility
        ) {
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                // calling onPrepareOptionsMenu() to show action bar icons
                invalidateOptionsMenu();
            }
 
            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(mDrawerTitle);
                // calling onPrepareOptionsMenu() to hide action bar icons
                invalidateOptionsMenu();
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);
 
        if (savedInstanceState == null) {
            // on first time display view for first nav item
            updateDisplay(0);
        }
    }
 
    class SlideitemListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            updateDisplay(position);
        }
 
    }
 
    private void updateDisplay(int position) {
        Fragment fragment = null;
        switch (position) {
        case 0:
            fragment = new Home();
            break;
        case 1:
            fragment = new Profil();
            break;
        case 2:
            fragment = new Visi();
            break;
        default:
            break;
        }
 
        if (fragment != null) {
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.frame_container, fragment).commit();
 
            // update selected item and title, then close the drawer
            setTitle(menutitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            // error in creating fragment
            Log.e("MainActivity", "Error in creating fragment");
        }
 
    }
 
    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getActionBar().setTitle(mTitle);
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return true;
    }
 
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // toggle nav drawer on selecting action bar app icon/title
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
 
        return super.onOptionsItemSelected(item);
 
    }
 
    /***
     * Called when invalidateOptionsMenu() is triggered
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // if nav drawer is opened, hide the action items
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        // menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }
 
    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */
 
    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }
 
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }
 
}

CustonAdapter.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.stmik.promo;
 
import java.util.List;
 
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
 
public class CustomAdapter extends BaseAdapter {
 
    Context context;
    List<RowItem> rowItem;
 
    CustomAdapter(Context context, List<RowItem> rowItem) {
        this.context = context;
        this.rowItem = rowItem;
    }
 
    private class ViewHolder {
        ImageView icon;
        TextView title;
    }
 
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
 
        ViewHolder holder = null;
 
        LayoutInflater mInflater = (LayoutInflater) context
                .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.list_item, null);
            holder = new ViewHolder();
            holder.icon = (ImageView) convertView.findViewById(R.id.icon);
            holder.title = (TextView) convertView.findViewById(R.id.title);
            RowItem row_pos = rowItem.get(position);
            holder.icon.setImageResource(row_pos.getIcon());
            holder.title.setText(row_pos.getTitle());
            convertView.setTag(holder);
 
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
 
        return convertView;
 
    }
 
    @Override
    public int getCount() {
        return rowItem.size();
    }
 
    @Override
    public Object getItem(int position) {
        return rowItem.get(position);
    }
 
    @Override
    public long getItemId(int position) {
        return rowItem.indexOf(getItem(position));
    }
 
}

RowItem.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.stmik.promo;
 
public class RowItem {
 
    private String title;
    private int icon;
 
    public RowItem(String title, int icon) {
        this.title = title;
        this.icon = icon;
 
    }
 
    public String getTitle() {
        return title;
    }
 
    public void setTitle(String title) {
        this.title = title;
    }
 
    public int getIcon() {
        return icon;
    }
 
    public void setIcon(int icon) {
        this.icon = icon;
    }
 
}

Home.java, Profil.java, dan Visi.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.stmik.promo.cont;
 
import com.stmik.promo.R;
 
import android.annotation.SuppressLint;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
 
@SuppressLint("NewApi")
public class Home extends Fragment {
 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.home, container, false);
 
        return rootView;
    }
 
}
Hasilnya seperti berikut.

Wednesday, December 7, 2016

Membuat Kode Transaksi Otomatis menggunakan Pemograman PHP

Selamat sore.... sudah lama tidak posting, kali ini saya akan membagikan cara membuat kode otomatis pada kode primary key yang kita gunakan seperti kode transaksi, dan kode faktur lainnya. Kode otomatis ini akan secara otomatis, saya membuat kode otomatis dengan format P0001 dst, setelah proses penyimpanan di database dilakukan.Pertama buatlah database, kemudian buat tabel di database seperti dibawah ini.

Buat file php lalu simpan di htdoc
testing.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<a href="https://www.blogger.com/blogger.g?blogID=8703675925861192611" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"></a><a href="https://www.blogger.com/blogger.g?blogID=" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"></a><?php
mysql_connect('localhost','root','');
  mysql_select_db('kode');
  ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
 
</head>
 
<body>
<form action="" method="post">
<table class="form" width="500" border="0" align="center">
  <tr>
    <td colspan="3" align="center"><h2><strong> Kode OTOMATIS</strong></h2></td>
  </tr>
  <tr>
    <td>Kode Penumpang</td>
    <td>:</td>
    <td><input name="kp" type="text" size="5" maxlength="5" id="kp" value="<?php
  
 $h=mysql_query("select *from kode");
 if (mysql_num_rows($h)>0){
   $k=mysql_query("SELECT CONCAT( 'P' ,LPAD(( RIGHT( MAX(kode),4)+1),4,'0')) as kod FROM kode");
   $dk=mysql_fetch_array($k);
   echo $dk[0];
 } else {
  echo "P0001";
 }
 ?>" readonly="readonly" /></td>
  </tr>
 
   <tr>
    <td>Nama Penumpang</td>
    <td>:</td>
    <td><input name="nama" type="text" size="20" maxlength="20" id="kp" /></td>
  </tr>
   <tr>
    <td></td>
    <td></td>
    <td><input name="simpan" type="submit" /></td>
  </tr>
</table>
</form>
 
<?php
if (isset($_POST['simpan'])){
  mysql_query("insert into kode values ('$_POST[kp]','$_POST[nama]')");
  echo "<meta http-equiv='refresh' content='0 url=testing.php' />";
 
}
?>
</body>
</html>
Maka hasilnya

Membuat Aplikasi Android CRUD (Create Read Update Delete) Database SQLite

Selamat siang, siang ini perut lapar belum makan, teringat tadi malam makan roti canai makin lapar saja perut ni. Pada hari ini saya akan membagikan tutorial membuat aplikasi crud sederhana menggunakan database sqlite. tentukan anda yang masih pemula belum tahu bagaimana cara membuat aplikasi crud tersebut. Ayo kita ikuti cara-cara dibawah ini yang telah saya sajikan.
Pertama-tama dan yang paling utama buatlah project baru dengan nama terserah anda dan nama package com.example.dbs. Kemudian pada folder res/layout buat file xml baru seperti dibawah ini.
add_update_screen.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/wall"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
 
    <TextView
        android:id="@+id/alamattext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/namatext"
        android:layout_below="@+id/alamat"
        android:layout_marginTop="29dp"
        android:text="JENIS KELAMIN"
        android:textColor="#ff0000"
        android:textStyle="bold" />
 
    <TextView
        android:id="@+id/textnim1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/nim"
        android:layout_alignBottom="@+id/nim"
        android:layout_alignParentLeft="true"
        android:text="NPM"
        android:textColor="#ff0000"
        android:textStyle="bold" />
 
    <TextView
        android:id="@+id/nimtext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textnim1"
        android:layout_below="@+id/nim"
        android:layout_marginTop="14dp"
        android:text="NAMA"
        android:textColor="#ff0000"
        android:textStyle="bold" />
 
    <EditText
        android:id="@+id/alamat"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/namatext"
        android:layout_alignBottom="@+id/namatext"
        android:layout_alignRight="@+id/nama"
        android:layout_toRightOf="@+id/alamattext"
        android:ems="10"
        android:hint="Alamat"
        android:inputType="textPersonName"
        android:textColor="#000000"
        android:textColorHint="#ffffff" />
 
    <TextView
        android:id="@+id/namatext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/nimtext"
        android:layout_below="@+id/nama"
        android:layout_marginTop="28dp"
        android:text="ALAMAT"
        android:textColor="#ff0000"
        android:textStyle="bold" />
 
    <RadioGroup
        android:id="@+id/sexsex"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/alamat"
        android:layout_alignTop="@+id/alamattext"
        android:layout_toRightOf="@+id/alamattext" >
 
        <RadioButton
            android:id="@+id/radio0"
            android:layout_width="120dp"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="Laki-laki"
            android:textColor="#000000" />
 
        <RadioButton
            android:id="@+id/radio1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Perempuan"
            android:textColor="#000000" />
 
    </RadioGroup>
 
    <EditText
        android:id="@+id/nim"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/nama"
        android:layout_alignParentTop="true"
        android:layout_marginTop="20dp"
        android:ems="10"
        android:hint="Nim"
        android:inputType="textPersonName"
        android:maxLength="13"
        android:textColor="#000000"
        android:textColorHint="#ffffff" >
 
 
        <requestFocus />
         
    </EditText>
 
    <EditText
        android:id="@+id/nama"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/nimtext"
        android:layout_alignBottom="@+id/nimtext"
        android:layout_toRightOf="@+id/alamattext"
        android:ems="10"
        android:hint="Nama"
        android:inputType="textPersonName"
        android:textColor="#000000"
        android:textColorHint="#ffffff" />
 
    <Spinner
        android:id="@+id/agama"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/sexsex"
        android:layout_alignRight="@+id/sexsex"
        android:layout_below="@+id/sexsex"
        android:layout_marginTop="15dp"
        android:entries="@array/agama" />
 
    <Button
        android:id="@+id/tampill"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/simpann"
        android:layout_alignRight="@+id/agama"
        android:layout_alignTop="@+id/button1"
        android:background="#000000"
        android:text="Show"
        android:textColor="#ffffff"
        android:textColorLink="#0000ff" />
 
    <Button
        android:id="@+id/simpann"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView5"
        android:layout_alignParentBottom="true"
        android:layout_toLeftOf="@+id/nim"
        android:background="#000000"
        android:text="Simpan"
        android:textColor="#ffffff"
        android:textColorLink="#0000ff" />
 
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/simpann"
        android:layout_alignLeft="@+id/agama"
        android:layout_alignTop="@+id/simpann"
        android:layout_marginLeft="18dp"
        android:background="#000000"
        android:text="Reset"
        android:textColor="#ffffff" />
 
    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/alamattext"
        android:layout_alignTop="@+id/agama"
        android:text="AGAMA"
        android:textColor="#ff0000"
        android:textStyle="bold" />
 
</RelativeLayout>

listview_row.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <TextView
        android:id="@+id/user_name_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:visibility="gone" />
 
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/www"
        android:orientation="horizontal" >
 
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical" >
 
            <TextView
                android:id="@+id/npm_txt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text=""
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="#0000ff" />
 
            <TextView
                android:id="@+id/nama_txt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text=""
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:textColor="#ffff00" />
 
            <TextView
                android:id="@+id/alamat_txt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text=""
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:textColor="#ff0000" />
 
            <TextView
                android:id="@+id/kelamin_txt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#00ff00" />
 
            <TextView
                android:id="@+id/agama_txt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#996600" />
 
        </LinearLayout>
 
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="right"
            android:orientation="horizontal" >
 
            <Button
                android:id="@+id/btn_update"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="5dp"
                android:background="@drawable/write2"
                android:focusable="false"
                android:focusableInTouchMode="false"
                android:minHeight="50dip"
                android:minWidth="50dip" />
 
            <Button
                android:id="@+id/btn_delete"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="5dp"
                android:background="@drawable/delet"
                android:focusable="false"
                android:focusableInTouchMode="false"
                android:minHeight="50dip"
                android:minWidth="50dip" />
 
        </LinearLayout>
    </LinearLayout>
 
</LinearLayout>

main.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
 
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="#000000"
        android:orientation="horizontal"
        android:weightSum="1" >
 
        <Button
            android:id="@+id/add_btn"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#000000"
            android:clickable="false"
            android:focusable="false"
            android:minWidth="64dp"
            android:text="Tambah Biodata"
            android:textColor="#FFFFFF" />
 
    </LinearLayout>
 
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >
 
        <ListView
            android:id="@+id/list"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:focusable="false"
            android:focusableInTouchMode="false" />
    </LinearLayout>
 
</LinearLayout>

Pada folder values/strings tambahkan koding berikut untuk item spinner agama.
1
2
3
4
5
6
7
<string-array name="agama">
        <item>Islam</item>
        <item>Hindu</item>
        <item>Budha</item>
        <item>Protestan</item>
        <item>Katholik</item>
    </string-array>

Kemudian pada folder src/ buatlah file java baru dengan nama seperti dibawah ini.
Main_Screen.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
package com.example.dbs;
 
import java.util.ArrayList;
 
import com.example.dbs.R;
 
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
 
public class Main_Screen extends Activity {
    Button add_btn;
    ListView Contact_listview;
    ArrayList<Contact> contact_data = new ArrayList<Contact>();
    Contact_Adapter cAdapter;
    DatabaseHandler db;
    String Toast_msg;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);
 try {
     Contact_listview = (ListView) findViewById(R.id.list);
     Contact_listview.setItemsCanFocus(false);
     add_btn = (Button) findViewById(R.id.add_btn);
 
     Set_Referash_Data();
 
 } catch (Exception e) {
     // TODO: handle exception
     Log.e("some error", "" + e);
 }
 add_btn.setOnClickListener(new View.OnClickListener() {
 
     @Override
     public void onClick(View v) {
  // TODO Auto-generated method stub
  Intent add_user = new Intent(Main_Screen.this,Add_Update_User.class);
  add_user.putExtra("called", "Simpan");
  add_user.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
   | Intent.FLAG_ACTIVITY_NEW_TASK);
  startActivity(add_user);
  finish();
     }
 });
 
    }
 
    
    public void Set_Referash_Data() {
 contact_data.clear();
 db = new DatabaseHandler(this);
 ArrayList<Contact> contact_array_from_db = db.Get_Contacts();
 
 for (int i = 0; i < contact_array_from_db.size(); i++) {
 
     int tidno = contact_array_from_db.get(i).getID();
     String npm = contact_array_from_db.get(i).getNpm();
     String nama = contact_array_from_db.get(i).getNama();
     String alamat = contact_array_from_db.get(i).getAlamat();
     String kelamin = contact_array_from_db.get(i).getKelamin();
     String agama = contact_array_from_db.get(i).getAgama();
     Contact cnt = new Contact();
     cnt.setID(tidno);
     cnt.setNpm(npm);
     cnt.setNama(nama);
     cnt.setAlamat(alamat);
     cnt.setKelamin(kelamin);
     cnt.setAgama(agama);
      
      
 
     contact_data.add(cnt);
 }
 db.close();
 cAdapter = new Contact_Adapter(Main_Screen.this, R.layout.listview_row,
  contact_data);
 Contact_listview.setAdapter(cAdapter);
 cAdapter.notifyDataSetChanged();
    }
 
    public void Show_Toast(String msg) {
 Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
    }
 
    @Override
    public void onResume() {
 // TODO Auto-generated method stub
 super.onResume();
 Set_Referash_Data();
 
    }
 
    public class Contact_Adapter extends ArrayAdapter<Contact> {
 Activity activity;
 int layoutResourceId;
 Contact user;
 ArrayList<Contact> data = new ArrayList<Contact>();
 
 public Contact_Adapter(Activity act, int layoutResourceId,
  ArrayList<Contact> data) {
     super(act, layoutResourceId, data);
     this.layoutResourceId = layoutResourceId;
     this.activity = act;
     this.data = data;
     notifyDataSetChanged();
 }
 
 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
     View row = convertView;
     UserHolder holder = null;
 
     if (row == null) {
  LayoutInflater inflater = LayoutInflater.from(activity);
 
  row = inflater.inflate(layoutResourceId, parent, false);
  holder = new UserHolder();
  holder.name = (TextView) row.findViewById(R.id.npm_txt);
  holder.email = (TextView) row.findViewById(R.id.nama_txt);
  holder.number = (TextView) row.findViewById(R.id.alamat_txt);
  holder.kelamn = (TextView) row.findViewById(R.id.kelamin_txt);
  holder.agam = (TextView) row.findViewById(R.id.agama_txt);
  holder.edit = (Button) row.findViewById(R.id.btn_update);
  holder.delete = (Button) row.findViewById(R.id.btn_delete);
  row.setTag(holder);
     } else {
  holder = (UserHolder) row.getTag();
     }
     user = data.get(position);
     holder.edit.setTag(user.getID());
     holder.delete.setTag(user.getID());
     holder.name.setText(user.getNpm());
     holder.email.setText(user.getNama());
  holder.number.setText(user.getAlamat());
  holder.kelamn.setText(user.getKelamin());
  holder.agam.setText(user.getAgama());
 
     holder.edit.setOnClickListener(new OnClickListener() {
 
  @Override
  public void onClick(View v) {
      // TODO Auto-generated method stub
      Log.i("Edit data", "**********");
 
      Intent update_user = new Intent(activity,
       Add_Update_User.class);
      update_user.putExtra("called", "Update");
      update_user.putExtra("USER_ID", v.getTag().toString());
      activity.startActivity(update_user);
 
  }
     });
     holder.delete.setOnClickListener(new OnClickListener() {
 
  @Override
  public void onClick(final View v) {
      // TODO Auto-generated method stub
 
      // show a message while loader is loading
 
      AlertDialog.Builder adb = new AlertDialog.Builder(activity);
      adb.setTitle("Hapus?");
      adb.setMessage("Anda yakin ingin menghapus?");
      final int user_id = Integer.parseInt(v.getTag().toString());
      adb.setNegativeButton("TIDAK", null);
      adb.setPositiveButton("YA",
       new AlertDialog.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog,
     int which) {
        // MyDataObject.remove(positionToRemove);
        DatabaseHandler dBHandler = new DatabaseHandler(
         activity.getApplicationContext());
        dBHandler.Delete_Contact(user_id);
        Main_Screen.this.onResume();
 
    }
       });
      adb.show();
  }
 
     });
     return row;
 
 }
 
 class UserHolder {
     TextView name;
     TextView email;
     TextView number;
     TextView kelamn;
     TextView agam;
     Button edit;
     Button delete;
 }
 
    }
 
}
DatabaseHandler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
package com.example.dbs;
 
import java.util.ArrayList;
 
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
 
public class DatabaseHandler extends SQLiteOpenHelper {
 
    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;
 
    // Database Name
    private static final String DATABASE_NAME = "MISRAL_DB";
 
    // Contacts table name
    private static final String TABLE_BIODATA = "biodata";
 
    // Contacts Table Columns names
    private static final String ID = "id";
    private static final String NPM = "npm";
    private static final String NAMA = "nama";
    private static final String ALAMAT = "alamat";
    private static final String KELAMIN = "kelamin";
    private static final String AGAMA = "agama";
    private final ArrayList<Contact> contact_list = new ArrayList<Contact>();
 
    public DatabaseHandler(Context context) {
 super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
 
    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
 String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_BIODATA + "("
  + ID + " INTEGER PRIMARY KEY," + NPM + " TEXT,"
   + NAMA + " TEXT," + ALAMAT + " TEXT," + KELAMIN + " TEXT," + AGAMA + " TEXT" + " )";
 db.execSQL(CREATE_CONTACTS_TABLE);
    }
 
    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
 // Drop older table if existed
 db.execSQL("DROP TABLE IF EXISTS " + TABLE_BIODATA);
 
 // Create tables again
 onCreate(db);
    }
 
    /**
     * All CRUD(Create, Read, Update, Delete) Operations
     */
 
    // Adding new contact
    public void Add_Contact(Contact contact) {
 SQLiteDatabase db = this.getWritableDatabase();
 ContentValues values = new ContentValues();
 values.put(NPM, contact.getNpm()); // Contact Name
 values.put(NAMA, contact.getNama()); // Contact Phone
 values.put(ALAMAT, contact.getAlamat()); // Contact Email
 values.put(KELAMIN, contact.getKelamin());
 values.put(AGAMA, contact.getAgama());
 // Inserting Row
 db.insert(TABLE_BIODATA, null, values);
 db.close(); // Closing database connection
    }
 
    // Getting single contact
    Contact Get_Contact(int id) {
 SQLiteDatabase db = this.getReadableDatabase();
 
 Cursor cursor = db.query(TABLE_BIODATA, new String[] { ID,
   NPM, NAMA, ALAMAT, KELAMIN, AGAMA }, ID + "=?",
  new String[] { String.valueOf(id) }, null, null, null, null);
 if (cursor != null)
     cursor.moveToFirst();
 
 Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
  cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5));
 // return contact
 cursor.close();
 db.close();
 
 return contact;
    }
 
    // Getting All Contacts
    public ArrayList<Contact> Get_Contacts() {
 try {
     contact_list.clear();
 
     // Select All Query
     String selectQuery = "SELECT  * FROM " + TABLE_BIODATA;
 
     SQLiteDatabase db = this.getWritableDatabase();
     Cursor cursor = db.rawQuery(selectQuery, null);
 
     // looping through all rows and adding to list
     if (cursor.moveToFirst()) {
  do {
      Contact contact = new Contact();
      contact.setID(Integer.parseInt(cursor.getString(0)));
      contact.setNpm(cursor.getString(1));
      contact.setNama(cursor.getString(2));
      contact.setAlamat(cursor.getString(3));
      contact.setKelamin(cursor.getString(4));
      contact.setAgama(cursor.getString(5));
      // Adding contact to list
      contact_list.add(contact);
  } while (cursor.moveToNext());
     }
 
     // return contact list
     cursor.close();
     db.close();
     return contact_list;
 } catch (Exception e) {
     // TODO: handle exception
     Log.e("all_contact", "" + e);
 }
 
 return contact_list;
    }
 
    // Updating single contact
    public int Update_Contact(Contact contact) {
 SQLiteDatabase db = this.getWritableDatabase();
 
 ContentValues values = new ContentValues();
 values.put(NPM, contact.getNpm());
 values.put(NAMA, contact.getNama());
 values.put(ALAMAT, contact.getAlamat());
 values.put(KELAMIN, contact.getKelamin());
 values.put(AGAMA, contact.getAgama());
 
 // updating row
 return db.update(TABLE_BIODATA, values, ID + " = ?",
  new String[] { String.valueOf(contact.getID()) });
    }
 
    // Deleting single contact
    public void Delete_Contact(int id) {
 SQLiteDatabase db = this.getWritableDatabase();
 db.delete(TABLE_BIODATA, ID + " = ?",
  new String[] { String.valueOf(id) });
 db.close();
    }
 
    // Getting contacts Count
    public int Get_Total_Contacts() {
 String countQuery = "SELECT  * FROM " + TABLE_BIODATA;
 SQLiteDatabase db = this.getReadableDatabase();
 Cursor cursor = db.rawQuery(countQuery, null);
 cursor.close();
 
 // return count
 return cursor.getCount();
    }
 
}
Contact.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package com.example.dbs;
 
public class Contact {
 
    // private variables
    public int _id;
    public String _npm;
    public String _nama;
    public String _alamat;
    public String _kelamin;
    public String _agama;
 
    public Contact() {
    }
 
    // constructor
    public Contact(int id, String npm, String _nama, String _alamat, String _kelamin, String _agama) {
 this._id = id;
 this._npm = npm;
 this._nama = _nama;
 this._alamat = _alamat;
 this._kelamin = _kelamin;
 this._agama = _agama;
 
    }
 
    // constructor
    public Contact(String npm, String _nama, String _alamat, String _kelamin, String _agama) {
 this._npm = npm;
 this._nama = _nama;
 this._alamat = _alamat;
 this._kelamin = _kelamin;
 this._agama = _agama;
    }
 
    // getting ID
    public int getID() {
 return this._id;
    }
 
    // setting id
    public void setID(int id) {
 this._id = id;
    }
 
    // getting name
    public String getNpm() {
 return this._npm;
    }
 
    // setting name
    public void setNpm(String npm) {
 this._npm = npm;
    }
 
    // getting phone number
    public String getNama() {
 return this._nama;
    }
 
    // setting phone number
    public void setNama(String _nama) {
 this._nama = _nama;
    }
 
    // getting email
    public String getAlamat() {
 return this._alamat;
    }
 
    // setting email
    public void setAlamat(String alamat) {
 this._alamat = alamat;
    }
 
    public String getKelamin() {
     return this._kelamin;
        }
 
        // setting email
        public void setKelamin(String _kelamin) {
     this._kelamin = _kelamin;
        }
         
        public String getAgama() {
         return this._agama;
            }
 
            // setting email
            public void setAgama(String _agama) {
         this._agama = _agama;
            }
}
Add_Update_User.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
package com.example.dbs;
 
import com.example.dbs.R;
 
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;
 
public class Add_Update_User extends Activity {
    EditText add_npm, add_nama, add_alamat;
    Button add_save_btn, add_view_all, resett;
    Spinner addagama;
    RadioGroup rg;
    RadioButton kelamin,lk,pr;
     
    LinearLayout add_view, update_view;
    String valid_npm = null, valid_alamat = null, valid_nama = null,
     Toast_msg = null, valid_user_id = "", v_kelamin, v_agama;
    int USER_ID;
    DatabaseHandler dbHandler = new DatabaseHandler(this);
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
 // TODO Auto-generated method stub
 super.onCreate(savedInstanceState);
 setContentView(R.layout.add_update_screen);
 add_npm = (EditText) findViewById(R.id.nim);
 add_nama = (EditText) findViewById(R.id.nama);
 add_alamat = (EditText) findViewById(R.id.alamat);
 
 add_save_btn = (Button) findViewById(R.id.simpann);
 resett = (Button) findViewById(R.id.button1);
 add_view_all = (Button) findViewById(R.id.tampill);
 rg=(RadioGroup)findViewById(R.id.sexsex);
 int selectid = rg.getCheckedRadioButtonId();
 kelamin = (RadioButton)findViewById(selectid);
 addagama=(Spinner)findViewById(R.id.agama);
 lk =(RadioButton)findViewById(R.id.radio0);
 pr =(RadioButton)findViewById(R.id.radio1);
 
 // set visibility of view as per calling activity
 String called_from = getIntent().getStringExtra("called");
  
 
 if (called_from.equalsIgnoreCase("Simpan")) {
  Bundle b = getIntent().getExtras();
  String sim = b.getString("called");
  add_save_btn.setText(sim);
   
   
 } else if (called_from.equalsIgnoreCase("Update")) {
  Bundle b = getIntent().getExtras();
  String updt = b.getString("called");
  add_save_btn.setText(updt);
      
     USER_ID = Integer.parseInt(getIntent().getStringExtra("USER_ID"));
 
     Contact c = dbHandler.Get_Contact(USER_ID);
 
     add_npm.setText(c.getNpm());
     add_npm.setText("");
      
     add_nama.setText(c.getNama());
     add_alamat.setText(c.getAlamat());
     String kel= c.getKelamin();
     String agam = c.getAgama();
     add_npm.setText(c.getNpm());
     if (kel.toString().equals("Laki-laki")){
      lk.setChecked(true);
     }else if (kel.toString().equals("Perempuan")){
      pr.setChecked(true);
     }
     if (agam.toString().equals("Islam")){
      addagama.setSelection(0);
     } else  if (agam.toString().equals("Hindu")){
      addagama.setSelection(1);
     } else  if (agam.toString().equals("Budha")){
      addagama.setSelection(2);
     } else  if (agam.toString().equals("Protestan")){
      addagama.setSelection(3);
     } else  if (agam.toString().equals("Katholik")){
      addagama.setSelection(4);
     }
     //dbHandler.close();
 
 }
  
 add_npm.addTextChangedListener(new TextWatcher() {
 
     @Override
     public void onTextChanged(CharSequence s, int start, int before,
      int count) {
  // TODO Auto-generated method stub
 
     }
 
     @Override
     public void beforeTextChanged(CharSequence s, int start, int count,
      int after) {
  // TODO Auto-generated method stub
 
     }
 
     @Override
     public void afterTextChanged(Editable s) {
  // TODO Auto-generated method stub
  // min lenth 10 and max lenth 12 (2 extra for - as per phone
  // matcher format)
  Is_Valid_Sign_Number_Validation(13, 13, add_npm);
     }
 });
  
 resett.setOnClickListener(new View.OnClickListener() {
   
  @Override
  public void onClick(View arg0) {
   // TODO Auto-generated method stub
  Reset_Text();
  add_save_btn.setText("Simpan");
  }
 });
 
 add_save_btn.setOnClickListener(new View.OnClickListener() {
 
     @Override
     public void onClick(View v) {
  // TODO Auto-generated method stub
  // check the value state is null or not
      int selectid = rg.getCheckedRadioButtonId();
      kelamin = (RadioButton)findViewById(selectid);
       
      if (add_save_btn.getText().toString().equals("Update")){
       upDate();
       add_save_btn.setText("Simpan");
      } else if (add_save_btn.getText().toString().equals("Simpan")) {
      if (!add_nama.getText().toString().equals("") && !add_alamat.getText().toString().equals("") && !add_npm.getText().toString().equals("") && valid_npm !=null){
    
      valid_alamat=add_alamat.getText().toString();
   valid_nama=add_nama.getText().toString();
   v_kelamin = kelamin.getText().toString();
   v_agama = String.valueOf(addagama.getSelectedItem());
      dbHandler.Add_Contact(new Contact(valid_npm, valid_nama, valid_alamat, v_kelamin, v_agama ));
      Toast_msg = "Data telah disimpan";
      Show_Toast(Toast_msg);
      Reset_Text();
 
      } else
      {
       Show_Toast("Data belum lengkap");
        
      }
      } else {
       Show_Toast("Maaf,field tidak diketahui.");
       add_save_btn.setText("Simpan");
      }
     }
 });
  
 
 add_view_all.setOnClickListener(new View.OnClickListener() {
 
     @Override
     public void onClick(View v) {
  // TODO Auto-generated method stub
  Intent view_user = new Intent(Add_Update_User.this,
   Main_Screen.class);
  view_user.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
   | Intent.FLAG_ACTIVITY_NEW_TASK);
  startActivity(view_user);
  finish();
     }
 });
 
    }
 
  private void upDate() {
  // TODO Auto-generated method stub
   int selectid = rg.getCheckedRadioButtonId();
   kelamin = (RadioButton)findViewById(selectid);
   valid_alamat=add_alamat.getText().toString();
    valid_nama=add_nama.getText().toString();
  valid_npm=add_npm.getText().toString();
  v_kelamin = kelamin.getText().toString();
  v_agama = String.valueOf(addagama.getSelectedItem());
         dbHandler.Update_Contact(new Contact(USER_ID, valid_npm, valid_nama, valid_alamat, v_kelamin, v_agama));
      dbHandler.close();
      Toast_msg = "Data telah di update";
      Show_Toast(Toast_msg);
      Reset_Text();
    
   
 }
     
    public void Set_Add_Update_Screen() {
 
    }
 
    public void Is_Valid_Sign_Number_Validation(int MinLen, int MaxLen,
     EditText edt) throws NumberFormatException {
 if (edt.getText().toString().length() <= 0) {
     edt.setError("Format NPM 13 digit");
     valid_npm = null;
 } else if (edt.getText().toString().length() < MinLen) {
     edt.setError("Maksimal " + MinLen + " digit");
     valid_npm = null;
 } else if (edt.getText().toString().length() > MaxLen) {
     edt.setError("Maksimal " + MinLen + " digit");
     valid_npm = null;
 } else {
     valid_npm = edt.getText().toString();
 
 }
 
    } // END OF Edittext validation
 
    public void Is_Valid_Email(EditText edt) {
 if (edt.getText().toString() == null) {
     edt.setError("Invalid Email Address");
     valid_alamat = null;
 } else if (isEmailValid(edt.getText().toString()) == false) {
     edt.setError("Invalid Email Address");
     valid_alamat = null;
 } else {
     valid_alamat = edt.getText().toString();
 }
    }
 
    boolean isEmailValid(CharSequence email) {
 return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
    } // end of email matcher
 
     
     
 
    public void Show_Toast(String msg) {
 Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
    }
 
    public void Reset_Text() {
 
 add_npm.getText().clear();
 add_nama.getText().clear();
 add_alamat.getText().clear();
 lk.setChecked(true);
 addagama.setSelection(0);
    }
 
}

Membuat Toast Menampilkan Pesan MessageBox pada Program Android

Selamat pagi dan salam sejahtera. Semoga anda disana di lindungi dan sehat serta bahagia selalu disamping orang tersayang. Pada postingan kali ini, saya akan membagikan tutorial untuk membuat toast atau messagebox yaitu pesan yang muncul beberapa saat dan menghilang di android, ini adalah cara dasar menampilkan toast di android. Okeeyy, langsung aja kita mulai, pertama kali buatlah project baru dengan nama terserah anda. Pada src ubah MainActivity seperti koding dibawah ini.
MainActivity.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.example.test;
 
import org.w3c.dom.Text;
import org.xml.sax.helpers.DefaultHandler;
 
import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
 
public class MainActivity extends Activity {
EditText nim,nama,alamat;
RadioGroup kel;
RadioButton jk;
Spinner agama;
private Button button;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         
        button = (Button)findViewById(R.id.button1);
        nim = (EditText)findViewById(R.id.editText1);
        nama=(EditText)findViewById(R.id.editText2);
        alamat=(EditText)findViewById(R.id.editText3);
        kel=(RadioGroup)findViewById(R.id.radioGroup1);
        agama=(Spinner)findViewById(R.id.spinner1);
        // add button listener
        button.setOnClickListener(new OnClickListener() {
                         
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
            int selectedId = kel.getCheckedRadioButtonId();
            jk=(RadioButton) findViewById(selectedId);
                 Toast.makeText(getApplicationContext(),"NPM : "+ nim.getText()+"\n"+
                 "NAMA : "+nama.getText()+"\n"+"ALAMAT : "+ alamat.getText()+"\n"+
                    "JENIS KELAMIN : "+jk.getText()+
                    "\nAGAMA : "+String.valueOf(agama.getSelectedItem())+"\nData tersimpan...", Toast.LENGTH_LONG).show();
 
            }
        });
 
    }
 
}
Kemudian ubah file activity_main.xml seperti koding dibawah ini.
main_activity.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
 
    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
 
    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView1"
        android:layout_alignBottom="@+id/textView1"
        android:layout_alignLeft="@+id/editText2"
        android:ems="10" >
 
        <requestFocus />
    </EditText>
 
    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText3"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="16dp"
        android:ems="10" />
 
    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/editText2"
        android:layout_alignBottom="@+id/editText2"
        android:layout_alignLeft="@+id/textView1"
        android:text="NAMA" />
 
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView2"
        android:layout_below="@+id/textView2"
        android:layout_marginTop="20dp"
        android:text="NPM" />
 
    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView3"
        android:layout_below="@+id/editText2"
        android:layout_marginTop="22dp"
        android:text="ALAMAT" />
 
    <EditText
        android:id="@+id/editText3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView4"
        android:layout_alignBottom="@+id/textView4"
        android:layout_alignLeft="@+id/radioGroup1"
        android:ems="10" />
 
    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView4"
        android:layout_below="@+id/editText3"
        android:layout_marginTop="26dp"
        android:text="JENIS KELAMIN" />
 
    <TextView
        android:id="@+id/textView6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView5"
        android:layout_alignTop="@+id/spinner1"
        android:layout_marginTop="14dp"
        android:text="AGAMA" />
 
    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/radioGroup1"
        android:layout_below="@+id/radioGroup1"
        android:entries="@array/country_arrays" />
 
    <RadioGroup
        android:id="@+id/radioGroup1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/textView5"
        android:layout_marginLeft="32dp"
        android:layout_toRightOf="@+id/textView5" >
 
        <RadioButton
            android:id="@+id/radio0"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="LAKI-LAKI" />
 
        <RadioButton
            android:id="@+id/radio1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="PEREMPUAN" />
    </RadioGroup>
 
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignRight="@+id/textView5"
        android:layout_marginBottom="30dp"
        android:text="Simpan" />
 
</RelativeLayout