Membuat Multiple Choice ListView Aplikasi Android database MySQL

Tutorial kali membuat multiple choice listview. Floating Action Button sebagai action ketika sudah memilih data yang ada di listview kemudian hasilnya ditampilkan di custom alert dialog. Berikut ini adalah gambar hasilnya :


 
Pertama membuat database dengan nama kuncoro_multiple_choice dengan nama tabel menu dan struktur tabelnya seperti berikut :

Column nameData TypelenghtPrimary KeyNot NullAuto Increment
idbigint10vvv
namavarchar50

 
Membuat web service untuk parsing data aplikasi android.
koneksi.php
Sebagai koneksi aplikasi ke database. Coding-nya disini.
menu.php
Untuk menampilkan data menu makanan. Coding-nya disini.
 

multi choice

 
Buat project baru di Android Studio File ⇒ New Project. Kemudian pilih Blank Activity dan melanjutkannya hingga selesai.

activity_main.xml
Tampilan untuk container floating action button.

<?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"
    android:fitsSystemWindows="true"
    tools:context="com.dedykuncoro.multiplechoice.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/checkbox_on_background" />

</android.support.design.widget.CoordinatorLayout>

 

content_main.xml
Sebagai tampilan dari data-data pada listview.

<?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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.dedykuncoro.multiplechoice.MainActivity"
    tools:showIn="@layout/activity_main">

    <ListView
        android:id="@+id/list_menu"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:listitem = "@layout/list_row"
        android:dividerHeight="1dp"/>

</RelativeLayout>

 

list_row.xml
Sebagai tampilan custom listview yang ada checkbox-nya.

<?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="wrap_content"
    android:padding="@dimen/activity_horizontal_margin">

    <TextView
        android:id="@+id/nama_menu"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:focusable="false"
        android:textStyle="bold"
        android:textSize="16dp"/>

    <CheckBox
        android:id="@+id/cb"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="true"
        android:focusable="false"
        android:clickable="false"
        android:layout_alignParentRight="true"/>

</RelativeLayout>

 

form_submit.xml
Sebagai tampilan hasil dari memilih data pada listview.

<?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">

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:padding="10dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/txt_menu"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="16dp"
            android:padding="10dp"
            android:textStyle="bold" />

    </LinearLayout>

</ScrollView>

 

Buka build.gradle dan tambahkan volley library didalamnya.

compile 'com.mcxiaoke.volley:library:1.0.19'

 

build.gradle

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.1'
    compile 'com.android.support:design:23.2.1'
    compile 'com.mcxiaoke.volley:library:1.0.19'
}

 

Agar project terstruktur dan terorganisir, buat 4 paket dengan nama adapter, app, data, dan volley. Untuk membuat paket baru , klik kanan pada src=>New=>Peckage dan memberikan nama paket . Contoh : com.dedykuncoro.multiplechoice.

struktur

 

Buat class dengan nama LruBitmapCache.java didalam package volley dan tambah coding seperti dibawah ini. Class ini berfingsi untuk mengatur caching network image dalam penyimpanan.
LruBitmapCache.java

package com.dedykuncoro.multiplechoice.volley;

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

import com.android.volley.toolbox.ImageLoader.ImageCache;

public class LruBitmapCache extends LruCache<String, Bitmap> implements
		ImageCache {
	public static int getDefaultLruCacheSize() {
		final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
		final int cacheSize = maxMemory / 8;

		return cacheSize;
	}

	public LruBitmapCache() {
		this(getDefaultLruCacheSize());
	}

	public LruBitmapCache(int sizeInKiloBytes) {
		super(sizeInKiloBytes);
	}

	@Override
	protected int sizeOf(String key, Bitmap value) {
		return value.getRowBytes() * value.getHeight() / 1024;
	}

	@Override
	public Bitmap getBitmap(String url) {
		return get(url);
	}

	@Override
	public void putBitmap(String url, Bitmap bitmap) {
		put(url, bitmap);
	}
}

 

