Pada
kesmpatan kali ini kita akan membhasas cara mengkoneksikan projek kita ke
firebase menggunakan firebase assistant, jika anda belum mengenal firebase anda
bisa berkenalan dulu dengan firebase disini, sebenarnya ada du acara untuk
menyambungkan projek android ke firebase yang pertama adalah cara manual jadi
kita perlu mendownload google service .json dan memasukan key SHA1 namun cara
yang pertama ini ribet karena harus mendownload file json dan memindahkanya
pada projek kita jadi yang akan kita bahas kali ini adalah cara yang kedua
menggunakan firebase assistant karena cara ini lebih simple.
Langkah
pertama sambungkan PC/Notebook anda ke internet, pastikan akun google anda
sudah mendaftar ke firebase di https://firebase.google.com/
buka projek
android anda kemudian klik tools lalu pilih Firebase
akan muncul
Firebase Assistant seperti pada gambar -> pilih fitur yang diinginkan
misalnya realtime database, kemudian klik Connect to Firebase
akan muncul
dialog connecting to Firebase, jika anda belum memilih project anda akan
diredirect ke browser untuk login dan membuat project baru di firebase, jika
anda sudah membuat project baru anda akan disuguhkan pilihan untuk memilih
projek mana yang akan disambungkan
jika sudah
dipilih akan muncul tulisan connected warna hijau
sekarang
klik add the realtime database to your app -> kemudian klik accept changes
maka firebase assistant akan menambahkan despendency ke build.gradle secara
otomatis. kemudian gradle akan menyinkronkan secara otomatis, tunggu hingga
sinkronisasi gradle selesai. kemudian akan ada tulisan despendecies set up
correctly sampai disini anda sudah berhasil mengkoneksikan projek android ke
database sekarang anda sudah bisa menggunakan database firebase untuk menyimpan
data aplikasi anda seperti membuat crud. anda juga bisa menambahkan beberapa
layanan firebase lainya seperti authentication atau storage, caranya sama
tinggal klik authentication add firebase authentication to your app ->
accept changes.
pada
postingan selanjutnya kita akan membuat CRUD dengan meggunakan Firebase,
terimakasih sudah berkunjung, jika ada yang kurang jelas silakan tanyakan pada kolom komentar dibawah, jika artikel ini bermanfaat silakan di share
Berkenalan dengan Firebase
Pada
kesempatan kali ini kita akan membahas mengenai firebase, sebelum kita
menggunakanya alangkah baiknya kita mengenal dulu. Apa itu Firebase? Firebase
adalah layanan real time database yang dibuat oleh google. dengan Firebase kita
dimudahkan dalam pengembangan aplikasi kita tidak perlu repot-repot membuat
server database sendiri. kita tinggal focus pada pengembangan aplikasi kita,
karena urusan penyimpanannya kita serahkan pada firebase. Firebase memiliki
layanan yang gratis dan berbayar. untuk pembelajaran kita cukup menggunakan
layanan yang gratis saja, jika layanan yang berbayar harganya tergantung sesuai
pemakaian kita.
Firebase
mendukung fitur realtime database yang memungkinkan kita menyimpan data tanpa
melakukan refresh halaman, firebase ini bekerja secara assynchonous. fitur ini
cocok untuk membuat aplikasi chat, selain itu banyak kelebihan firebase diantaranya
fitur authentikasi yang lengkap, bisa menyimpan file, kita juga bisa membuat
cache pada aplikasi kita jadi jika sedang offline aplikasi kita bisa tetap
menampilkan data.
Firebase
juga bisa digunakan oleh beberpa platform dan Bahasa pemrograman seperti mobile
platform, web/desktop, dan game. untuk mobile firebase bisa digunakan oleh ios
dan android. untuk web firebase bisa dihubungkan dengan angularjs/nodejs untuk
game firebase bisa disandingkan dengan unity dan mendukung Bahasa pemrograman
C++, java, Objective C, karena berbasis API, jadi jika anda sedang
mengembangkan program untuk mobile atau website ataupun game anda bisa
menggunakan firebase untuk databasenya.
Sejarah
Firebase
Sebelum
mebahas firebase lebih jauh mari kita lihat sejarahnya terlebih dahulu, Firebase
bersevolusi dari Envolve, startup yang didirikan oleh James Tamplin dan Andrew
Lee di tahun 2011. Envolve menyediakan pengembang sebuah API yang memungkinkan
integrasi fungsi obrolan online ke dalam situs web mereka. Setelah merilis
layanan obrolan, Tamplin dan Lee menemukan bahwa itu digunakan untuk melewatkan
data aplikasi yang bukan pesan chat. Pengembang menggunakan Envolve untuk
menyinkronkan data aplikasi seperti status game secara real time di seluruh
pengguna mereka. Tamplin dan Lee memutuskan untuk memisahkan sistem obrolan dan
arsitektur real-time yang mendukungnya. Mereka mendirikan Firebase sebagai
perusahaan terpisah pada bulan April 2012.
Firebase
Inc. meningkatkan pendanaan benih pada bulan Mei 2012. Perusahaan tersebut
selanjutnya mengumpulkan dana Seri A pada bulan Juni 2013. Pada bulan Oktober
2014, Firebase diakuisisi oleh Google. Pada bulan Oktober 2015, Google
mengakuisisi Divshot untuk menggabungkannya dengan tim Firebase. Sejak akuisisi
tersebut, Firebase telah berkembang di dalam Google dan memperluas layanan
mereka untuk menjadi platform terpadu bagi pengembang seluler. Firebase sekarang
terintegrasi dengan berbagai layanan Google lainnya untuk menawarkan produk dan
skala yang lebih luas bagi pengembang. Pada bulan Januari 2017, Google
mengakuisisi Fabric dan Crashlytics dari Twitter untuk bergabung dengan layanan
tersebut ke tim Firebase.Menurut laporan tersebut, Firebase akan meluncurkan
Cloud Firestore, Document Database, pada bulan Oktober 2017.
Layanan
yang ada di Firebase
·
Analytics
berfungsi untuk menganisis aplikasi gratis yang memberi wawasan tentang
penggunaan aplikasi dan keterlibatan pengguna
·
Cloud
Messaging
berfungsi untuk mengirimkan pesan dan notifikasi untuk android, ios dan aplikasi
web
·
Authentication
berfungsi untuk mengatur authentikasi pengguna aplikasi kita, fitur
authentikasi di firebase sangat lengkap bisa authentikasi melalui no handphone,
email, google accout, facebook, twitter, github bahkan secara anonymus juga
bisa
·
Realtime
Database
Layanan ini menyediakan pengembang aplikasi API yang memungkinkan data
aplikasi disinkronkan ke klien dan disimpan di awan Firebase
·
Storage
Firebase Storage menyediakan upload dan download file yang aman untuk
aplikasi Firebase, terlepas dari kualitas jaringannya. Pengembang dapat
menggunakannya untuk menyimpan gambar, audio, video, atau konten buatan
pengguna lainnya. Penyimpanan Firebase didukung oleh Google Cloud Storage
·
Remote
Config
Remote Config adalah layanan awan yang memungkinkan pengembang mengubah
perilaku dan tampilan apl mereka tanpa mengharuskan pengguna mengunduh
pembaruan aplikasi
·
Test
Lab
berfungsi untuk mengetes aplikasi kita di perangkat lainya, pengetesanya
pada perangkat asli yang dihosting di google cloud
·
Crash
Reporting
untuk memberi tahu jika aplikasi kita ada yang error/ membuat laporan
rinci tentang kesalahan di aplikasi
·
App
Indexing
untuk mengideks aplikasi kita pada google search
·
Dynamic
Links
membuat link dinamis, seperti shot URL pada aplikasi kita selengkapnya
mengenai dynamic link bisa dilihat pada tautan berikut https://firebase.google.com/docs/dynamic-links/?utm_source=studio
·
Invites
berfungsi untuk mengundang teman melalui sms/ email
·
Admob
berfungsi untuk memasang iklan
admob di aplikasi kita, admob yang dipasang disini merupakan admob yang terintegrasi dengan firebase
Ok,
sekianlah pembahasan mengenai firebase kali ini kedepanya kita akan
menyambungkan projek kita dengan firebase. jika ada yang ditanyakan silakan
tuliskan dikomentar, jika aplikasi ini bermanfaat silakan di share
Membuat Aplikasi CRUD SQLite dengan Content Provider dan Circular Reveal Animation di Android Part4
di part ke3 kita sudah membuat beberapa class untuk menambahkan data, menampilkan data menampilkan details data dan mengedit data. sekarang kita akan menambahkan class Searchable activity untuk fungsi pencarian data CRUD kita
pertama
buat class SearchableActivity dan masukan kode berikut:
package com.giviews.employee;
import android.app.ListActivity;
import android.app.SearchManager;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import com.giviews.employee.data.EmployeeContract;
import java.util.Timer;
import java.util.TimerTask;
/**
* Created by asus on 29/10/2017.
*/
public class SearchableActivity extends ListActivity implements SearchView.OnQueryTextListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
checkIntent(intent);
}
@Override
protected void onNewIntent(Intent newIntent) {
setIntent(newIntent);
checkIntent(newIntent);
}
private void checkIntent(Intent intent) {
String query = "";
String intentAction = intent.getAction();
if (Intent.ACTION_SEARCH.equals(intentAction)) {
query = intent.getStringExtra(SearchManager.QUERY);
} else if (Intent.ACTION_VIEW.equals(intentAction)) {
Uri details = intent.getData();
Intent detailsIntent = new Intent(Intent.ACTION_VIEW, details);
startActivity(detailsIntent);
}
fillList(query);
}
private void fillList(String query) {
String wildcardQuery = "%" + query + "%";
Cursor cursor = getContentResolver().query(
EmployeeContract.EmployeeEntry.CONTENT_URI,
null,
EmployeeContract.EmployeeEntry.COLUMN_FIRSTNAME + " LIKE ? OR " + EmployeeContract.EmployeeEntry.COLUMN_LASTNAME + " LIKE ? OR ",
new String[]{ wildcardQuery, wildcardQuery },
null);
if (cursor.getCount() == 0) {
Toast.makeText(this, " NO SEARCH RESULT ", Toast.LENGTH_SHORT).show();
int timeout = 3000;
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
finish();
Intent intent = new Intent(SearchableActivity.this, EmployeeActivity.class);
startActivity(intent);
}
}, timeout);
}
ListAdapter adapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_2,
cursor,
new String[]{ EmployeeContract.EmployeeEntry.COLUMN_FIRSTNAME, EmployeeContract.EmployeeEntry.COLUMN_LASTNAME },
new int[]{android.R.id.text1, android.R.id.text2},
0);
setListAdapter(adapter);
}
@Override
protected void onListItemClick(ListView l, View view, int position, long id) {
Intent intent = new Intent(SearchableActivity.this, EmployeeActivity.class);
Uri details = Uri.withAppendedPath(EmployeeContract.EmployeeEntry.CONTENT_URI, "" + id);
intent.setData(details);
startActivity(intent);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
Intent parentActivityIntent = new Intent(this, EmployeeActivity.class);
parentActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(parentActivityIntent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
}
import android.app.ListActivity;
import android.app.SearchManager;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import com.giviews.employee.data.EmployeeContract;
import java.util.Timer;
import java.util.TimerTask;
/**
* Created by asus on 29/10/2017.
*/
public class SearchableActivity extends ListActivity implements SearchView.OnQueryTextListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
checkIntent(intent);
}
@Override
protected void onNewIntent(Intent newIntent) {
setIntent(newIntent);
checkIntent(newIntent);
}
private void checkIntent(Intent intent) {
String query = "";
String intentAction = intent.getAction();
if (Intent.ACTION_SEARCH.equals(intentAction)) {
query = intent.getStringExtra(SearchManager.QUERY);
} else if (Intent.ACTION_VIEW.equals(intentAction)) {
Uri details = intent.getData();
Intent detailsIntent = new Intent(Intent.ACTION_VIEW, details);
startActivity(detailsIntent);
}
fillList(query);
}
private void fillList(String query) {
String wildcardQuery = "%" + query + "%";
Cursor cursor = getContentResolver().query(
EmployeeContract.EmployeeEntry.CONTENT_URI,
null,
EmployeeContract.EmployeeEntry.COLUMN_FIRSTNAME + " LIKE ? OR " + EmployeeContract.EmployeeEntry.COLUMN_LASTNAME + " LIKE ? OR ",
new String[]{ wildcardQuery, wildcardQuery },
null);
if (cursor.getCount() == 0) {
Toast.makeText(this, " NO SEARCH RESULT ", Toast.LENGTH_SHORT).show();
int timeout = 3000;
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
finish();
Intent intent = new Intent(SearchableActivity.this, EmployeeActivity.class);
startActivity(intent);
}
}, timeout);
}
ListAdapter adapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_2,
cursor,
new String[]{ EmployeeContract.EmployeeEntry.COLUMN_FIRSTNAME, EmployeeContract.EmployeeEntry.COLUMN_LASTNAME },
new int[]{android.R.id.text1, android.R.id.text2},
0);
setListAdapter(adapter);
}
@Override
protected void onListItemClick(ListView l, View view, int position, long id) {
Intent intent = new Intent(SearchableActivity.this, EmployeeActivity.class);
Uri details = Uri.withAppendedPath(EmployeeContract.EmployeeEntry.CONTENT_URI, "" + id);
intent.setData(details);
startActivity(intent);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
Intent parentActivityIntent = new Intent(this, EmployeeActivity.class);
parentActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(parentActivityIntent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
}
kemudian
buat class SettingsActivity untuk menggati warna thema aplikasi kita, dengan
kode seperti berikut:
package com.giviews.employee; import android.annotation.TargetApi; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Paint; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.OvalShape; import android.os.Build; import android.preference.PreferenceManager; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.Button; import com.turkialkhateeb.materialcolorpicker.ColorChooserDialog; import com.turkialkhateeb.materialcolorpicker.ColorListener; public class SettingsActivity extends AppCompatActivity { SharedPreferences sharedPreferences, app_preperences; SharedPreferences.Editor editor; Button button; Methods methods; int appTheme; int themeColor; int appColor; Constant constant; @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); app_preperences = PreferenceManager.getDefaultSharedPreferences(this); appColor = app_preperences.getInt("color", 0); appTheme = app_preperences.getInt("theme", 0); themeColor = appColor; constant.color = appColor; if (themeColor == 0) { setTheme(Constant.theme); } else if (appTheme == 0) { setTheme(Constant.theme); } else { setTheme(appTheme); } setContentView(R.layout.activity_settings); final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_setting); toolbar.setTitle("Settings"); toolbar.setBackgroundColor(Constant.color); methods = new Methods(); button = (Button) findViewById(R.id.button_color); sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); editor = sharedPreferences.edit(); colorize(); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ColorChooserDialog dialog = new ColorChooserDialog(SettingsActivity.this); dialog.setTitle("Select"); dialog.setColorListener(new ColorListener() { @Override public void OnColorClick(View v, int color) { colorize(); Constant.color = color; methods.setColorTheme(); editor.putInt("color", color); editor.putInt("theme", Constant.theme); editor.commit(); Intent intent = new Intent(getApplicationContext(), EmployeeActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } }); dialog.show(); } }); } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) private void colorize(){ ShapeDrawable d = new ShapeDrawable(new OvalShape()); d.setBounds(58, 58, 58, 58); d.getPaint().setStyle(Paint.Style.FILL); d.getPaint().setColor(Constant.color); button.setBackground(d); } }
kemudian
kita buat class Constant untuk mengganti warna thema aplikasi kita:
package com.giviews.employee; import java.io.Serializable; /** * Created by asus on 05/11/2017. */ public class Constant implements Serializable { public static int nav_clicked = 0; public static Boolean isNavClicked = false; public static Boolean isToggle = true; public static int color = 0xfff67f21; public static int theme = R.style.AppTheme; }
selanjutnya
buat class Methods untuk mengubah warna theme, dengan kode seperti berikut:
package com.giviews.employee; /** * Created by asus on 05/11/2017. */ public class Methods { public void setColorTheme() { switch (Constant.color){ case 0xffF44336: Constant.theme = R.style.AppTheme_red; break; case 0xffE91E63: Constant.theme = R.style.AppTheme_pink; break; case 0xff9C27B0: Constant.theme = R.style.AppTheme_darpink; break; case 0xff673AB7: Constant.theme = R.style.AppTheme_violet; break; case 0xff3F51B5: Constant.theme = R.style.AppTheme_blue; break; case 0xff03A9F4: Constant.theme = R.style.AppTheme_skyblue; break; case 0xff4CAF50: Constant.theme = R.style.AppTheme_green; break; case 0xffFF9800: Constant.theme = R.style.AppTheme; break; case 0xff9E9E9E: Constant.theme = R.style.AppTheme_grey; break; case 0xff795548: Constant.theme = R.style.AppTheme_brown; break; default: Constant.theme = R.style.AppTheme; } } }
Terakhir
sesuaikan AndroidManifest anda seperti berikut:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.giviews.employee"> <uses-feature android:name="android.hardware.camera2"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".EmployeeActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".EmployeeEditor" android:parentActivityName=".EmployeeActivity"> <meta-data android:name="android.support.PARENT_ACTIVITY" android:value=".EmployeeActivity" /> </activity> <!-- Employee Details --> <activity android:name=".EmployeeDetailsActivity" android:parentActivityName=".EmployeeActivity"> <meta-data android:name="android.support.PARENT_ACTIVITY" android:value=".EmployeeActivity" /> </activity> <provider android:name=".data.EmployeeProvider" android:authorities="com.giviews.employee" android:exported="false" /> <!-- searchable --> <activity android:name=".SearchableActivity" android:launchMode="singleTop"> <intent-filter> <action android:name="android.intent.action.SEARCH" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW" /> </intent-filter> <meta-data android:name="android.app.searchable" android:resource="@xml/searchable" /> </activity> <meta-data android:name="android.app.default_searchable" android:value="com.giview.employee.SearchableActivity" /> <activity android:name=".SettingsActivity"></activity> </application> </manifest>
Sekarang
jalankan aplikasi anda, jika ada yang kurang jelas silakan ditanyakan pada
komentar dibawah. jika anda ingin melihat sourcode versi full silakan download disini. jika artikel ini bermanfaat silakan di share, selamat mencoba semoga
bermanfaat kdepanya kita akan membuat CRUD SQLite dengan model dan adapter,
CRUD dengan database firebase, dan CRUD dengan MySQL database
Membuat Aplikasi CRUD SQLite dengan Content Provider dan Circular Reveal Animation di Android Part3
di part ke2 kita sudah membuat beberapa layout antarmuka aplikasi kita sekarang kita tinggal memberikan fungsi pada layout-layout kita tapi sebelum itu kita tambahkan lagi dua buah layout untuk activity_details dan settings_activity
1. buat layout dengan nama activity_employee_details
untuk menampilkan details employee kita, sebagai berikut:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.giviews.employee.EmployeeDetailsActivity">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar_setting"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
android:theme="@style/AppTheme.AppBarOverlay" />
<ScrollView
android:layout_marginTop="60dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/root_layout"
android:layout_width="match_parent"
android:orientation="vertical"
android:padding="16dp"
android:layout_height="match_parent">
<ImageView
android:id="@+id/profileImageView"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_gravity="center"
android:layout_marginBottom="10dp"
android:background="#fff"
android:src="@drawable/ic_account_circle_black"/>
<LinearLayout
android:padding="16dp"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.AppCompatTextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textStyle="bold"
android:textSize="15dp"
android:text="First Name" />
<android.support.v7.widget.AppCompatTextView
android:id="@+id/employee_firstname"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Unknown" />
</LinearLayout>
<LinearLayout
android:padding="16dp"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.AppCompatTextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textSize="15dp"
android:textStyle="bold"
android:layout_weight="1"
android:text="Last Name" />
<android.support.v7.widget.AppCompatTextView
android:id="@+id/employee_lastname"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Unknown" />
</LinearLayout>
<LinearLayout
android:padding="16dp"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.AppCompatTextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="15dp"
android:textStyle="bold"
android:text="Title" />
<android.support.v7.widget.AppCompatTextView
android:id="@+id/employee_title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Unknown" />
</LinearLayout>
<LinearLayout
android:padding="16dp"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.AppCompatTextView
android:layout_width="0dp"
android:textSize="15dp"
android:textStyle="bold"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Department" />
<android.support.v7.widget.AppCompatTextView
android:id="@+id/employee_department"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Unknown" />
</LinearLayout>
<LinearLayout
android:padding="16dp"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.AppCompatTextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="15dp"
android:textStyle="bold"
android:text="City" />
<android.support.v7.widget.AppCompatTextView
android:id="@+id/employee_city"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Unknown" />
</LinearLayout>
<LinearLayout
android:padding="16dp"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.AppCompatTextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="15dp"
android:textStyle="bold"
android:text="Phone" />
<android.support.v7.widget.AppCompatTextView
android:id="@+id/employee_phone"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Unknown" />
</LinearLayout>
<LinearLayout
android:padding="16dp"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.AppCompatTextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="15dp"
android:textStyle="bold"
android:text="Email" />
<android.support.v7.widget.AppCompatTextView
android:id="@+id/employee_email"
android:layout_weight="1"
android:text="Unknown"
android:layout_width="0dp"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:padding="16dp"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.AppCompatTextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textSize="15dp"
android:textStyle="bold"
android:layout_weight="1"
android:text="Gender" />
<android.support.v7.widget.AppCompatTextView
android:id="@+id/employee_gender"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Unknown" />
</LinearLayout>
</LinearLayout>
</ScrollView>
</RelativeLayout>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.giviews.employee.EmployeeDetailsActivity">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar_setting"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
android:theme="@style/AppTheme.AppBarOverlay" />
<ScrollView
android:layout_marginTop="60dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/root_layout"
android:layout_width="match_parent"
android:orientation="vertical"
android:padding="16dp"
android:layout_height="match_parent">
<ImageView
android:id="@+id/profileImageView"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_gravity="center"
android:layout_marginBottom="10dp"
android:background="#fff"
android:src="@drawable/ic_account_circle_black"/>
<LinearLayout
android:padding="16dp"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.AppCompatTextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textStyle="bold"
android:textSize="15dp"
android:text="First Name" />
<android.support.v7.widget.AppCompatTextView
android:id="@+id/employee_firstname"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Unknown" />
</LinearLayout>
<LinearLayout
android:padding="16dp"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.AppCompatTextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textSize="15dp"
android:textStyle="bold"
android:layout_weight="1"
android:text="Last Name" />
<android.support.v7.widget.AppCompatTextView
android:id="@+id/employee_lastname"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Unknown" />
</LinearLayout>
<LinearLayout
android:padding="16dp"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.AppCompatTextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="15dp"
android:textStyle="bold"
android:text="Title" />
<android.support.v7.widget.AppCompatTextView
android:id="@+id/employee_title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Unknown" />
</LinearLayout>
<LinearLayout
android:padding="16dp"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.AppCompatTextView
android:layout_width="0dp"
android:textSize="15dp"
android:textStyle="bold"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Department" />
<android.support.v7.widget.AppCompatTextView
android:id="@+id/employee_department"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Unknown" />
</LinearLayout>
<LinearLayout
android:padding="16dp"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.AppCompatTextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="15dp"
android:textStyle="bold"
android:text="City" />
<android.support.v7.widget.AppCompatTextView
android:id="@+id/employee_city"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Unknown" />
</LinearLayout>
<LinearLayout
android:padding="16dp"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.AppCompatTextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="15dp"
android:textStyle="bold"
android:text="Phone" />
<android.support.v7.widget.AppCompatTextView
android:id="@+id/employee_phone"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Unknown" />
</LinearLayout>
<LinearLayout
android:padding="16dp"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.AppCompatTextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="15dp"
android:textStyle="bold"
android:text="Email" />
<android.support.v7.widget.AppCompatTextView
android:id="@+id/employee_email"
android:layout_weight="1"
android:text="Unknown"
android:layout_width="0dp"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:padding="16dp"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.AppCompatTextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textSize="15dp"
android:textStyle="bold"
android:layout_weight="1"
android:text="Gender" />
<android.support.v7.widget.AppCompatTextView
android:id="@+id/employee_gender"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Unknown" />
</LinearLayout>
</LinearLayout>
</ScrollView>
</RelativeLayout>
2. buat layout dengan nama
activity_settings.xml dengan kode sebagai berikut, activity ini akan digunakan
untuk memilih warna thema pada aplikasi CRUD kita.
3. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.giviews.employee.EmployeeDetailsActivity"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar_setting" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" android:theme="@style/AppTheme.AppBarOverlay" /> <ScrollView android:layout_marginTop="60dp" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:id="@+id/root_layout" android:layout_width="match_parent" android:orientation="vertical" android:padding="16dp" android:layout_height="match_parent"> <ImageView android:id="@+id/profileImageView" android:layout_width="200dp" android:layout_height="200dp" android:layout_gravity="center" android:layout_marginBottom="10dp" android:background="#fff" android:src="@drawable/ic_account_circle_black"/> <LinearLayout android:padding="16dp" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <android.support.v7.widget.AppCompatTextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:textStyle="bold" android:textSize="15dp" android:text="First Name" /> <android.support.v7.widget.AppCompatTextView android:id="@+id/employee_firstname" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Unknown" /> </LinearLayout> <LinearLayout android:padding="16dp" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <android.support.v7.widget.AppCompatTextView android:layout_width="0dp" android:layout_height="wrap_content" android:textSize="15dp" android:textStyle="bold" android:layout_weight="1" android:text="Last Name" /> <android.support.v7.widget.AppCompatTextView android:id="@+id/employee_lastname" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Unknown" /> </LinearLayout> <LinearLayout android:padding="16dp" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <android.support.v7.widget.AppCompatTextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:textSize="15dp" android:textStyle="bold" android:text="Title" /> <android.support.v7.widget.AppCompatTextView android:id="@+id/employee_title" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Unknown" /> </LinearLayout> <LinearLayout android:padding="16dp" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <android.support.v7.widget.AppCompatTextView android:layout_width="0dp" android:textSize="15dp" android:textStyle="bold" android:layout_height="wrap_content" android:layout_weight="1" android:text="Department" /> <android.support.v7.widget.AppCompatTextView android:id="@+id/employee_department" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Unknown" /> </LinearLayout> <LinearLayout android:padding="16dp" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <android.support.v7.widget.AppCompatTextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:textSize="15dp" android:textStyle="bold" android:text="City" /> <android.support.v7.widget.AppCompatTextView android:id="@+id/employee_city" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Unknown" /> </LinearLayout> <LinearLayout android:padding="16dp" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <android.support.v7.widget.AppCompatTextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:textSize="15dp" android:textStyle="bold" android:text="Phone" /> <android.support.v7.widget.AppCompatTextView android:id="@+id/employee_phone" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Unknown" /> </LinearLayout> <LinearLayout android:padding="16dp" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <android.support.v7.widget.AppCompatTextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:textSize="15dp" android:textStyle="bold" android:text="Email" /> <android.support.v7.widget.AppCompatTextView android:id="@+id/employee_email" android:layout_weight="1" android:text="Unknown" android:layout_width="0dp" android:layout_height="wrap_content" /> </LinearLayout> <LinearLayout android:padding="16dp" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <android.support.v7.widget.AppCompatTextView android:layout_width="0dp" android:layout_height="wrap_content" android:textSize="15dp" android:textStyle="bold" android:layout_weight="1" android:text="Gender" /> <android.support.v7.widget.AppCompatTextView android:id="@+id/employee_gender" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Unknown" /> </LinearLayout> </LinearLayout> </ScrollView> </RelativeLayout>
Sekarang tinggal java nya, buat class dengan nama EmployeeActivity dan
masukan kode berikut:
package com.giviews.employee; import android.annotation.TargetApi; import android.app.LoaderManager; import android.app.SearchManager; import android.content.ContentUris; import android.content.Context; import android.content.CursorLoader; import android.content.Intent; import android.content.Loader; import android.database.Cursor; import android.graphics.Rect; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import com.giviews.employee.data.EmployeeContract; import com.giviews.employee.data.EmployeeDbHelper; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; public class EmployeeActivity extends AppCompatActivity implements SearchView.OnQueryTextListener, LoaderManager.LoaderCallbacks<Cursor>{ // EmployeeDbHelper employeeDbHelper; private static final int EMPLOYEE_LOADER = 0; EmployeeCursorAdapter mCursorAdapter; @BindView(R.id.fab) FloatingActionButton button; public EmployeeActivity(){ } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_employee); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_setting); setSupportActionBar(toolbar); toolbar.setBackgroundColor(Constant.color); //Setup FAB ButterKnife.bind(this); findViewById(R.id.fab).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getApplicationContext(), EmployeeEditor.class); intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); intent.putExtra(EmployeeEditor.EXTRA_RECT, createRect(button)); startActivity(intent); } }); ListView employeeListView = (ListView) findViewById(R.id.list); View emptyView = findViewById(R.id.empty_view); employeeListView.setEmptyView(emptyView); mCursorAdapter = new EmployeeCursorAdapter(this, null); employeeListView.setAdapter(mCursorAdapter); //TODO employeeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { Intent intent = new Intent(getApplicationContext(), EmployeeDetailsActivity.class); Uri currentEmployeeUri = ContentUris.withAppendedId(EmployeeContract.EmployeeEntry.CONTENT_URI, id); intent.setData(currentEmployeeUri); intent.putExtra(EmployeeEditor.EXTRA_RECT, createRect(button)); startActivity(intent); } }); employeeListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) { Intent intent = new Intent(EmployeeActivity.this, EmployeeEditor.class); Uri currentEmployeeUri = ContentUris.withAppendedId(EmployeeContract.EmployeeEntry.CONTENT_URI, id); intent.setData(currentEmployeeUri); intent.putExtra(EmployeeEditor.EXTRA_RECT, createRect(button)); startActivity(intent); return true; } }); getLoaderManager().initLoader(EMPLOYEE_LOADER, null, this); // employeeDbHelper = new EmployeeDbHelper(this); } private Rect createRect(View view) { Rect rect = new Rect(); view.getDrawingRect(rect); ((ViewGroup) view.getParent()).offsetDescendantRectToMyCoords(view, rect); return rect; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_catalog, menu); MenuItem search = menu.findItem(R.id.action_search); SearchView searchView = (SearchView) MenuItemCompat.getActionView(search); searchView.setOnQueryTextListener(this); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.action_search: onSearchRequested(); return true; case R.id.setting: startActivity(new Intent(getApplicationContext(), SettingsActivity.class)); return true; default: return false; } } @Override public Loader<Cursor> onCreateLoader(int i, Bundle bundle) { String[] projection = { EmployeeContract.EmployeeEntry._ID, EmployeeContract.EmployeeEntry.COLUMN_FIRSTNAME, EmployeeContract.EmployeeEntry.COLUMN_LASTNAME, EmployeeContract.EmployeeEntry.COLUMN_TITLE, EmployeeContract.EmployeeEntry.COLUMN_DEPARTMENT, EmployeeContract.EmployeeEntry.COLUMN_CITY, EmployeeContract.EmployeeEntry.COLUMN_PHONE, EmployeeContract.EmployeeEntry.COLUMN_IMAGE, EmployeeContract.EmployeeEntry.COLUMN_EMAIL, }; return new CursorLoader(this, EmployeeContract.EmployeeEntry.CONTENT_URI, projection, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { mCursorAdapter.swapCursor(cursor); } @Override public void onLoaderReset(Loader<Cursor> loader) { mCursorAdapter.swapCursor(null); } @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { newText = newText.toLowerCase(); ArrayList<Cursor> newList = new ArrayList<>(); return true; } }
selanjutnya buat lagi class dengan nama EmployeeCursorAdapter dengan
kode seperti berikut:
package com.giviews.employee; import android.content.Context; import android.database.Cursor; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.TextView; import com.giviews.employee.data.EmployeeContract; /** * Created by asus on 27/10/2017. */ class EmployeeCursorAdapter extends CursorAdapter{ public EmployeeCursorAdapter(Context context, Cursor c) { super(context, c, 0); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return LayoutInflater.from(context).inflate(R.layout.list_item, parent, false); } @Override public void bindView(View view, Context context, Cursor cursor) { TextView firstnameTextView = (TextView) view.findViewById(R.id.firstname); TextView lastnameTextView = (TextView) view.findViewById(R.id.lastname); TextView titleTextView = (TextView) view.findViewById(R.id.titleview); int firstnameColumnIndex = cursor.getColumnIndex(EmployeeContract.EmployeeEntry.COLUMN_FIRSTNAME); int lastnameColumnIndex = cursor.getColumnIndex(EmployeeContract.EmployeeEntry.COLUMN_LASTNAME); int titleColumnIndex = cursor.getColumnIndex(EmployeeContract.EmployeeEntry.COLUMN_TITLE); String employeeFirstName = cursor.getString(firstnameColumnIndex); String employeeLastName = cursor.getString(lastnameColumnIndex); String employeeTitle = cursor.getString(titleColumnIndex); if (TextUtils.isEmpty(employeeFirstName)) { employeeFirstName = "Unknown"; } if (TextUtils.isEmpty(employeeLastName)) { employeeLastName = "Unknown"; } if (TextUtils.isEmpty(employeeTitle)) { employeeTitle = "Unknown"; } firstnameTextView.setText(employeeFirstName); lastnameTextView.setText(employeeLastName); titleTextView.setText(employeeTitle); } }
Selanjutnya buat lagi class dengan nama EmployeeEditor dan masukan kode
berikut:
package com.giviews.employee;
import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.AlertDialog;
import android.app.LoaderManager;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Loader;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NavUtils;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import com.afollestad.materialdialogs.MaterialDialog;
import com.giviews.employee.data.EmployeeContract;
import com.hendraanggrian.bundler.BindExtra;
import com.hendraanggrian.bundler.Bundler;
import com.hendraanggrian.kota.content.Themes;
import com.hendraanggrian.reveallayout.Radius;
import com.hendraanggrian.reveallayout.RevealableLayout;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import butterknife.BindView;
import butterknife.ButterKnife;
@RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
public class EmployeeEditor extends AppCompatActivity implements View.OnClickListener, LoaderManager.LoaderCallbacks<Cursor>{
private static final int EXISTING_EMPLOYEE_LOADER = 0;
private Uri mCurrentEmployeeUri;
private EditText mFirstNameEditText;
private EditText mLastNameEditText;
private EditText mTitleEditText;
private EditText mDepartment;
private EditText mCity;
private EditText mPhone;
private EditText mEmail;
private Spinner mGenderSpinner;
private int mGender = EmployeeContract.EmployeeEntry.GENDER_UNKNOWN;
private ImageView profileImageView;
private Button pickImage;
private static final int SELECT_PHOTO = 1;
private static final int CAPTURE_PHOTO = 2;
//TODO
public static final int MEDIA_TYPE_IMAGE = 1;
private static final String IMAGE_DIRECTORY_NAME = "KAMERA";
private Uri fileUri;
private ProgressDialog progressBar;
private int progressBarStatus = 0;
private Handler progressBarHandler = new Handler();
private boolean hasImageChanges = false;
Bitmap thumbnail;
private boolean mEmployeeHasChanged = false;
View rootLayout;
public static final String EXTRA_RECT = "com.giviews.employee";
@BindExtra(EXTRA_RECT)
Rect rect;
@BindView(R.id.revealLayout)
RevealableLayout revealLayout;
@BindView(R.id.root_layout)
ViewGroup layout;
private View.OnTouchListener mTouchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
mEmployeeHasChanged = true;
return false;
}
};
@RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editor);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_setting);
setSupportActionBar(toolbar);
toolbar.setBackgroundColor(Constant.color);
Bundler.bindExtras(this);
ButterKnife.bind(this);
//TODO
Intent intent = getIntent();
mCurrentEmployeeUri = intent.getData();
if (mCurrentEmployeeUri == null) {
setTitle("Add an Employee");
invalidateOptionsMenu();
}else {
setTitle("Edit Employee");
getLoaderManager().initLoader(EXISTING_EMPLOYEE_LOADER, null, this);
}
mFirstNameEditText = (EditText) findViewById(R.id.firstName);
mLastNameEditText = (EditText) findViewById(R.id.lastName);
mTitleEditText = (EditText) findViewById(R.id.title);
mDepartment = (EditText) findViewById(R.id.department);
mCity = (EditText) findViewById(R.id.city);
mPhone = (EditText) findViewById(R.id.phone);
mEmail = (EditText) findViewById(R.id.email);
mGenderSpinner = (Spinner) findViewById(R.id.spinner_gender);
mFirstNameEditText.setOnTouchListener(mTouchListener);
mLastNameEditText.setOnTouchListener(mTouchListener);
mTitleEditText.setOnTouchListener(mTouchListener);
mDepartment.setOnTouchListener(mTouchListener);
mCity.setOnTouchListener(mTouchListener);
mPhone.setOnTouchListener(mTouchListener);
mEmail.setOnTouchListener(mTouchListener);
mGenderSpinner.setOnTouchListener(mTouchListener);
setupSpinner();
rootLayout = findViewById(R.id.root_layout);
layout.post(new Runnable() {
@RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
@Override
public void run() {
Animator animator = revealLayout.reveal(layout, rect.centerX(), rect.centerY(), Radius.GONE_ACTIVITY);
animator.setDuration(1000);
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(Themes.getColor(getTheme(), R.attr.colorAccent, true));
}
}
});
animator.start();
}
});
//TODO
profileImageView = (ImageView) findViewById(R.id.profileImageView);
pickImage = (Button) findViewById(R.id.pickImage);
pickImage.setOnClickListener(this);
if (ContextCompat.checkSelfPermission(EmployeeEditor.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
profileImageView.setEnabled(false);
ActivityCompat.requestPermissions(EmployeeEditor.this, new String[]{ Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
}else {
profileImageView.setEnabled(true);
}
}
private void setupSpinner() {
ArrayAdapter genderSpinnerAdapter = ArrayAdapter.createFromResource(this,R.array.array_gender_options, android.R.layout.simple_spinner_item);
genderSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
mGenderSpinner.setAdapter(genderSpinnerAdapter);
mGenderSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selection = (String) parent.getItemAtPosition(position);
if (!TextUtils.isEmpty(selection)){
if (selection.equals(getString(R.string.gender_male))){
mGender = EmployeeContract.EmployeeEntry.GENDER_MALE;
}else if (selection.equals(getString(R.string.gender_female))) {
mGender = EmployeeContract.EmployeeEntry.GENDER_FEMALE;
}else {
mGender = EmployeeContract.EmployeeEntry.GENDER_UNKNOWN;
}
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
mGender = EmployeeContract.EmployeeEntry.GENDER_UNKNOWN;
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_editor, menu);
if (mCurrentEmployeeUri == null) {
MenuItem menuItem = menu.findItem(R.id.action_delete);
menuItem.setVisible(false);
}
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_save:
saveEmployee();
finish();
return true;
case R.id.action_delete:
showDeleteConfirmationDialog();
return true;
case android.R.id.home:
if (!mEmployeeHasChanged) {
NavUtils.navigateUpFromSameTask(EmployeeEditor.this);
return true;
}
DialogInterface.OnClickListener discardButtonClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
NavUtils.navigateUpFromSameTask(EmployeeEditor.this);
}
};
showUnSavedChangesDialog(discardButtonClickListener);
return true;
}
return super.onOptionsItemSelected(item);
}
private void saveEmployee() {
String firstnameString = mFirstNameEditText.getText().toString().trim();
String lastnameString = mLastNameEditText.getText().toString().trim();
String titleString = mTitleEditText.getText().toString().trim();
String departmentString = mDepartment.getText().toString().trim();
String cityString = mCity.getText().toString().trim();
String phoneString = mPhone.getText().toString().trim();
String emailString = mEmail.getText().toString().trim();
profileImageView.setDrawingCacheEnabled(true);
profileImageView.buildDrawingCache();
Bitmap bitmap = profileImageView.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
if (mCurrentEmployeeUri == null &&
TextUtils.isEmpty(firstnameString) && TextUtils.isEmpty(lastnameString) &&
TextUtils.isEmpty(titleString) && TextUtils.isEmpty(departmentString) &&
TextUtils.isEmpty(cityString) && TextUtils.isEmpty(phoneString) &&
TextUtils.isEmpty(emailString) && mGender == EmployeeContract.EmployeeEntry.GENDER_UNKNOWN) {
return;
}
ContentValues values = new ContentValues();
values.put(EmployeeContract.EmployeeEntry.COLUMN_FIRSTNAME, firstnameString);
values.put(EmployeeContract.EmployeeEntry.COLUMN_LASTNAME, lastnameString);
values.put(EmployeeContract.EmployeeEntry.COLUMN_TITLE, titleString);
values.put(EmployeeContract.EmployeeEntry.COLUMN_DEPARTMENT, departmentString);
values.put(EmployeeContract.EmployeeEntry.COLUMN_CITY, cityString);
values.put(EmployeeContract.EmployeeEntry.COLUMN_PHONE, phoneString);
values.put(EmployeeContract.EmployeeEntry.COLUMN_IMAGE, data);
values.put(EmployeeContract.EmployeeEntry.COLUMN_EMAIL, emailString);
values.put(EmployeeContract.EmployeeEntry.COLUMN_EMPLOYEE_GENDER, mGender);
if (mCurrentEmployeeUri == null) {
Uri newUri = getContentResolver().insert(EmployeeContract.EmployeeEntry.CONTENT_URI, values);
if (newUri == null) {
Toast.makeText(this, "Error with saving Employee", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this, "Employee saved", Toast.LENGTH_SHORT).show();
}
}else {
int rowAffected = getContentResolver().update(mCurrentEmployeeUri, values, null, null);
if (rowAffected == 0) {
Toast.makeText(getApplicationContext(), "Error with updating employee", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getApplicationContext(), "Employee updated", Toast.LENGTH_SHORT).show();
}
}
}
@RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String[] projection = {
EmployeeContract.EmployeeEntry._ID,
EmployeeContract.EmployeeEntry.COLUMN_FIRSTNAME,
EmployeeContract.EmployeeEntry.COLUMN_LASTNAME,
EmployeeContract.EmployeeEntry.COLUMN_TITLE,
EmployeeContract.EmployeeEntry.COLUMN_DEPARTMENT,
EmployeeContract.EmployeeEntry.COLUMN_CITY,
EmployeeContract.EmployeeEntry.COLUMN_PHONE,
EmployeeContract.EmployeeEntry.COLUMN_IMAGE,
EmployeeContract.EmployeeEntry.COLUMN_EMAIL,
EmployeeContract.EmployeeEntry.COLUMN_EMPLOYEE_GENDER,
};
return new CursorLoader(this,
mCurrentEmployeeUri,
projection,
null,
null,
null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (cursor == null || cursor.getCount() < 1) {
return;
}
if (cursor.moveToFirst()) {
int firstnameColumnIndex = cursor.getColumnIndex(EmployeeContract.EmployeeEntry.COLUMN_FIRSTNAME);
int lastnameColumnIndex = cursor.getColumnIndex(EmployeeContract.EmployeeEntry.COLUMN_LASTNAME);
int titleColumnIndex = cursor.getColumnIndex(EmployeeContract.EmployeeEntry.COLUMN_TITLE);
int departmentColumnIndex = cursor.getColumnIndex(EmployeeContract.EmployeeEntry.COLUMN_DEPARTMENT);
int cityColumnIndex = cursor.getColumnIndex(EmployeeContract.EmployeeEntry.COLUMN_CITY);
int phoneColumnIndex = cursor.getColumnIndex(EmployeeContract.EmployeeEntry.COLUMN_PHONE);
int imageColumnIndex = cursor.getColumnIndex(EmployeeContract.EmployeeEntry.COLUMN_IMAGE);
int emailColumnIndex = cursor.getColumnIndex(EmployeeContract.EmployeeEntry.COLUMN_EMAIL);
int genderColumnIndex = cursor.getColumnIndex(EmployeeContract.EmployeeEntry.COLUMN_EMPLOYEE_GENDER);
String firstName = cursor.getString(firstnameColumnIndex);
String lastName = cursor.getString(lastnameColumnIndex);
String title = cursor.getString(titleColumnIndex);
String department = cursor.getString(departmentColumnIndex);
String city = cursor.getString(cityColumnIndex);
String phone = cursor.getString(phoneColumnIndex);
byte[] image = cursor.getBlob(imageColumnIndex);
String email = cursor.getString(emailColumnIndex);
int gender = cursor.getInt(genderColumnIndex);
mFirstNameEditText.setText(firstName);
mLastNameEditText.setText(lastName);
mTitleEditText.setText(title);
mDepartment.setText(department);
mCity.setText(city);
mPhone.setText(phone);
Bitmap bmp = BitmapFactory.decodeByteArray(image, 0, image.length);
profileImageView.setImageBitmap(Bitmap.createScaledBitmap(bmp, 200, 200, false));
mEmail.setText(email);
switch (gender) {
case EmployeeContract.EmployeeEntry.GENDER_MALE:
mGenderSpinner.setSelection(1);
break;
case EmployeeContract.EmployeeEntry.GENDER_FEMALE:
mGenderSpinner.setSelection(2);
break;
default:
mGenderSpinner.setSelection(0);
break;
}
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
mFirstNameEditText.setText("");
mLastNameEditText.setText("");
mTitleEditText.setText("");
mDepartment.setText("");
mCity.setText("");
mPhone.setText("");
mEmail.setText("");
mGenderSpinner.setSelection(0);
}
private void showUnSavedChangesDialog(DialogInterface.OnClickListener discardButtonClickListener) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Discard your changes and quit editing?");
builder.setPositiveButton("Discard", discardButtonClickListener);
builder.setNegativeButton("Keep Editing", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
if (dialog != null) {
dialog.dismiss();
}
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void showDeleteConfirmationDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Delete this Employee?");
builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
deleteEmployee();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
if (dialog != null){
dialog.dismiss();
}
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void deleteEmployee() {
if (mCurrentEmployeeUri != null){
int rowsDeleted = getContentResolver().delete(mCurrentEmployeeUri,null, null);
if (rowsDeleted == 0) {
Toast.makeText(this, "Error with deleteing employee", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this, "Employee deleted", Toast.LENGTH_SHORT).show();
}
}
finish();
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.pickImage:
new MaterialDialog.Builder(this)
.title("set your image")
.items(R.array.upload_images)
.itemsIds(R.array.itemIds)
.itemsCallback(new MaterialDialog.ListCallback() {
@Override
public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
switch (which) {
case 0:
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
break;
case 1:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAPTURE_PHOTO);
break;
case 2:
profileImageView.setImageResource(R.drawable.ic_account_circle_black);
break;
}
}
})
.show();
break;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 0){
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
profileImageView.setEnabled(true);
}
}
}
public void setProgressBar(){
progressBar = new ProgressDialog(this);
progressBar.setCancelable(true);
progressBar.setMessage("Please wait....");
progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressBar.setProgress(0);
progressBar.setMax(100);
progressBar.show();
progressBarStatus = 0;
new Thread(new Runnable() {
@Override
public void run() {
while (progressBarStatus < 100) {
progressBarStatus += 30;
try {
Thread.sleep(1000);
}catch (InterruptedException e) {
e.printStackTrace();
}
progressBarHandler.post(new Runnable() {
@Override
public void run() {
progressBar.setProgress(progressBarStatus);
}
});
}
if (progressBarStatus >= 100){
try {
Thread.sleep(2000);
}catch (InterruptedException e){
e.printStackTrace();
}
progressBar.dismiss();
}
}
}).start();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SELECT_PHOTO) {
if (resultCode == RESULT_OK) {
try {
final Uri imageUri = data.getData();
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
setProgressBar();
profileImageView.setImageBitmap(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}else if (requestCode == CAPTURE_PHOTO){
if (resultCode == RESULT_OK) {
onCaptureImageResult();
}
}
}
}
private void onCaptureImageResult() {
try {
// thumbnail = (Bitmap) data.getExtras().get("data");
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
thumbnail = BitmapFactory.decodeFile(fileUri.getPath(), options);
setProgressBar();
// profileImageView.setMaxWidth(200);
profileImageView.setImageBitmap(thumbnail);
}catch (NullPointerException e) {
e.printStackTrace();
}
}
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
private File getOutputMediaFile(int type) {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Ooops! Failed create"
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
String timeStamp;
timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmsss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
}else {
return null;
}
return mediaFile;
}
}
import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.AlertDialog;
import android.app.LoaderManager;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Loader;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NavUtils;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import com.afollestad.materialdialogs.MaterialDialog;
import com.giviews.employee.data.EmployeeContract;
import com.hendraanggrian.bundler.BindExtra;
import com.hendraanggrian.bundler.Bundler;
import com.hendraanggrian.kota.content.Themes;
import com.hendraanggrian.reveallayout.Radius;
import com.hendraanggrian.reveallayout.RevealableLayout;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import butterknife.BindView;
import butterknife.ButterKnife;
@RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
public class EmployeeEditor extends AppCompatActivity implements View.OnClickListener, LoaderManager.LoaderCallbacks<Cursor>{
private static final int EXISTING_EMPLOYEE_LOADER = 0;
private Uri mCurrentEmployeeUri;
private EditText mFirstNameEditText;
private EditText mLastNameEditText;
private EditText mTitleEditText;
private EditText mDepartment;
private EditText mCity;
private EditText mPhone;
private EditText mEmail;
private Spinner mGenderSpinner;
private int mGender = EmployeeContract.EmployeeEntry.GENDER_UNKNOWN;
private ImageView profileImageView;
private Button pickImage;
private static final int SELECT_PHOTO = 1;
private static final int CAPTURE_PHOTO = 2;
//TODO
public static final int MEDIA_TYPE_IMAGE = 1;
private static final String IMAGE_DIRECTORY_NAME = "KAMERA";
private Uri fileUri;
private ProgressDialog progressBar;
private int progressBarStatus = 0;
private Handler progressBarHandler = new Handler();
private boolean hasImageChanges = false;
Bitmap thumbnail;
private boolean mEmployeeHasChanged = false;
View rootLayout;
public static final String EXTRA_RECT = "com.giviews.employee";
@BindExtra(EXTRA_RECT)
Rect rect;
@BindView(R.id.revealLayout)
RevealableLayout revealLayout;
@BindView(R.id.root_layout)
ViewGroup layout;
private View.OnTouchListener mTouchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
mEmployeeHasChanged = true;
return false;
}
};
@RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editor);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_setting);
setSupportActionBar(toolbar);
toolbar.setBackgroundColor(Constant.color);
Bundler.bindExtras(this);
ButterKnife.bind(this);
//TODO
Intent intent = getIntent();
mCurrentEmployeeUri = intent.getData();
if (mCurrentEmployeeUri == null) {
setTitle("Add an Employee");
invalidateOptionsMenu();
}else {
setTitle("Edit Employee");
getLoaderManager().initLoader(EXISTING_EMPLOYEE_LOADER, null, this);
}
mFirstNameEditText = (EditText) findViewById(R.id.firstName);
mLastNameEditText = (EditText) findViewById(R.id.lastName);
mTitleEditText = (EditText) findViewById(R.id.title);
mDepartment = (EditText) findViewById(R.id.department);
mCity = (EditText) findViewById(R.id.city);
mPhone = (EditText) findViewById(R.id.phone);
mEmail = (EditText) findViewById(R.id.email);
mGenderSpinner = (Spinner) findViewById(R.id.spinner_gender);
mFirstNameEditText.setOnTouchListener(mTouchListener);
mLastNameEditText.setOnTouchListener(mTouchListener);
mTitleEditText.setOnTouchListener(mTouchListener);
mDepartment.setOnTouchListener(mTouchListener);
mCity.setOnTouchListener(mTouchListener);
mPhone.setOnTouchListener(mTouchListener);
mEmail.setOnTouchListener(mTouchListener);
mGenderSpinner.setOnTouchListener(mTouchListener);
setupSpinner();
rootLayout = findViewById(R.id.root_layout);
layout.post(new Runnable() {
@RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
@Override
public void run() {
Animator animator = revealLayout.reveal(layout, rect.centerX(), rect.centerY(), Radius.GONE_ACTIVITY);
animator.setDuration(1000);
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(Themes.getColor(getTheme(), R.attr.colorAccent, true));
}
}
});
animator.start();
}
});
//TODO
profileImageView = (ImageView) findViewById(R.id.profileImageView);
pickImage = (Button) findViewById(R.id.pickImage);
pickImage.setOnClickListener(this);
if (ContextCompat.checkSelfPermission(EmployeeEditor.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
profileImageView.setEnabled(false);
ActivityCompat.requestPermissions(EmployeeEditor.this, new String[]{ Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
}else {
profileImageView.setEnabled(true);
}
}
private void setupSpinner() {
ArrayAdapter genderSpinnerAdapter = ArrayAdapter.createFromResource(this,R.array.array_gender_options, android.R.layout.simple_spinner_item);
genderSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
mGenderSpinner.setAdapter(genderSpinnerAdapter);
mGenderSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selection = (String) parent.getItemAtPosition(position);
if (!TextUtils.isEmpty(selection)){
if (selection.equals(getString(R.string.gender_male))){
mGender = EmployeeContract.EmployeeEntry.GENDER_MALE;
}else if (selection.equals(getString(R.string.gender_female))) {
mGender = EmployeeContract.EmployeeEntry.GENDER_FEMALE;
}else {
mGender = EmployeeContract.EmployeeEntry.GENDER_UNKNOWN;
}
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
mGender = EmployeeContract.EmployeeEntry.GENDER_UNKNOWN;
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_editor, menu);
if (mCurrentEmployeeUri == null) {
MenuItem menuItem = menu.findItem(R.id.action_delete);
menuItem.setVisible(false);
}
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_save:
saveEmployee();
finish();
return true;
case R.id.action_delete:
showDeleteConfirmationDialog();
return true;
case android.R.id.home:
if (!mEmployeeHasChanged) {
NavUtils.navigateUpFromSameTask(EmployeeEditor.this);
return true;
}
DialogInterface.OnClickListener discardButtonClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
NavUtils.navigateUpFromSameTask(EmployeeEditor.this);
}
};
showUnSavedChangesDialog(discardButtonClickListener);
return true;
}
return super.onOptionsItemSelected(item);
}
private void saveEmployee() {
String firstnameString = mFirstNameEditText.getText().toString().trim();
String lastnameString = mLastNameEditText.getText().toString().trim();
String titleString = mTitleEditText.getText().toString().trim();
String departmentString = mDepartment.getText().toString().trim();
String cityString = mCity.getText().toString().trim();
String phoneString = mPhone.getText().toString().trim();
String emailString = mEmail.getText().toString().trim();
profileImageView.setDrawingCacheEnabled(true);
profileImageView.buildDrawingCache();
Bitmap bitmap = profileImageView.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
if (mCurrentEmployeeUri == null &&
TextUtils.isEmpty(firstnameString) && TextUtils.isEmpty(lastnameString) &&
TextUtils.isEmpty(titleString) && TextUtils.isEmpty(departmentString) &&
TextUtils.isEmpty(cityString) && TextUtils.isEmpty(phoneString) &&
TextUtils.isEmpty(emailString) && mGender == EmployeeContract.EmployeeEntry.GENDER_UNKNOWN) {
return;
}
ContentValues values = new ContentValues();
values.put(EmployeeContract.EmployeeEntry.COLUMN_FIRSTNAME, firstnameString);
values.put(EmployeeContract.EmployeeEntry.COLUMN_LASTNAME, lastnameString);
values.put(EmployeeContract.EmployeeEntry.COLUMN_TITLE, titleString);
values.put(EmployeeContract.EmployeeEntry.COLUMN_DEPARTMENT, departmentString);
values.put(EmployeeContract.EmployeeEntry.COLUMN_CITY, cityString);
values.put(EmployeeContract.EmployeeEntry.COLUMN_PHONE, phoneString);
values.put(EmployeeContract.EmployeeEntry.COLUMN_IMAGE, data);
values.put(EmployeeContract.EmployeeEntry.COLUMN_EMAIL, emailString);
values.put(EmployeeContract.EmployeeEntry.COLUMN_EMPLOYEE_GENDER, mGender);
if (mCurrentEmployeeUri == null) {
Uri newUri = getContentResolver().insert(EmployeeContract.EmployeeEntry.CONTENT_URI, values);
if (newUri == null) {
Toast.makeText(this, "Error with saving Employee", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this, "Employee saved", Toast.LENGTH_SHORT).show();
}
}else {
int rowAffected = getContentResolver().update(mCurrentEmployeeUri, values, null, null);
if (rowAffected == 0) {
Toast.makeText(getApplicationContext(), "Error with updating employee", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getApplicationContext(), "Employee updated", Toast.LENGTH_SHORT).show();
}
}
}
@RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String[] projection = {
EmployeeContract.EmployeeEntry._ID,
EmployeeContract.EmployeeEntry.COLUMN_FIRSTNAME,
EmployeeContract.EmployeeEntry.COLUMN_LASTNAME,
EmployeeContract.EmployeeEntry.COLUMN_TITLE,
EmployeeContract.EmployeeEntry.COLUMN_DEPARTMENT,
EmployeeContract.EmployeeEntry.COLUMN_CITY,
EmployeeContract.EmployeeEntry.COLUMN_PHONE,
EmployeeContract.EmployeeEntry.COLUMN_IMAGE,
EmployeeContract.EmployeeEntry.COLUMN_EMAIL,
EmployeeContract.EmployeeEntry.COLUMN_EMPLOYEE_GENDER,
};
return new CursorLoader(this,
mCurrentEmployeeUri,
projection,
null,
null,
null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (cursor == null || cursor.getCount() < 1) {
return;
}
if (cursor.moveToFirst()) {
int firstnameColumnIndex = cursor.getColumnIndex(EmployeeContract.EmployeeEntry.COLUMN_FIRSTNAME);
int lastnameColumnIndex = cursor.getColumnIndex(EmployeeContract.EmployeeEntry.COLUMN_LASTNAME);
int titleColumnIndex = cursor.getColumnIndex(EmployeeContract.EmployeeEntry.COLUMN_TITLE);
int departmentColumnIndex = cursor.getColumnIndex(EmployeeContract.EmployeeEntry.COLUMN_DEPARTMENT);
int cityColumnIndex = cursor.getColumnIndex(EmployeeContract.EmployeeEntry.COLUMN_CITY);
int phoneColumnIndex = cursor.getColumnIndex(EmployeeContract.EmployeeEntry.COLUMN_PHONE);
int imageColumnIndex = cursor.getColumnIndex(EmployeeContract.EmployeeEntry.COLUMN_IMAGE);
int emailColumnIndex = cursor.getColumnIndex(EmployeeContract.EmployeeEntry.COLUMN_EMAIL);
int genderColumnIndex = cursor.getColumnIndex(EmployeeContract.EmployeeEntry.COLUMN_EMPLOYEE_GENDER);
String firstName = cursor.getString(firstnameColumnIndex);
String lastName = cursor.getString(lastnameColumnIndex);
String title = cursor.getString(titleColumnIndex);
String department = cursor.getString(departmentColumnIndex);
String city = cursor.getString(cityColumnIndex);
String phone = cursor.getString(phoneColumnIndex);
byte[] image = cursor.getBlob(imageColumnIndex);
String email = cursor.getString(emailColumnIndex);
int gender = cursor.getInt(genderColumnIndex);
mFirstNameEditText.setText(firstName);
mLastNameEditText.setText(lastName);
mTitleEditText.setText(title);
mDepartment.setText(department);
mCity.setText(city);
mPhone.setText(phone);
Bitmap bmp = BitmapFactory.decodeByteArray(image, 0, image.length);
profileImageView.setImageBitmap(Bitmap.createScaledBitmap(bmp, 200, 200, false));
mEmail.setText(email);
switch (gender) {
case EmployeeContract.EmployeeEntry.GENDER_MALE:
mGenderSpinner.setSelection(1);
break;
case EmployeeContract.EmployeeEntry.GENDER_FEMALE:
mGenderSpinner.setSelection(2);
break;
default:
mGenderSpinner.setSelection(0);
break;
}
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
mFirstNameEditText.setText("");
mLastNameEditText.setText("");
mTitleEditText.setText("");
mDepartment.setText("");
mCity.setText("");
mPhone.setText("");
mEmail.setText("");
mGenderSpinner.setSelection(0);
}
private void showUnSavedChangesDialog(DialogInterface.OnClickListener discardButtonClickListener) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Discard your changes and quit editing?");
builder.setPositiveButton("Discard", discardButtonClickListener);
builder.setNegativeButton("Keep Editing", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
if (dialog != null) {
dialog.dismiss();
}
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void showDeleteConfirmationDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Delete this Employee?");
builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
deleteEmployee();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
if (dialog != null){
dialog.dismiss();
}
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void deleteEmployee() {
if (mCurrentEmployeeUri != null){
int rowsDeleted = getContentResolver().delete(mCurrentEmployeeUri,null, null);
if (rowsDeleted == 0) {
Toast.makeText(this, "Error with deleteing employee", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this, "Employee deleted", Toast.LENGTH_SHORT).show();
}
}
finish();
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.pickImage:
new MaterialDialog.Builder(this)
.title("set your image")
.items(R.array.upload_images)
.itemsIds(R.array.itemIds)
.itemsCallback(new MaterialDialog.ListCallback() {
@Override
public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
switch (which) {
case 0:
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
break;
case 1:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAPTURE_PHOTO);
break;
case 2:
profileImageView.setImageResource(R.drawable.ic_account_circle_black);
break;
}
}
})
.show();
break;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 0){
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
profileImageView.setEnabled(true);
}
}
}
public void setProgressBar(){
progressBar = new ProgressDialog(this);
progressBar.setCancelable(true);
progressBar.setMessage("Please wait....");
progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressBar.setProgress(0);
progressBar.setMax(100);
progressBar.show();
progressBarStatus = 0;
new Thread(new Runnable() {
@Override
public void run() {
while (progressBarStatus < 100) {
progressBarStatus += 30;
try {
Thread.sleep(1000);
}catch (InterruptedException e) {
e.printStackTrace();
}
progressBarHandler.post(new Runnable() {
@Override
public void run() {
progressBar.setProgress(progressBarStatus);
}
});
}
if (progressBarStatus >= 100){
try {
Thread.sleep(2000);
}catch (InterruptedException e){
e.printStackTrace();
}
progressBar.dismiss();
}
}
}).start();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SELECT_PHOTO) {
if (resultCode == RESULT_OK) {
try {
final Uri imageUri = data.getData();
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
setProgressBar();
profileImageView.setImageBitmap(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}else if (requestCode == CAPTURE_PHOTO){
if (resultCode == RESULT_OK) {
onCaptureImageResult();
}
}
}
}
private void onCaptureImageResult() {
try {
// thumbnail = (Bitmap) data.getExtras().get("data");
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
thumbnail = BitmapFactory.decodeFile(fileUri.getPath(), options);
setProgressBar();
// profileImageView.setMaxWidth(200);
profileImageView.setImageBitmap(thumbnail);
}catch (NullPointerException e) {
e.printStackTrace();
}
}
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
private File getOutputMediaFile(int type) {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Ooops! Failed create"
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
String timeStamp;
timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmsss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
}else {
return null;
}
return mediaFile;
}
}
kemudian buat lagi class dengan nama EmployeeDetailsActivity untuk
menampilkan details data employee nya, dengan kode seperti berikut:
package com.giviews.employee; import android.app.LoaderManager; import android.content.CursorLoader; import android.content.Intent; import android.content.Loader; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.PersistableBundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.giviews.employee.data.EmployeeContract; /** * Created by asus on 28/10/2017. */ public class EmployeeDetailsActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor>{ private Uri mCurrentEmployeeUri; private TextView mFirstname; private TextView mLastname; private TextView mDepartment; private TextView mTitle; private TextView mCity; private TextView mPhone; private TextView mEmail; private TextView mGender; private ImageView profileImageView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_employee_details); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_setting); setSupportActionBar(toolbar); toolbar.setBackgroundColor(Constant.color); Intent intent = getIntent(); mCurrentEmployeeUri = intent.getData(); if (mCurrentEmployeeUri == null) { Toast.makeText(this, "No Employee Data ", Toast.LENGTH_SHORT).show(); }else { getLoaderManager().initLoader(0, null, this); } mFirstname = (TextView) findViewById(R.id.employee_firstname); mLastname = (TextView) findViewById(R.id.employee_lastname); mTitle = (TextView) findViewById(R.id.employee_title); mDepartment = (TextView) findViewById(R.id.employee_department); mCity = (TextView) findViewById(R.id.employee_city); mPhone = (TextView) findViewById(R.id.employee_phone); mEmail = (TextView) findViewById(R.id.employee_email); mGender = (TextView) findViewById(R.id.employee_gender); profileImageView = (ImageView) findViewById(R.id.profileImageView); } public Loader<Cursor> onCreateLoader(int id, Bundle args) { String[] projection = { EmployeeContract.EmployeeEntry._ID, EmployeeContract.EmployeeEntry.COLUMN_FIRSTNAME, EmployeeContract.EmployeeEntry.COLUMN_LASTNAME, EmployeeContract.EmployeeEntry.COLUMN_TITLE, EmployeeContract.EmployeeEntry.COLUMN_DEPARTMENT, EmployeeContract.EmployeeEntry.COLUMN_CITY, EmployeeContract.EmployeeEntry.COLUMN_PHONE, EmployeeContract.EmployeeEntry.COLUMN_IMAGE, EmployeeContract.EmployeeEntry.COLUMN_EMAIL, EmployeeContract.EmployeeEntry.COLUMN_EMPLOYEE_GENDER, }; return new CursorLoader(this, mCurrentEmployeeUri, projection, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (cursor == null || cursor.getCount() < 1) { return; } if (cursor.moveToFirst()) { int firstnameColumnIndex = cursor.getColumnIndex(EmployeeContract.EmployeeEntry.COLUMN_FIRSTNAME); int lastnameColumnIndex = cursor.getColumnIndex(EmployeeContract.EmployeeEntry.COLUMN_LASTNAME); int titleColumnIndex = cursor.getColumnIndex(EmployeeContract.EmployeeEntry.COLUMN_TITLE); int departmentColumnIndex = cursor.getColumnIndex(EmployeeContract.EmployeeEntry.COLUMN_DEPARTMENT); int cityColumnIndex = cursor.getColumnIndex(EmployeeContract.EmployeeEntry.COLUMN_CITY); int phoneColumnIndex = cursor.getColumnIndex(EmployeeContract.EmployeeEntry.COLUMN_PHONE); int imageCoumnIndex = cursor.getColumnIndex(EmployeeContract.EmployeeEntry.COLUMN_IMAGE); int emailColumnIndex = cursor.getColumnIndex(EmployeeContract.EmployeeEntry.COLUMN_EMAIL); int genderColumnIndex = cursor.getColumnIndex(EmployeeContract.EmployeeEntry.COLUMN_EMPLOYEE_GENDER); String firstName = cursor.getString(firstnameColumnIndex); String lastName = cursor.getString(lastnameColumnIndex); String title = cursor.getString(titleColumnIndex); String department = cursor.getString(departmentColumnIndex); String city = cursor.getString(cityColumnIndex); String phone = cursor.getString(phoneColumnIndex); byte[] image = cursor.getBlob(imageCoumnIndex); String email = cursor.getString(emailColumnIndex); int gender = cursor.getInt(genderColumnIndex); setTitle(firstName); mFirstname.setText(firstName); mLastname.setText(lastName); mTitle.setText(title); mDepartment.setText(department); mCity.setText(city); mPhone.setText(phone); Bitmap bmp = BitmapFactory.decodeByteArray(image, 0, image.length); profileImageView.setImageBitmap(Bitmap.createScaledBitmap(bmp, 200, 200, false)); mEmail.setText(email); switch (gender) { case EmployeeContract.EmployeeEntry.GENDER_MALE: mGender.setText("Male"); break; case EmployeeContract.EmployeeEntry.GENDER_FEMALE: mGender.setText("Female"); break; default: mGender.setText("Unknown"); break; } } } @Override public void onLoaderReset(Loader<Cursor> loader) { } }
karena artikel ini sudah terlalu panjang maka part ke3 dicukupkan dulu
sampai sini akan kita lanjutkan ke part4 finishing
Langganan:
Postingan
(
Atom
)
SUBSCRIBE
Total Tayangan Halaman
Popular Posts
- Cara Membuat Form Berada di tengah layar menggunakan html dan css
- Cara Membuat Launcher Sendiri di Android Studio (updated)
- cara membuat undangan online sendiri seperti nikah.co.id dengan html, css, dan jquery
- Membuat Form pendaftaran multipart seperti di facebook / twitter
- Cara Membuat template wordpress sendiri
- Menambahkan animasi Loading ketika halaman sedang di muat
- Membuat Aplikasi CRUD Sederhana dengan database SQLite di Android Studio
- Membuat Aplikasi Menu Makanan dengan android Studio
- Cara Mengimport file CSV ke dalam Microsoft SQL Server
- Membuat Register User dengan Firebase di Android Studio
Label
- adsense
- Ai
- ajax
- android
- angular
- animasi
- api
- Ar
- artificial intelligence
- artikel
- assistant
- bard
- blogger
- blokchain
- bootstrap
- bypass
- ceritajenius
- ChatGPT
- codeigniter
- coding
- covid19
- crud
- css
- cyclist
- Dall-E
- data warehouse
- database
- desain-web
- developer
- digital
- disqus
- ebook
- Encrypt
- express
- firebase
- flash
- form
- frp
- frugal living
- git
- gym
- hack
- health
- html
- industri 4.0
- investasi
- Iot
- it
- javascript
- jquery
- keuangan
- kopi
- laravel
- liburan
- Lifestyle
- login
- mean
- Metaverse
- mobile programming
- mongo
- node
- oop
- oracle
- pdo
- php
- restfull
- Robotik
- Saham
- search
- software
- sql
- sqlite
- tips&trick
- vcs
- vr
- web programming
- Web3
- wordpress
0 komentar :