Menampilkan Database ke Android ?

Assalamualaikum Guys, sekarang saya akan memberikan tutorial cara menampilkan database ke aplikasi : 

1. Buat Aplikasi "Master Database"

2. Pilih Base Activity

3. Lengkapi Kode Activity_main : 

<?xml version="1.0" encoding="utf-8"?><android.support.v4.widget.DrawerLayout    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:id="@+id/drawer_layout"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:fitsSystemWindows="true"    tools:openDrawer="start">

    <include        layout="@layout/app_bar_main"        android:layout_width="match_parent"        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView        android:id="@+id/nav_view"        android:layout_width="wrap_content"        android:layout_height="match_parent"        android:layout_gravity="start"        android:fitsSystemWindows="true"        app:headerLayout="@layout/nav_header_main"        app:menu="@menu/activity_main_drawer" />

    </android.support.v4.widget.DrawerLayout>



4. Main Activity : 

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private Fragment fragment;

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

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        fragment = new TampilSiswaFragment();
        showFragment(fragment);
    }

    private void showFragment(Fragment fragment) {
        getSupportFragmentManager().beginTransaction().replace(R.id.main_container, fragment).commit();
    }

    @Override    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroidManifest.xml.        int id = item.getItemId();

        //noinspection SimplifiableIfStatement        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}


5. Buat Class (SiswaAdapter) dan lengkapi sebagai berikut : 

class SiswaAdapter extends RecyclerView.Adapter<SiswaAdapter.ViewHolder> {

    private Context context;
    private ArrayList<HashMap<String, String>> list_data;

    SiswaAdapter(FragmentActivity activity, ArrayList<HashMap<String, String>> listDataSiswa) {
        context = activity;
        list_data = listDataSiswa;
    }

    @NonNull    @Override    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(context).inflate(R.layout.siswa_item, viewGroup, false);
        return new ViewHolder(view);
    }

    @Override    public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) {
        viewHolder.showDataAtRow(list_data.get(i));
    }

    @Override    public int getItemCount() {
        return list_data.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        private TextView item_namasiswa;

        ViewHolder(@NonNull View itemView) {
            super(itemView);

            item_namasiswa = itemView.findViewById(R.id.item_namasiswa);
        }

        void showDataAtRow(HashMap<String, String> stringStringHashMap) {
            item_namasiswa.setText(stringStringHashMap.get("nama"));
        }
    }
}

6. Buat Activity TampilSiswaFragment dan lengkapi kodenya : 

public class TampilSiswaFragment extends Fragment {


    public TampilSiswaFragment() {
        // Required empty public constructor    }

    private RecyclerView lv_siswa;
    private SwipeRefreshLayout swipesiswa;
    private ProgressBar pgsiswa;

    private ArrayList<HashMap<String, String>> listDataSiswa;
    private static String TAG_JSON = "tag_json";
    private String url;

    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment        return inflater.inflate(R.layout.fragment_tampil_siswa, container, false);
    }

    @Override    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        lv_siswa = (RecyclerView) view.findViewById(R.id.lv_siswa);
        swipesiswa = (SwipeRefreshLayout) view.findViewById(R.id.swipeSiswa);
        pgsiswa = (ProgressBar) view.findViewById(R.id.pg_siswa);
        pgsiswa.setVisibility(View.GONE);

        lv_siswa.setLayoutManager(new LinearLayoutManager(getActivity()));

        listDataSiswa = new ArrayList<HashMap<String, String>>();

        url = "http://192.168.70.209/SMPIDN/onlinedatabase/apitampilsiswa.php";

        showData();
    }

    private void showData() {
        pgsiswa.setVisibility(View.VISIBLE);

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,
                null, new Response.Listener<JSONObject>() {
            @Override            public void onResponse(JSONObject response) {
                pgsiswa.setVisibility(View.GONE);
                // emnampilkan data yang di dapat ke logcat                Log.d(TAG_JSON, "onResponse: " + response.toString());
                try {
                    // mengambil json array pada data                    JSONArray jsonArray = response.getJSONArray("siswa");
                    // generate index untuk mengambil json objek di dalam json array siswa per row/index                    for (int index = 0; index < jsonArray.length(); index++) {
                        // mengambil json objek di dalam json array berdasarkan index yahng sudah tergenerate                        JSONObject jsonObject = jsonArray.getJSONObject(index);
                        // data yang sudah didapat dipilah lagi per field kemudian di masukkan ke dalam map                        HashMap<String, String> map = new HashMap<>();
                        // di dalam map, kita masukan key dan value dari data                        map.put("id", jsonObject.getString("id_siswa"));
                        map.put("nama", jsonObject.getString("nama_siswa"));
                        map.put("alamat", jsonObject.getString("alamat_siswa"));
                        // kita masukkan map field tadi ke dalam array list                        listDataSiswa.add(map);
                        // kirim array list ke dalam adapter                        SiswaAdapter siswaAdapter = new SiswaAdapter(getActivity(), listDataSiswa);
                        lv_siswa.setAdapter(siswaAdapter);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override            public void onErrorResponse(VolleyError error) {
                pgsiswa.setVisibility(View.GONE);
                Toast.makeText(getActivity(), "Gagal konek ke server", Toast.LENGTH_SHORT).show();
            }
        });

        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        requestQueue.add(jsonObjectRequest);
    }
}

7. buat siswa_item.xml dan lengkapi kodenya : 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginLeft="@dimen/card_margin_horizontal"        android:layout_marginTop="@dimen/card_vertical_margin"        android:layout_marginRight="@dimen/card_margin_horizontal"        android:layout_marginBottom="@dimen/card_vertical_margin">

        <LinearLayout            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:orientation="vertical">

            <TextView                android:id="@+id/item_namasiswa"                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:padding="@dimen/activity_horizontal_margin"                android:text="@string/app_name"                android:textSize="@dimen/name_size" />
        </LinearLayout>
    </android.support.v7.widget.CardView>
</RelativeLayout>

8. Buat layout (fragment_tampil_siswa.xml) dan lengkapi kodenya sebagai berikut :


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".TampilSiswaFragment">

    <android.support.v4.widget.SwipeRefreshLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/swipeSiswa">

        <android.support.v7.widget.RecyclerView            android:layout_width="match_parent"            android:layout_height="match_parent"            android:id="@+id/lv_siswa"/>
    </android.support.v4.widget.SwipeRefreshLayout>

    <ProgressBar        android:id="@+id/pg_siswa"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerInParent="true"/>
</RelativeLayout>


Selesai !

Nah, nanti tampilannya akan menjadi seperti ini :


Semoga Bermanfaat !

Assalamualaikum !!!


Komentar