Buat class AppController.java didalam package app dan tambah coding seperti dibawah ini. Class tunggal yang menginisialisasi class global yang diperlukan. Semua objek yang berhubungan dengan volley diinisialisasi di sini.
AppController.java

package com.dedykuncoro.multiplechoice.app;

import android.app.Application;
import android.text.TextUtils;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.dedykuncoro.multiplechoice.volley.LruBitmapCache;

public class AppController extends Application {

	public static final String TAG = AppController.class.getSimpleName();

	private RequestQueue mRequestQueue;
	private ImageLoader mImageLoader;
	LruBitmapCache mLruBitmapCache;

	private static AppController mInstance;

	@Override
	public void onCreate() {
		super.onCreate();
		mInstance = this;
	}

	public static synchronized AppController getInstance() {
		return mInstance;
	}

	public RequestQueue getRequestQueue() {
		if (mRequestQueue == null) {
			mRequestQueue = Volley.newRequestQueue(getApplicationContext());
		}

		return mRequestQueue;
	}

	public ImageLoader getImageLoader() {
		getRequestQueue();
		if (mImageLoader == null) {
			getLruBitmapCache();
			mImageLoader = new ImageLoader(this.mRequestQueue, mLruBitmapCache);
		}

		return this.mImageLoader;
	}

	public LruBitmapCache getLruBitmapCache() {
		if (mLruBitmapCache == null)
			mLruBitmapCache = new LruBitmapCache();
		return this.mLruBitmapCache;
	}

	public <T> void addToRequestQueue(Request<T> req, String tag) {
		req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
		getRequestQueue().add(req);
	}

	public <T> void addToRequestQueue(Request<T> req) {
		req.setTag(TAG);
		getRequestQueue().add(req);
	}

	public void cancelPendingRequests(Object tag) {
		if (mRequestQueue != null) {
			mRequestQueue.cancelAll(tag);
		}
	}

}

 

Buat class Data.java didalam package data dan tambahkan coding seperti dibawah ini. Class ini berfungsi sebagai membuat objek untuk setiap item yang diparsing JSON. Objek ini berisi informasi seperti nama, dan boolean checkbox.
Data.java

package com.dedykuncoro.multiplechoice.data;

/**
 * Created by Kuncoro on 20/03/2016.
 */
public class Data {
    private String menu;
    private boolean check;

    public Data() {}

    public Data(String menu, boolean check) {
        this.menu = menu;
        this.check = check;
    }

    public String getMenu() {
        return menu;
    }

    public void setMenu(String menu) {
        this.menu = menu;
    }

    public boolean isCheckbox() {
        return check;
    }

    public void setCheckbox(boolean check) {
        this.check = check;
    }
}

 

Buat class Adapter.java didalam package adapter dan tambahkan coding seperti dibawah ini. Class ini berfungsi sebagai menampilkan data seperti nama menu makanan dan checkbox ke dalam listview.
Adapter.java

package com.dedykuncoro.multiplechoice.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;

import com.dedykuncoro.multiplechoice.R;
import com.dedykuncoro.multiplechoice.data.Data;

import java.util.ArrayList;

/**
 * Created by Kuncoro on 20/03/2016.
 */
public class Adapter extends BaseAdapter {

    private Context activity;
    private ArrayList<Data> data;
    private static LayoutInflater inflater = null;
    private View vi;
    private ViewHolder viewHolder;

    public Adapter(Context context, ArrayList<Data> items) {
        this.activity = context;
        this.data = items;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int i) {
        return i;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int position, View view, ViewGroup viewGroup) {
        vi = view;
        final int pos = position;
        Data items = data.get(pos);

        if(view == null) {
            vi = inflater.inflate(R.layout.list_row, null);
            viewHolder = new ViewHolder();
            viewHolder.checkBox = (CheckBox) vi.findViewById(R.id.cb);
            viewHolder.menu = (TextView) vi.findViewById(R.id.nama_menu);
            vi.setTag(viewHolder);
        }else {
            viewHolder = (ViewHolder) view.getTag();
            viewHolder.menu.setText(items.getMenu());
        }

        if(items.isCheckbox()){
            viewHolder.checkBox.setChecked(true);
        } else {
            viewHolder.checkBox.setChecked(false);
        }

        return vi;
    }

