-
Android realtime chat dengan menggunakan Firebase Realtime Database
Pada artikel kali ini, saya akan membuat realtime chat yang sederhana dengan menggunakan Firebase Realtime Database. Firebase Realtime Database adalah database yang di-host di cloud. Data disimpan sebagai JSON dan disinkronkan secara realtime ke setiap klien yang terhubung. Ketika membuat aplikasi cross-platform dengan SDK Android, iOS, dan JavaScript, semua klien akan berbagi sebuah instance Realtime Database dan menerima update data terbaru secara otomatis.
Langkah pertama yang perlu dilakukan adalah membuat firebase project pada:
https://console.firebase.google.com
-
Android Bounce Animation
Buat android project.
Langkah selanjutnya adalah membuat layout dengan menggunakan ImageButton.
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout 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=".MainActivity"> <ImageButton android:id="@+id/ibtn_book" android:layout_width="180dp" android:layout_height="180dp" android:background="@null" android:scaleType="fitCenter" android:src="@drawable/img_book" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout>
Buat transisi untuk bounce.
- Klik kanan pada
res
, kemudian buat folder anim. - Untuk membuat animasi yang berjalan terus menerus, tambahkan atribut
android:repeatCount="infinite"
pada elemen<scale>
. - Buat file
bounce.xml
, kemudian tambahkan code berikut:
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" > <scale android:duration="2000" android:fromXScale="0.4" android:toXScale="1.0" android:fromYScale="0.4" android:toYScale="1.0" android:pivotX="50%" android:pivotY="50%" /> </set>
Buat class
QBounceInterpolator.java
sebagai interpolator pada animasi yang akan dibuat.package org.akhal.example.buttonanimation; import android.view.animation.Interpolator; public class QBounceInterpolator implements Interpolator { private double mAmplitude = 1; private double mFrequency = 10; public QBounceInterpolator(double amplitude, double frequency) { mAmplitude = amplitude; mFrequency = frequency; } public float getInterpolation(float time) { return (float) (-1 * Math.pow(Math.E, -time/ mAmplitude) * Math.cos(mFrequency * time) + 1); } }
Agar menjadi animasi, tambahkan code
AnimationUtils
padaMainActivity.java
sehingga menjadi superti berikut:package org.akhal.example.buttonanimation; import android.content.Context; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageButton; public class MainActivity extends AppCompatActivity { private Animation bounceAnimation; private Context context; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bounceAnimation = AnimationUtils.loadAnimation(this, R.anim.bounce); QBounceInterpolator interpolator = new QBounceInterpolator(0.2, 20); bounceAnimation.setInterpolator(interpolator); final ImageButton imageButton = findViewById(R.id.ibtn_book); imageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { imageButton.startAnimation(bounceAnimation); } }); imageButton.startAnimation(bounceAnimation); } }
Jalankan aplikasi, sehingga nampak seperti gambar berikut ini:
Untuk program lengkapnya, dapat diunduh di link di bawah ini:
- Klik kanan pada
-
BottomAppBar
Salah satu komponen yang diperkenalkan pada acara Google I/O 2018 atalha BottomAppBar yang merupakan extension dari Toolbar yang peletakannya berada pada bagana bawah jendela aplikasi. Bersaam dengan BottomAppBar penempatan Floating Action Button (FAB) juga telah berubah. Dengan dessin baru, FAB data ditempatkan pada posisi yang bervariasi. Pada artikel kali ini, akan ditunjukkan bagaimana cara menggunakan material BottomAppBar pada sebuah layout.
Langkah pertama adalah buat project baru.
Tambahkan dependency pada file
build.gradle
.implementation 'com.android.support:design:28.0.0'
untuk AndroidX
implementation 'com.google.android.material:material:1.0.0'
Langkah selanjutnya adalah membuat layout.
<?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout 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=".MainActivity"> <android.support.design.bottomappbar.BottomAppBar android:id="@+id/bottom_appbar" android:layout_gravity="bottom" android:layout_width="match_parent" android:layout_height="wrap_content" app:navigationIcon="@drawable/ic_menu_black" style="@style/Widget.MaterialComponents.BottomAppBar.Colored"> </android.support.design.bottomappbar.BottomAppBar> <android.support.design.widget.FloatingActionButton android:id="@+id/floating" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_camera_alt_black" app:backgroundTint="@color/colorPrimary" app:fabSize="normal" app:layout_anchor="@id/bottom_appbar" /> </android.support.design.widget.CoordinatorLayout>
Langah berikutnya adalah membuat file menu dengan nama file
bottomappbar_menu.xml
.<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/app_bar_share"
android:icon="@drawable/ic_share_black"
android:title="Share"
app:showAsAction="ifRoom"/>
<item
android:id="@+id/app_bar_favorite"
android:icon="@drawable/ic_favorite_black"
android:title="Favorite"
app:showAsAction="ifRoom"/>
</menu>Untuk menangani tombol ketika diklik, buat beberapa tambahan program pada file activity.
package org.akhal.example.bottomappbar; import android.content.Context; import android.os.Bundle; import android.support.design.bottomappbar.BottomAppBar; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private BottomAppBar bottomAppBar; private FloatingActionButton fab; private Context context; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); context = this; bottomAppBar = findViewById(R.id.bottom_appbar); bottomAppBar.replaceMenu(R.menu.bottomappbar_menu); bottomAppBar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(context, "On click menu!", Toast.LENGTH_SHORT).show(); } }); fab = findViewById(R.id.floating); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(context, "On click camera!", Toast.LENGTH_SHORT).show(); } }); bottomAppBar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { int item = menuItem.getItemId(); switch (item) { case R.id.app_bar_share: Toast.makeText(context, "On click share!", Toast.LENGTH_SHORT).show(); break; case R.id.app_bar_favorite: Toast.makeText(context, "On click favorite!", Toast.LENGTH_SHORT).show(); break; } return false; } }); } }
-
ListView on ScrollView
Buat custom ListView tanpa fitur scroll.
package al.akh.example.testing.view; import android.content.Context; import android.util.AttributeSet; import android.view.ViewGroup; import android.widget.ListView; public class ListViewNonScroll extends ListView { public ListViewNonScroll(Context context) { super(context); } public ListViewNonScroll(Context context, AttributeSet attrs) { super(context, attrs); } public ListViewNonScroll(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int heightMeasureSpec_custom = MeasureSpec.makeMeasureSpec( Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, heightMeasureSpec_custom); ViewGroup.LayoutParams params = getLayoutParams(); params.height = getMeasuredHeight(); } }
Pada layout resource file, gunakan custom ListView yang telah dibuat di atas.
<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:fadingEdgeLength="0dp" android:fillViewport="true" android:overScrollMode="never" android:scrollbars="none" > <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <al.akh.example.testing.view.ListViewNonScroll android:id="@+id/list_view" android:layout_width="match_parent" android:layout_height="wrap_content"/ > <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/list_view" > ... </RelativeLayout> </RelativeLayout> </ScrollView>
-
Custom ActionBar on Android
Buat activity untuk ActionBar. Misal saya beri nama
custom_actionbar_center.xml
.<?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" xmlns:app="http://schemas.android.com/apk/res-auto" android:background="@android:color/transparent"> <TextView android:id="@+id/title_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:textSize="25sp" android:textColor="#fff" android:gravity="center" android:text="title" /> <ImageButton android:id="@+id/ibtn_bluetooth" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_marginRight="15dp" android:layout_alignParentRight="true" android:foregroundGravity="center" android:background="@null" android:src="@drawable/ic_settings_white_32dp" /> </RelativeLayout>
Tambahkan code berikut pada activity
ActionBar mActionBar = getSupportActionBar(); assert mActionBar != null; mActionBar.setDisplayShowHomeEnabled(false); mActionBar.setDisplayShowTitleEnabled(false); LayoutInflater mInflater = LayoutInflater.from(this); View actionBar = mInflater.inflate(R.layout.custom_actionbar_center, null); TextView mTitleTextView = actionBar.findViewById(R.id.title_text); mTitleTextView.setText(R.string.app_name); mActionBar.setCustomView(actionBar); mActionBar.setDisplayShowCustomEnabled(true); ((Toolbar) actionBar.getParent()).setContentInsetsAbsolute(0,0);
Jika ingin menghilangkan shadow di bawah ActionBar, tambahkan code berikut pada activity:
getSupportActionBar().setElevation(0);
-
apache2: Could not reliably determine the server’s fully qualified domain name
Ada yang pernah mencoba menjalankan ubuntu di perangkat android? Mungkin teman-teman yang pernah mencobanya mengalami masalah yang sama dengan yang saya alami. ketika mencoba menginstall lamp server, muncul error “AH00558: apache2: Could not reliably determine the server’s fully qualified domain name, using ::1. Set the ‘ServerName’ directive globally to suppress this message” ketika akan menjalankan apache server.
Solusi:
tambahkanServerName
pada/etc/apache2/apache2.conf
.sudo nano /etc/apache2/apache2.conf
Pada contoh ini saya tambahkan dibawah
Global configuration
.# Global configuration # ServerName localhost
Langkah selanjutnya, restart apache2.
sudo service apache2 restart
-
No directory, logging in with HOME=/
Ada yang pernah mencoba menjalankan ubuntu di perangkat android? Mungkin teman-teman yang pernah mencobanya mengalami masalah yang sama dengan yang saya alami. ketika mencoba menginstall lamp server, muncul error “No directory, logging in with HOME=/” ketika akan menjalankan mysql server. Hal ini mungkin disebabkan karena kernel android dicompile dengan konfigurasi CONFIG_ANDROID_PARANOID_NETWORK. Masalah ini dapat diperbaiki dengan menambahkan mysql user pada aid_inet dan aid_net_raw groups.
usermod -a -G aid_inet,aid_net_raw mysql su mysql
Langkah selanjutnya tinggal menjalankan mysql.
sudo service mysql start
-
Simpan Layout sebagai Image
Ketika kita membuat suatu aplikasi, terkadang membutuhkan dokumentasi berupa gambar (image).
Berikut adalah salah satu cara untuk membuat image dari layout yang telah dibuat.
Buat method untuk konversi dari view ke bitmap:
private Bitmap getBitmap(View view) { view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)); view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); view.buildDrawingCache(true); Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); Drawable background =view.getBackground(); if (background!=null) { background.draw(canvas); }else{ canvas.drawColor(Color.WHITE); } view.draw(canvas); return bitmap; }
Buat method untuk simpan ke dalam bentuk file:
public void save(Bitmap image, String path) { try { FileOutputStream output = new FileOutputStream(path); image.compress(Bitmap.CompressFormat.PNG, 100, output); output.close(); Toast.makeText(context,"File berhasil disimpan di: "+path+".",Toast.LENGTH_LONG).show(); } catch (FileNotFoundException e) { // e.printStackTrace(); Log.e(TAG, e.toString()); Toast.makeText(context,"Gagal menyimpan file.",Toast.LENGTH_LONG).show(); } catch (IOException e) { // e.printStackTrace(); Log.e(TAG, e.toString()); Toast.makeText(context,"Gagal menyimpan file.",Toast.LENGTH_LONG).show(); } }
Panggil method yang telah dibuat:
image = getBitmap(layout);
Buat fungsi untuk menyimpan image:
btnSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String path = Environment.getExternalStorageDirectory()+"/image.png"; save(image, path); } }); Buat fungsi untuk menampilkan image:
btnView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { bmImage.setImageBitmap(image); } });
Source code:
download -
Custom Color Listview Selected
Pada res, buat file color_selector.xml
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:color="#04b3d3" /> <item android:state_selected="true" android:color="#048563" /> <item android:color="#04b3d3" /> </selector>
Pada textview property, tambahkan android:textColor=”@color/color_selector”.
<TextView android:id="@+id/tv_list" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/color_selector"/>
Pada program java, tambahkan view.setSelected(true);.
list.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { view.setSelected(true); } });
-
Android TimerTask
Pada kali ini akan dicontohkan penggunaan Timer dan TimerTask untuk sekali perhitungan timer maupun timer yang berulang-ulang (repeat) pada jeda waktu tertentu.
Buat variabel yang diperlukan pada program java.
private Timer timer; private TimerTask timerTask;
Buat method startTimer(int time). Method ini digunakan untuk perhitungan timer yang bersifat sekali jalan.
private void startTimer(int time) { stopTimer(); timer = new Timer(); initTimerTask(); timer.schedule(timerTask,time); }
Buat method startRepeatTimer(int time). Method ini digunakan untuk perhitungan timer yang berulang-ulang (repeat).
private void startRepeatTimer(int time) { stopTimer(); timer = new Timer(); initTimerTask(); timer.schedule(timerTask,time,time); }
Buat method stopTimer();
private void stopTimer() { if(timer != null) { timer.cancel(); timer = null; }
Buat method initTimerTask();
private void initTimerTask() { timerTask = new TimerTask() { @Override public void run() { System.out.println("On Timer."); } }; }
Untuk menjalankan timer, tinggal panggil method startTimer(int timer) atau method startRepeatTImer(int timer).
Gunakan Handler jika ingin menampilkan data pada TextView maupun sejenisnya.
Buat object dari class Handler.
Handler timerHandler; timerHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 0: textView.setText(msg.obj); break; default: break; } } };
Gunakan sendMessage untuk menampilkan data.
private void initTimerTask() { timerTask = new TimerTask() { @Override public void run() { Message msg = Message.obtain(null,0,"On Timer."); timerHandler.sendMessage(msg); } }; }
Source code:
donwload