    public ArrayList<Data> getAllData(){
        return data;
    }

    public void setCheckBox(int position){
        Data items = data.get(position);
        items.setCheckbox(!items.isCheckbox());
        notifyDataSetChanged();
    }

    public class ViewHolder{
        TextView menu;
        CheckBox checkBox;
    }
}

 

Buka class MainActivity.java dan tambahkan coding seperti dibawah ini. Class ini berfungsi menampilkan data nama menu makanan dalam listview dari web service volley JsonArrayRequest. Setelah diparsing, semua data JSON Array akan disimpan pada objek Data.
MainActivity.java

package com.dedykuncoro.multiplechoice;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.dedykuncoro.multiplechoice.adapter.Adapter;
import com.dedykuncoro.multiplechoice.app.AppController;
import com.dedykuncoro.multiplechoice.data.Data;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Kuncoro on 20/03/2016.
 */
public class MainActivity extends AppCompatActivity {

    Toolbar toolbar;
    FloatingActionButton fab;
    ListView list;
    TextView txt_menu;
    String dipilih;
    private static final String TAG = MainActivity.class.getSimpleName();

    Adapter adapter;
    ProgressDialog pDialog;

    List<Data> itemList = new ArrayList<Data>();

    // Sesuaikan dengan IP Address PC/LAptop atau ip emulator bawaan android 10.0.2.2
    private static String url = "http://172.20.10.2/android/kuncoro_multiple_choice/menu.php";

    public static final String TAG_NAMA = "nama";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        fab     = (FloatingActionButton) findViewById(R.id.fab);
        list    = (ListView) findViewById(R.id.list_menu);

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String checkbox = "";
                for (Data hold : adapter.getAllData()) {
                    if (hold.isCheckbox()) {
                        checkbox += "\n" + hold.getMenu();
                    }
                }
                if (!checkbox.isEmpty()) {
                    dipilih = checkbox;
                } else {
                    dipilih = "Anda Belum Memilih Menu.";
                }

                formSubmit(dipilih);
            }
        });

        callVolley();

        adapter = new Adapter(this, (ArrayList<Data>) itemList);
        list.setAdapter(adapter);

        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                adapter.setCheckBox(position);
            }
        });

    }

    private void formSubmit(String hasil){
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        LayoutInflater inflater = getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.form_submit, null);
        dialog.setView(dialogView);
        dialog.setIcon(R.mipmap.ic_launcher);
        dialog.setTitle("Menu Yang Dipilih");
        dialog.setCancelable(true);

        txt_menu = (TextView) dialogView.findViewById(R.id.txt_menu);

        txt_menu.setText(hasil);

        dialog.setNeutralButton("CLOSE", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        dialog.show();
    }

    private void callVolley(){
        itemList.clear();
        // menapilkan dialog loading
        pDialog = new ProgressDialog(this);
        pDialog.setMessage("Loading...");
        showDialog();

        // membuat request JSON
        JsonArrayRequest jArr = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        hideDialog();

                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {
                                JSONObject obj = response.getJSONObject(i);

                                Data item = new Data();

                                item.setMenu(obj.getString(TAG_NAMA));

                                // menambah item ke array
                                itemList.add(item);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        // notifikasi adanya perubahan data pada adapter
                        adapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hideDialog();
            }
        });

        // menambah request ke request queue
        AppController.getInstance().addToRequestQueue(jArr);
    }

    private void showDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hideDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }

}

 

Tambahkan perijinan INTERNET dan android:name=”.app.AppController” pada application pada AndroidManifest.xml.
AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.dedykuncoro.multiplechoice">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:name=".app.AppController"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

 
Run Aplikasinya.
 

Download Source Code :

Please share 🙂


Share on FacebookTweet about this on TwitterShare on Google+Pin on PinterestShare on LinkedInEmail this to someone
close