Nothing Special   »   [go: up one dir, main page]

Laporan Pemrograman Mobile 2

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 63

LAPORAN

PEMROGRAMAN MOBILE 2

PENYUSUN:
Rahmad Zulhilmi
16.10.031.802.089

PROGRAM STUDI TEKNIK INFORMATIKA


SEKOLAH TINGGI MANAJEMEN INFORMATIKA DAN KOMPUTER AMIK RIAU
STMIK Amik Riau
2018
1.Tampilan Home

Source Code
Frg_welcome.java
package com.rahmad.lab2menu;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;

import com.rahmad.lab2menu.R;

/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link frg_welcome.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link frg_welcome#newInstance} factory method to
* create an instance of this fragment.
*/
public class frg_welcome extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters


private String mParam1;
private String mParam2;

private OnFragmentInteractionListener mListener;

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

/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment frg_welcome.
*/
// TODO: Rename and change types and number of parameters
public static frg_welcome newInstance(String param1, String param2) {
frg_welcome fragment = new frg_welcome();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment

new myikc().execute();
return inflater.inflate(R.layout.fragment_frg_welcome, container, false);
}

// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}

@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}

@Override
public void onDetach() {
super.onDetach();
mListener = null;
}

/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}

class myikc extends AsyncTask<String, String, String> {

@Override
protected void onPreExecute() {
super.onPreExecute();

protected String doInBackground(String... args) {

return null;
}

protected void onPostExecute(String file_url) {


String urlPictureMain, urlCoverMain, urlPictureSecond;

Button btnHome=(Button) getView().findViewById(R.id.btnRefresh);


btnHome.setText("Selamat Datang di Home");

btnHome.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// do something

Toast.makeText(getActivity(), "Loading Home",


Toast.LENGTH_LONG).show();
new myikc().execute();

}
});

WebView wv =(WebView) getView().findViewById(R.id.wvAflowz);


WebSettings webSettings = wv.getSettings();
webSettings.setJavaScriptEnabled(true);
//tambahan script untuk invoke html javascript

String url="http://10.127.199.216/uasrahmad/login.html";

wv.loadUrl(url);
wv.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});

wv.addJavascriptInterface(new WebAppInterface(getActivity()),
"MyAndroid");

wv.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String
description, String
failingUrl) {
Toast.makeText(getActivity(), "Mohon periksa koneksi data internet
anda ...", Toast.LENGTH_SHORT).show();
WebView wv =(WebView) getView().findViewById(R.id.wvAflowz);

wv.loadDataWithBaseURL("file:///android_asset/", "<img
src=\"file:///android_res/drawable/internetdisc.png\"/>", "text/html", "utf-8", null);
}
});

}
}

public class WebAppInterface {


Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
@JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
@JavascriptInterface
public void PesanToast(String nama,String pesan) {
showToast("Pesan dari "+nama+":"+pesan);
((AppCompatActivity)
getActivity()).getSupportActionBar().setTitle("Button2");
}
@JavascriptInterface
public void showDialog(String nama,String pesan) {
DialogInterface.OnClickListener dialogClickListener = new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
{
}
break;
case DialogInterface.BUTTON_NEGATIVE:
{
}
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(pesan)
.setCancelable(false)
.setTitle("Pesan Dari:"+nama)
.setPositiveButton("Ya", dialogClickListener)
.show();
((AppCompatActivity)
getActivity()).getSupportActionBar().setTitle("Button1");
}
}
}

frg_welcome.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.rahmad.lab2menu.frg_welcome">

<!-- TODO: Update blank fragment layout -->

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

<Button
android:text="Refresh"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnRefresh" />
<WebView
android:id="@+id/wvAflowz"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/btnRefresh"
android:layout_marginTop="0dp" />
</RelativeLayout>
</FrameLayout>

2.Cari data
Frg_search.java
package com.rahmad.lab2menu;

import android.content.Context;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.rahmad.lab2menu.R;

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

import java.util.ArrayList;

/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link frg_search.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link frg_search#newInstance} factory method to
* create an instance of this fragment.
*/
public class frg_search extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters


private String mParam1;
private String mParam2;

private OnFragmentInteractionListener mListener;

//--deklarasi data JSON


/*
id_rec: "20170105135026564",
user_id: "asti",
user_name: "astimen",
department: "Finance",
user_sex: "Male",
role_admin: "true",
role_user: "false"
success: 1
*/

private static String id_rec="";


private static String user_id="";
private static String user_name="";
private static String department="";
private static String user_sex="";
private static String role_admin="";
private static String role_user="";
private static String img_user="";
private static Integer istatus;

private int nom=0;


private static ArrayList<SearchResults> results = new ArrayList<SearchResults>();
private SearchResults sr1 = new SearchResults();

//----end deklarasi

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

/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment frg_search.
*/
// TODO: Rename and change types and number of parameters
public static frg_search newInstance(String param1, String param2) {
frg_search fragment = new frg_search();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment

new myikc().execute();

return inflater.inflate(R.layout.fragment_frg_search, container, false);


}

// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}

@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}

@Override
public void onDetach() {
super.onDetach();
mListener = null;
}

/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}

//--myikc--

class myikc extends AsyncTask<String, String, String> {

@Override
protected void onPreExecute() {
super.onPreExecute();

protected String doInBackground(String... args) {


return null;
}

protected void onPostExecute(String file_url) {

Button btn_search = (Button) getView().findViewById(R.id.btnSearch);


btn_search.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// do something

//Toast.makeText(getActivity(), "Button Save Clicked",


Toast.LENGTH_LONG).show();

EditText etKriteria = (EditText)


getView().findViewById(R.id.txtKriteria);
final String setKriteria=etKriteria.getText().toString();

if(setKriteria.trim().length()==0)
{
pesandialog("Entrian Kriteria tidak boleh kosong ...!");
etKriteria.requestFocus();
return;

//------volley

final String REGISTER_URL =


"http://192.168.43.79/uasrahmad/web_cari.php?kriteria="+setKriteria;

JsonObjectRequest jsonRequest = new JsonObjectRequest


(Request.Method.GET, REGISTER_URL, null, new
Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// the response is already constructed as a
JSONObject!

//Toast.makeText(getActivity(),
response.toString(), Toast.LENGTH_LONG).show();

//---proses data response

try {

//istatus=response.getInt("success");
JSONArray ja =
response.getJSONArray("datauser");

results.clear();
nom=0;
for (int i = 0; i < ja.length(); i++) {

JSONObject c = ja.getJSONObject(i);

// Storing each json item in variable


nom=nom+1;

id_rec = c.getString("id_rec");
user_id = c.getString("user_id");
user_name = c.getString("user_name");
department = c.getString("department");
user_sex = c.getString("user_sex");
role_admin = c.getString("role_admin");
role_user = c.getString("role_user");
img_user = c.getString("img_user");

sr1 = new SearchResults();


sr1.set_id_rec(id_rec);
sr1.set_user_id(user_id);
sr1.set_user_name(user_name);
sr1.set_department(department);
sr1.set_user_sex(user_sex);
sr1.set_role_admin(role_admin);
sr1.set_role_user(role_user);
sr1.set_img_user(img_user);

results.add(sr1);

} catch (JSONException e) {
e.printStackTrace();
}

TampilListUser();
//------------------------
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(getActivity(),"Server :" +
error.toString(), Toast.LENGTH_LONG).show();
}
}){

};

RequestQueue requestQueue = Volley.newRequestQueue(getContext());


requestQueue.add(jsonRequest);

//-------------
}
});

}
}

void pesandialog(String pesan){


DialogInterface.OnClickListener dialogClickListener = new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which){
switch (which){
case DialogInterface.BUTTON_POSITIVE:
Toast.makeText(getActivity(), "Isi kembali entrian yang kosong
...", Toast.LENGTH_LONG).show();
break;
case DialogInterface.BUTTON_NEGATIVE:
break;

}
}

};

AlertDialog.Builder builder = new AlertDialog.Builder(getView().getContext());


builder
.setTitle("AflowZ")
.setMessage(pesan)
.setCancelable(false)
.setPositiveButton("OK",dialogClickListener)
.show();

//--endMyIkc--

public class SearchResults {


private String id_rec = "";
private String user_id = "";
private String user_name = "";
private String department = "";
private String user_sex = "";
private String role_admin = "";
private String role_user = "";
private String img_user = "";

//------id_rec
public void set_id_rec(String id_rec) {
this.id_rec = id_rec;
}
public String get_id_rec() {
return id_rec;
}
//------user_id
public void set_user_id(String user_id) {
this.user_id = user_id;
}
public String get_user_id() {
return user_id;
}

//------user_name
public void set_user_name(String user_name) {
this.user_name = user_name;
}
public String get_user_name() {
return user_name;
}
//------department
public void set_department(String department) {
this.department = department;
}
public String get_department() {
return department;
}

//------user_sex
public void set_user_sex(String user_sex) {
this.user_sex = user_sex;
}
public String get_user_sex() {
return user_sex;
}

//------role_admin
public void set_role_admin(String role_admin) {
this.role_admin = role_admin;
}
public String get_role_admin() {
return role_admin;
}

//------role_user
public void set_role_user(String role_user) {
this.role_user = role_user;
}
public String get_role_user() {
return role_user;
}

//------img_user
public void set_img_user(String img_user) {
this.img_user = img_user;
}
public String get_img_user() {
return img_user;
}

public class MyCustomBaseAdapter extends BaseAdapter {


private ArrayList<SearchResults> searchArrayList;
private LayoutInflater mInflater;

public MyCustomBaseAdapter(Context context, ArrayList<SearchResults> results)


{
searchArrayList = results;
mInflater = LayoutInflater.from(context);
}

public int getCount() {


return searchArrayList.size();
}

public Object getItem(int position) {


return searchArrayList.get(position);
}

public long getItemId(int position) {


return position;
}

public View getView(int position, View convertView, ViewGroup parent) {


ViewHolder holder;

if (convertView == null) {
convertView = mInflater.inflate(R.layout.datauser_list_view, null);
holder = new ViewHolder();
holder.txt_id_rec = (TextView)
convertView.findViewById(R.id.txtIdRec);
holder.txt_user_id = (TextView)
convertView.findViewById(R.id.txtUserId);
holder.txt_user_name = (TextView)
convertView.findViewById(R.id.txtUserName);
holder.txt_department = (TextView)
convertView.findViewById(R.id.txtDepartment);
holder.txt_user_admin = (TextView)
convertView.findViewById(R.id.txtRoleAdmin);
holder.txt_user_role = (TextView)
convertView.findViewById(R.id.txtRoleUser);

holder.imgPhoto = (ImageView) convertView.findViewById(R.id.imgUser);


convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}

holder.txt_id_rec.setText(searchArrayList.get(position).get_id_rec());
holder.txt_user_id.setText(searchArrayList.get(position).get_user_id());

holder.txt_user_name.setText(searchArrayList.get(position).get_user_name());

holder.txt_department.setText(searchArrayList.get(position).get_department());

holder.txt_user_admin.setText(searchArrayList.get(position).get_role_admin());

holder.txt_user_role.setText(searchArrayList.get(position).get_role_user());

if(searchArrayList.get(position).get_role_admin().equals("true"))
{
holder.txt_user_admin.setText("Admin");
}
else
{
holder.txt_user_admin.setText("Not Admin");
}

if(searchArrayList.get(position).get_role_user().equals("true"))
{
holder.txt_user_role.setText("User");
}
else
{
holder.txt_user_role.setText("Not User");
}

if(searchArrayList.get(position).get_img_user().equals("tidak ada"))
{
if(searchArrayList.get(position).get_user_sex().equals("Male"))
{
holder.imgPhoto.setImageResource(R.drawable.male);
holder.imgPhoto.setTag("Male");
}
else
{
holder.imgPhoto.setImageResource(R.drawable.famele);
holder.imgPhoto.setTag("Female");
}

}
else
{
String url_photo_oke="http://10.127.234.63/uasrahmad"+
searchArrayList.get(position).get_img_user();
Glide.with(getActivity())
.load(url_photo_oke)
.into(holder.imgPhoto);
}

return convertView;
}

class ViewHolder {
ImageView imgPhoto;
TextView txt_id_rec;
TextView txt_user_id;
TextView txt_user_name;
TextView txt_department;
TextView txt_user_admin;
TextView txt_user_role;

private void TampilListUser()


{
ArrayList<SearchResults> searchResults = results;

final ListView lv1 = (ListView) getView().findViewById(R.id.lvDataUser);


lv1.setAdapter(new MyCustomBaseAdapter(getActivity(), searchResults));

lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {

//Toast.makeText(getActivity(), "User Name : " + user_name +" clicking


...", Toast.LENGTH_LONG).show();
//--kirim data ke frg_edit

String bid_rec = ((TextView)


view.findViewById(R.id.txtIdRec)).getText().toString();
String buser_id = ((TextView)
view.findViewById(R.id.txtUserId)).getText().toString();
String buser_name = ((TextView)
view.findViewById(R.id.txtUserName)).getText().toString();
String bdepartment = ((TextView)
view.findViewById(R.id.txtDepartment)).getText().toString();

ImageView imgUser = ((ImageView) view.findViewById(R.id.imgUser));

String buser_sex = imgUser.getTag().toString();

String brole_admin = ((TextView)


view.findViewById(R.id.txtRoleAdmin)).getText().toString();
String brole_user = ((TextView)
view.findViewById(R.id.txtRoleUser)).getText().toString();

Bundle bundle_search = new Bundle();


bundle_search.putString("id_rec", bid_rec);
bundle_search.putString("user_id", buser_id);
bundle_search.putString("user_name", buser_name);
bundle_search.putString("department", bdepartment);
bundle_search.putString("user_sex", buser_sex);
bundle_search.putString("role_admin", brole_admin);
bundle_search.putString("role_user", brole_user);

//set Fragmentclass Arguments

android.support.v4.app.Fragment mFragment = null;


mFragment = frg_edit.newInstance(bundle_search);
mFragment.setArguments(bundle_search);

FragmentManager fragmentManager =
getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frm_utama, mFragment)
.addToBackStack(null)
.commit();

}
});

frg_search.xml
<FrameLayout 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.rahmad.lab2menu.frg_search">

<!-- TODO: Update blank fragment layout -->

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/background_light">

<LinearLayout
android:id="@+id/cari"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<TextView
android:text="Kriteria"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView2"
android:fontFamily="sans-serif"
android:textAlignment="center"
android:layout_weight="2"
android:textSize="18sp" />

<EditText
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:inputType="textPersonName"
android:id="@+id/txtKriteria"
android:layout_weight="10" />

<Button
android:text="Find"
android:layout_width="68dp"
android:layout_height="wrap_content"
android:id="@+id/btnSearch"
android:layout_weight="1"/>

</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/cari">

<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/lvDataUser" />
</LinearLayout>

</RelativeLayout>

</FrameLayout>

3.Registrasi Data

Frg_entry.java
package com.rahmad.lab2menu;

import android.content.Context;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.rahmad.lab2menu.R;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;

/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link frg_entry.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link frg_entry#newInstance} factory method to
* create an instance of this fragment.
*/
public class frg_entry extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters


private String mParam1;
private String mParam2;

private OnFragmentInteractionListener mListener;

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

/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment frg_entry.
*/
// TODO: Rename and change types and number of parameters
public static frg_entry newInstance(String param1, String param2) {
frg_entry fragment = new frg_entry();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}

public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {


inflater.inflate(R.menu.menu_entry, menu);
super.onCreateOptionsMenu(menu, inflater);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {

case R.id.action_entry_search:
{
((AppCompatActivity)
getActivity()).getSupportActionBar().setTitle("Search Data");

android.support.v4.app.Fragment mFragment = null;


mFragment = frg_search.newInstance("0","0");

FragmentManager fragmentManager =
getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frm_utama, mFragment)
.setCustomAnimations(R.anim.enter_from_left,
R.anim.exit_to_left, R.anim.enter_from_right, R.anim.exit_to_right)
.addToBackStack(null)
.commit();
}
}
return super.onOptionsItemSelected(item);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {

new myikc().execute();

// Inflate the layout for this fragment


return inflater.inflate(R.layout.fragment_frg_entry, container, false);

// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}

@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}

@Override
public void onDetach() {
super.onDetach();
mListener = null;
}

/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}

class myikc extends AsyncTask<String, String, String> {

@Override
protected void onPreExecute() {
super.onPreExecute();

protected String doInBackground(String... args) {

return null;
}

protected void onPostExecute(String file_url) {

Button btn_new = (Button) getView().findViewById(R.id.btnNew);


btn_new.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// do something

Toast.makeText(getActivity(), "Button New Clicked",


Toast.LENGTH_LONG).show();

//--ganti title bar

//---jika button save click

//---membuat idrec timestamp 17 digit TTTTBBHHJJMMDDmmm


//---Tahun-Bulan-Hari-Jam_Menit-Detik-MiliSecond

Calendar calendar = Calendar.getInstance(TimeZone.getDefault());


int iYear = calendar.get(Calendar.YEAR);
int iMonth = calendar.get(Calendar.MONTH)+1;
int iDay = calendar.get(Calendar.DAY_OF_MONTH);
int iHour = calendar.get(Calendar.HOUR_OF_DAY);
int iMinute = calendar.get(Calendar.MINUTE);
int iSecond = calendar.get(Calendar.SECOND);
int iMiliSecond = calendar.get(Calendar.MILLISECOND);

String siYear = Integer.toString(iYear);


String siMonth = Integer.toString(iMonth);
String siDay = Integer.toString(iDay);
String siHour = Integer.toString(iHour);
String siMinute = Integer.toString(iMinute);
String siSecond = Integer.toString(iSecond);
String siMiliSecond = Integer.toString(iMiliSecond);

if(iMonth<10)
{
siMonth = "0"+ siMonth;
}

if(iDay<10)
{
siDay = "0"+ siDay;
}

if(iHour<10)
{
siHour = "0"+ siHour;
}

if(iMinute<10)
{
siMinute = "0"+ siMinute;
}

if(iSecond<10)
{
siSecond = "0"+ siSecond;
}

if(iMiliSecond<100)
{
if(iMiliSecond<10)
{
siMiliSecond = "00"+ siMiliSecond;
}
else
{
siMiliSecond = "0"+ siMiliSecond;
}
}

String idrec = siYear + siMonth + siDay + siHour + siMinute +


siSecond + siMiliSecond;

EditText etIdRec = (EditText)


getView().findViewById(R.id.txtIdRec);
etIdRec.setText(idrec);

}
});
Button btn_save = (Button) getView().findViewById(R.id.btnSave);
btn_save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// do something

Toast.makeText(getActivity(), "Button Save Clicked",


Toast.LENGTH_LONG).show();

EditText etIdRec = (EditText)


getView().findViewById(R.id.txtIdRec);
final String dtxtIdrec=etIdRec.getText().toString();

EditText etUserId = (EditText)


getView().findViewById(R.id.txtUserId);
final String dtxtUserId=etUserId.getText().toString();

final String dtxtUserName = ((EditText)


getView().findViewById(R.id.txtUserName)).getText().toString();
final String dtxtPassword = ((EditText)
getView().findViewById(R.id.txtPassword)).getText().toString();
final String dtxtPassword2 = ((EditText)
getView().findViewById(R.id.txtPassword2)).getText().toString();
final String dspnDepartment = ((Spinner)
getView().findViewById(R.id.spnDepartment)).getSelectedItem().toString();

final int drbSex = ((RadioGroup)


getView().findViewById(R.id.rgSex)).getCheckedRadioButtonId();
final RadioButton rbSex = ((RadioButton)
getView().findViewById(drbSex));
final String sdrbSex = rbSex.getText().toString();

final Boolean bolRoleAdmin=((CheckBox)


getView().findViewById(R.id.cbxAdmin)).isChecked();
final Boolean bolRoleUser=((CheckBox)
getView().findViewById(R.id.cbxUser)).isChecked();

final String sbolRoleAdmin = bolRoleAdmin.toString();


final String sbolRoleUser = bolRoleUser.toString();

if(dtxtIdrec.trim().length()==0)
{
pesandialog("Entrian Id Record tidak boleh kosong ...!");
etIdRec.requestFocus();

}
else if(dtxtUserId.trim().length()==0)
{
pesandialog("Entrian User Id tidak boleh kosong ...!");
etUserId.requestFocus();

else if(dtxtUserName.trim().length()==0)
{
pesandialog("Entrian User Name tidak boleh kosong ...!");
((EditText)
getView().findViewById(R.id.txtUserName)).requestFocus();

else if(dtxtPassword.trim().length()==0)
{
pesandialog("Entrian Password tidak boleh kosong ...!");
((EditText)
getView().findViewById(R.id.txtPassword)).requestFocus();

}
else if(dtxtPassword2.trim().length()==0)
{
pesandialog("Entrian Password kedua tidak boleh kosong ...!");
((EditText)
getView().findViewById(R.id.txtPassword2)).requestFocus();

//pengecekan password satu dan dua

if(!dtxtPassword.equals(dtxtPassword2))
{
pesandialog("Password dan Pasword2 tidak sama ...!");
((EditText)
getView().findViewById(R.id.txtPassword2)).requestFocus();
}

//------volley

final String REGISTER_URL =


"http://192.168.43.79/uasrahmad/volleySimpan.php";

final String KEY_ID_REC = "id_rec";


final String KEY_USER_ID = "user_id";
final String KEY_USER_NAME = "user_name";
final String KEY_PASSWORD = "password";
final String KEY_DEPARTMENT = "department";
final String KEY_USER_SEX = "user_sex";
final String KEY_ROLE_ADMIN = "role_admin";
final String KEY_ROLE_USER = "role_user";

StringRequest stringRequest = new


StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(getActivity(),"Server : " +
response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),"Server :" +
error.toString(), Toast.LENGTH_LONG).show();
}
}){
@Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_ID_REC,dtxtIdrec);
params.put(KEY_USER_ID,dtxtUserId);
params.put(KEY_USER_NAME, dtxtUserName);
params.put(KEY_PASSWORD, dtxtPassword);
params.put(KEY_DEPARTMENT, dspnDepartment);
params.put(KEY_USER_SEX, sdrbSex);
params.put(KEY_ROLE_ADMIN, sbolRoleAdmin);
params.put(KEY_ROLE_USER, sbolRoleUser);

return params;
}

};

RequestQueue requestQueue = Volley.newRequestQueue(getContext());


requestQueue.add(stringRequest);

//-------------

}
});

}
}

void pesandialog(String pesan){


DialogInterface.OnClickListener dialogClickListener = new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which){
switch (which){
case DialogInterface.BUTTON_POSITIVE:
Toast.makeText(getActivity(), "Isi kembali entrian yang kosong
...", Toast.LENGTH_LONG).show();
break;
case DialogInterface.BUTTON_NEGATIVE:
break;

}
}

};

AlertDialog.Builder builder = new AlertDialog.Builder(getView().getContext());


builder
.setTitle("AflowZ")
.setMessage(pesan)
.setCancelable(false)
.setPositiveButton("OK",dialogClickListener)
.show();

}
frg_entry.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.rahmad.lab2menu.frg_entry">

<!-- TODO: Update blank fragment layout -->

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

android:background="@android:color/holo_blue_bright"
android:padding="10dip">

<TextView
android:id="@+id/lblIdRec"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Id Record" />

<EditText
android:id="@+id/txtIdRec"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/lblIdRec"
android:background="@android:drawable/editbox_background" />

<TextView
android:id="@+id/lblUserId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/txtIdRec"
android:text="User Id" />

<EditText
android:id="@+id/txtUserId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/lblUserId"
android:background="@android:drawable/editbox_background" />

<TextView
android:id="@+id/lblUserName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/txtUserId"
android:text="User Name" />

<EditText
android:id="@+id/txtUserName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/lblUserName"
android:background="@android:drawable/editbox_background" />

<TextView
android:id="@+id/lblPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/txtUserName"
android:text="Password" />

<EditText
android:id="@+id/txtPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/lblPassword"
android:background="@android:drawable/editbox_background"
android:inputType="textPassword" />

<TextView
android:id="@+id/lblPassword2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/txtPassword"
android:text="Password Check" />

<EditText
android:id="@+id/txtPassword2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/lblPassword2"
android:background="@android:drawable/editbox_background"
android:inputType="textPassword" />

<TextView
android:id="@+id/lblDepartment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/txtPassword2"
android:text="Departement" />

<Spinner
android:id="@+id/spnDepartment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/lblDepartment"
android:entries="@array/department_array"

android:prompt="@string/department_prompt" />

<TextView
android:id="@+id/lblSex"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/spnDepartment"
android:text="Sex" />

<RadioGroup
android:id="@+id/rgSex"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/lblSex"
android:checkedButton="@+id/rbFemale"
android:orientation="horizontal">

<RadioButton
android:id="@+id/rbFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Female" />

<RadioButton
android:id="@+id/rbMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Male" />
</RadioGroup>

<TextView
android:id="@+id/lblRole"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/rgSex"
android:text="Role" />

<CheckBox
android:id="@+id/cbxAdmin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/lblRole"
android:text="Admin" />

<CheckBox
android:id="@+id/cbxUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/lblRole"
android:layout_toRightOf="@id/cbxAdmin"
android:text="User" />

<Button
android:id="@+id/btnSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/cbxUser"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dip"
android:text="SAVE" />

<Button
android:id="@+id/btnNew"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/cbxUser"
android:layout_toLeftOf="@id/btnSave"
android:text="NEW" />

</RelativeLayout>

</FrameLayout>
4.Tujuan Lokasi

Direction Finder.Java
package com.rahmad.lab2menu;

import android.os.AsyncTask;
import com.google.android.gms.maps.model.LatLng;

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class DirectionFinder {


private static final String DIRECTION_URL_API =
"https://maps.googleapis.com/maps/api/directions/json?";
private static final String GOOGLE_API_KEY = "AIzaSyDXMM_zRzEMAweRZ73IcxHPo6-
EuSy_kYg";

private DirectionFinderListener listener;


private String origin;
private String destination;

public DirectionFinder(DirectionFinderListener listener, String origin, String


destination) {
this.listener = listener;
this.origin = origin;
this.destination = destination;
}

public void execute() throws UnsupportedEncodingException {


listener.onDirectionFinderStart();
new DownloadRawData().execute(createUrl());
}

private String createUrl() throws UnsupportedEncodingException {


String urlOrigin = URLEncoder.encode(origin, "utf-8");
String urlDestination = URLEncoder.encode(destination, "utf-8");

return DIRECTION_URL_API + "origin=" + urlOrigin + "&destination=" +


urlDestination + "&key=" + GOOGLE_API_KEY;
}

private class DownloadRawData extends AsyncTask<String, Void, String> {

@Override
protected String doInBackground(String... params) {
String link = params[0];
try {
URL url = new URL(link);
InputStream is = url.openConnection().getInputStream();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));

String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}

return buffer.toString();

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(String res) {
try {
parseJSon(res);
} catch (JSONException e) {
e.printStackTrace();
}
}
}

private void parseJSon(String data) throws JSONException {


if (data == null)
return;

List<Route> routes = new ArrayList<Route>();


JSONObject jsonData = new JSONObject(data);
JSONArray jsonRoutes = jsonData.getJSONArray("routes");
for (int i = 0; i < jsonRoutes.length(); i++) {
JSONObject jsonRoute = jsonRoutes.getJSONObject(i);
Route route = new Route();

JSONObject overview_polylineJson =
jsonRoute.getJSONObject("overview_polyline");
JSONArray jsonLegs = jsonRoute.getJSONArray("legs");
JSONObject jsonLeg = jsonLegs.getJSONObject(0);
JSONObject jsonDistance = jsonLeg.getJSONObject("distance");
JSONObject jsonDuration = jsonLeg.getJSONObject("duration");
JSONObject jsonEndLocation = jsonLeg.getJSONObject("end_location");
JSONObject jsonStartLocation = jsonLeg.getJSONObject("start_location");

route.distance = new Distance(jsonDistance.getString("text"),


jsonDistance.getInt("value"));
route.duration = new Duration(jsonDuration.getString("text"),
jsonDuration.getInt("value"));
route.endAddress = jsonLeg.getString("end_address");
route.startAddress = jsonLeg.getString("start_address");
route.startLocation = new LatLng(jsonStartLocation.getDouble("lat"),
jsonStartLocation.getDouble("lng"));
route.endLocation = new LatLng(jsonEndLocation.getDouble("lat"),
jsonEndLocation.getDouble("lng"));
route.points = decodePolyLine(overview_polylineJson.getString("points"));

routes.add(route);
}

listener.onDirectionFinderSuccess(routes);
}

private List<LatLng> decodePolyLine(final String poly) {


int len = poly.length();
int index = 0;
List<LatLng> decoded = new ArrayList<LatLng>();
int lat = 0;
int lng = 0;

while (index < len) {


int b;
int shift = 0;
int result = 0;
do {
b = poly.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;

shift = 0;
result = 0;
do {
b = poly.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;

decoded.add(new LatLng(
lat / 100000d, lng / 100000d
));
}

return decoded;
}
}

DirectionFinderListener.java
package com.rahmad.lab2menu;

import java.util.List;

public interface DirectionFinderListener {


void onDirectionFinderStart();
void onDirectionFinderSuccess(List<Route> route);
}

Distance.java
package com.rahmad.lab2menu;

public class Distance {


public String text;
public int value;

public Distance(String text, int value) {


this.text = text;
this.value = value;
}
}

Duration.java
package com.rahmad.lab2menu;

public class Duration {


public String text;
public int value;

public Duration(String text, int value) {


this.text = text;
this.value = value;
}
}

MapsActivity.Java
package com.rahmad.lab2menu;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import com.rahmad.lab2menu.R;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,


DirectionFinderListener {

private GoogleMap mMap;


private Button btnFindPath;
private EditText etOrigin;
private EditText etDestination;
private List<Marker> originMarkers = new ArrayList<>();
private List<Marker> destinationMarkers = new ArrayList<>();
private List<Polyline> polylinePaths = new ArrayList<>();
private ProgressDialog progressDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be
used.
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);

btnFindPath = (Button) findViewById(R.id.btnFindPath);


etOrigin = (EditText) findViewById(R.id.etOrigin);
etDestination = (EditText) findViewById(R.id.etDestination);

btnFindPath.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendRequest();
}
});
}

private void sendRequest() {


String origin = etOrigin.getText().toString();
String destination = etDestination.getText().toString();
if (origin.isEmpty()) {
Toast.makeText(this, "Please enter origin address!",
Toast.LENGTH_SHORT).show();
return;
}
if (destination.isEmpty()) {
Toast.makeText(this, "Please enter destination address!",
Toast.LENGTH_SHORT).show();
return;
}

try {
new DirectionFinder(this, origin, destination).execute();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}

@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng hcmus = new LatLng(0.506566, 101.437790);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(hcmus, 18));
originMarkers.add(mMap.addMarker(new MarkerOptions()
.title("Pekanbaru")
.position(hcmus)));

if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) !
= PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[]
permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the
documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mMap.setMyLocationEnabled(true);
}

@Override
public void onDirectionFinderStart() {
progressDialog = ProgressDialog.show(this, "Please wait.",
"Finding direction..!", true);

if (originMarkers != null) {
for (Marker marker : originMarkers) {
marker.remove();
}
}

if (destinationMarkers != null) {
for (Marker marker : destinationMarkers) {
marker.remove();
}
}

if (polylinePaths != null) {
for (Polyline polyline:polylinePaths ) {
polyline.remove();
}
}
}

@Override
public void onDirectionFinderSuccess(List<Route> routes) {
progressDialog.dismiss();
polylinePaths = new ArrayList<>();
originMarkers = new ArrayList<>();
destinationMarkers = new ArrayList<>();

for (Route route : routes) {


mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(route.startLocation,
16));
((TextView) findViewById(R.id.tvDuration)).setText(route.duration.text);
((TextView) findViewById(R.id.tvDistance)).setText(route.distance.text);

originMarkers.add(mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.start_blue))
.title(route.startAddress)
.position(route.startLocation)));
destinationMarkers.add(mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.end_green))
.title(route.endAddress)
.position(route.endLocation)));
PolylineOptions polylineOptions = new PolylineOptions().
geodesic(true).
color(Color.BLUE).
width(10);

for (int i = 0; i < route.points.size(); i++)


polylineOptions.add(route.points.get(i));

polylinePaths.add(mMap.addPolyline(polylineOptions));
}
}
}

activitymaps.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="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.rahmad.lab2menu.MapsActivity"
android:orientation="vertical" >
<EditText
android:id="@+id/etOrigin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:enabled="false"
android:text="STMIK Amik Riau " />

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Alamat Tujuan"
android:id="@+id/etDestination"

android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
/>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:text="Cari Alamat"
android:id="@+id/btnFindPath" />
<ImageView
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:layout_width="40dp"
android:layout_height="40dp"
android:src="@drawable/ic_distance"/>
<TextView
android:layout_marginLeft="2dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0 km"
android:id="@+id/tvDistance" />
<ImageView
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:layout_width="40dp"
android:layout_height="40dp"
android:padding="5dp"
android:src="@drawable/ic_clock"/>
<TextView
android:layout_marginLeft="2dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0 min"
android:id="@+id/tvDuration" />
</LinearLayout>

<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />

</LinearLayout>

5.Database Crud

Biodata.Java
package com.rahmad.lab2menu;

public class Biodata extends Koneksi {


String URL = "http://192.168.43.79/uasrahmad/server.php";
String url = "";
String response = "";

public String tampilBiodata() {


try {
url = URL + "?operasi=view";
System.out.println("URL Tampil Biodata: " + url);
response = call(url);
} catch (Exception e) {
}
return response;
}

public String inserBiodata(String nama, String alamat) {


try {
url = URL + "?operasi=insert&nama=" + nama + "&alamat=" + alamat;
System.out.println("URL Insert Biodata : " + url);
response = call(url);
} catch (Exception e) {
}
return response;
}

public String getBiodataById(int id) {


try {
url = URL + "?operasi=get_biodata_by_id&id=" + id;
System.out.println("URL Insert Biodata : " + url);
response = call(url);
} catch (Exception e) {
}
return response;
}

public String updateBiodata(String id, String nama, String alamat) {


try {
url = URL + "?operasi=update&id=" + id + "&nama=" + nama + "&alamat=" +
alamat;
System.out.println("URL Insert Biodata : " + url);
response = call(url);
} catch (Exception e) {
}
return response;
}

public String deleteBiodata(int id) {


try {
url = URL + "?operasi=delete&id=" + id;
System.out.println("URL Insert Biodata : " + url);
response = call(url);
} catch (Exception e) {
}
return response;
}

Data.java
package com.rahmad.lab2menu;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.view.ViewPager.LayoutParams;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.rahmad.lab2menu.R;

public class Data extends Activity implements OnClickListener {

Biodata biodata = new Biodata();


TableLayout tabelBiodata;

Button buttonTambahBiodata;
ArrayList<Button> buttonEdit = new ArrayList<Button>();
ArrayList<Button> buttonDelete = new ArrayList<Button>();

JSONArray arrayBiodata;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

if (android.os.Build.VERSION.SDK_INT > 9){


StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}

tabelBiodata = (TableLayout) findViewById(R.id.tableBiodata);


buttonTambahBiodata = (Button) findViewById(R.id.buttonTambahBiodata);
buttonTambahBiodata.setOnClickListener(this);

TableRow barisTabel = new TableRow(this);


barisTabel.setBackgroundColor(Color.CYAN);

TextView viewHeaderId = new TextView(this);


TextView viewHeaderNama = new TextView(this);
TextView viewHeaderAlamat = new TextView(this);
TextView viewHeaderAction = new TextView(this);

viewHeaderId.setText("ID");
viewHeaderNama.setText("Nama");
viewHeaderAlamat.setText("Alamat");
viewHeaderAction.setText("Action");

viewHeaderId.setPadding(5, 1, 5, 1);
viewHeaderNama.setPadding(5, 1, 5, 1);
viewHeaderAlamat.setPadding(5, 1, 5, 1);
viewHeaderAction.setPadding(5, 1, 5, 1);
barisTabel.addView(viewHeaderId);
barisTabel.addView(viewHeaderNama);
barisTabel.addView(viewHeaderAlamat);
barisTabel.addView(viewHeaderAction);

tabelBiodata.addView(barisTabel, new
TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));

try {

arrayBiodata = new JSONArray(biodata.tampilBiodata());

for (int i = 0; i < arrayBiodata.length(); i++) {


JSONObject jsonChildNode = arrayBiodata.getJSONObject(i);
String name = jsonChildNode.optString("nama");
String alamat = jsonChildNode.optString("alamat");
String id = jsonChildNode.optString("id");

System.out.println("Nama :" + name);


System.out.println("Alamat :" + alamat);
System.out.println("ID :" + id);

barisTabel = new TableRow(this);

if (i % 2 == 0) {
barisTabel.setBackgroundColor(Color.LTGRAY);
}

TextView viewId = new TextView(this);


viewId.setText(id);
viewId.setPadding(5, 1, 5, 1);
barisTabel.addView(viewId);

TextView viewNama = new TextView(this);


viewNama.setText(name);
viewNama.setPadding(5, 1, 5, 1);
barisTabel.addView(viewNama);

TextView viewAlamat = new TextView(this);


viewAlamat.setText(alamat);
viewAlamat.setPadding(5, 1, 5, 1);
barisTabel.addView(viewAlamat);

buttonEdit.add(i, new Button(this));


buttonEdit.get(i).setId(Integer.parseInt(id));
buttonEdit.get(i).setTag("Edit");
buttonEdit.get(i).setText("Edit");
buttonEdit.get(i).setOnClickListener(this);
barisTabel.addView(buttonEdit.get(i));

buttonDelete.add(i, new Button(this));


buttonDelete.get(i).setId(Integer.parseInt(id));
buttonDelete.get(i).setTag("Delete");
buttonDelete.get(i).setText("Delete");
buttonDelete.get(i).setOnClickListener(this);
barisTabel.addView(buttonDelete.get(i));

tabelBiodata.addView(barisTabel, new
TableLayout.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
}
} catch (JSONException e) {
e.printStackTrace();
}
}

public void onClick(View view) {

if (view.getId() == R.id.buttonTambahBiodata) {
// Toast.makeText(MainActivity.this, "Button Tambah Data",
// Toast.LENGTH_SHORT).show();

tambahBiodata();

} else {
/*
* Melakukan pengecekan pada data array, agar sesuai dengan index
* masing-masing button
*/
for (int i = 0; i < buttonEdit.size(); i++) {

/* jika yang diklik adalah button edit */


if (view.getId() == buttonEdit.get(i).getId() &&
view.getTag().toString().trim().equals("Edit")) {
// Toast.makeText(MainActivity.this, "Edit : " +
// buttonEdit.get(i).getId(), Toast.LENGTH_SHORT).show();
int id = buttonEdit.get(i).getId();
getDataByID(id);

} /* jika yang diklik adalah button delete */


else if (view.getId() == buttonDelete.get(i).getId() &&
view.getTag().toString().trim().equals("Delete")) {
// Toast.makeText(MainActivity.this, "Delete : " +
// buttonDelete.get(i).getId(), Toast.LENGTH_SHORT).show();
int id = buttonDelete.get(i).getId();
deleteBiodata(id);

}
}
}
}

public void deleteBiodata(int id) {


biodata.deleteBiodata(id);

/* restart acrtivity */
finish();
startActivity(getIntent());

public void getDataByID(int id) {

String namaEdit = null, alamatEdit = null;


JSONArray arrayPersonal;

try {

arrayPersonal = new JSONArray(biodata.getBiodataById(id));

for (int i = 0; i < arrayPersonal.length(); i++) {


JSONObject jsonChildNode = arrayPersonal.getJSONObject(i);
namaEdit = jsonChildNode.optString("nama");
alamatEdit = jsonChildNode.optString("alamat");
}
} catch (JSONException e) {
e.printStackTrace();
}

LinearLayout layoutInput = new LinearLayout(this);


layoutInput.setOrientation(LinearLayout.VERTICAL);

// buat id tersembunyi di alertbuilder


final TextView viewId = new TextView(this);
viewId.setText(String.valueOf(id));
viewId.setTextColor(Color.TRANSPARENT);
layoutInput.addView(viewId);

final EditText editNama = new EditText(this);


editNama.setText(namaEdit);
layoutInput.addView(editNama);

final EditText editAlamat = new EditText(this);


editAlamat.setText(alamatEdit);
layoutInput.addView(editAlamat);

AlertDialog.Builder builderEditBiodata = new AlertDialog.Builder(this);


builderEditBiodata.setIcon(R.drawable.rea1);
builderEditBiodata.setTitle("Update Biodata");
builderEditBiodata.setView(layoutInput);
builderEditBiodata.setPositiveButton("Update", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String nama = editNama.getText().toString();
String alamat = editAlamat.getText().toString();

System.out.println("Nama : " + nama + " Alamat : " + alamat);

String laporan = biodata.updateBiodata(viewId.getText().toString(),


editNama.getText().toString(),
editAlamat.getText().toString());

Toast.makeText(Data.this, laporan, Toast.LENGTH_SHORT).show();

/* restart acrtivity */
finish();
startActivity(getIntent());
}

});

builderEditBiodata.setNegativeButton("Cancel", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builderEditBiodata.show();

public void tambahBiodata() {


/* layout akan ditampilkan pada AlertDialog */
LinearLayout layoutInput = new LinearLayout(this);
layoutInput.setOrientation(LinearLayout.VERTICAL);
final EditText editNama = new EditText(this);
editNama.setHint("Nama");
layoutInput.addView(editNama);

final EditText editAlamat = new EditText(this);


editAlamat.setHint("Alamat");
layoutInput.addView(editAlamat);

AlertDialog.Builder builderInsertBiodata = new AlertDialog.Builder(this);


builderInsertBiodata.setIcon(R.drawable.rea1);
builderInsertBiodata.setTitle("Insert Biodata");
builderInsertBiodata.setView(layoutInput);
builderInsertBiodata.setPositiveButton("Insert", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String nama = editNama.getText().toString();
String alamat = editAlamat.getText().toString();

System.out.println("Nama : " + nama + " Alamat : " + alamat);

String laporan = biodata.inserBiodata(nama, alamat);

Toast.makeText(Data.this, laporan, Toast.LENGTH_SHORT).show();

/* restart acrtivity */
finish();
startActivity(getIntent());
}

});

builderInsertBiodata.setNegativeButton("Cancel", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builderInsertBiodata.show();
}
}

data_user_listview.xml
<?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"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:layout_width="100dp"
android:layout_height="120dp"
app:srcCompat="@mipmap/ic_launcher"
android:id="@+id/imgUser" />
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:id="@+id/txtIdRec"
android:layout_toRightOf="@id/imgUser"/>
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:id="@+id/txtUserId"
android:layout_toRightOf="@id/imgUser"
android:layout_below="@id/txtIdRec"/>
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:id="@+id/txtUserName"
android:layout_toRightOf="@id/imgUser"
android:layout_below="@id/txtUserId"/>
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:id="@+id/txtDepartment"
android:layout_toRightOf="@id/imgUser"
android:layout_below="@id/txtUserName"/>
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:id="@+id/txtRoleAdmin"
android:layout_toRightOf="@id/imgUser"
android:layout_below="@id/txtDepartment"/>
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:id="@+id/txtRoleUser"
android:layout_toRightOf="@id/imgUser"
android:layout_below="@id/txtRoleAdmin"/>
</RelativeLayout>

6.Database Pendidikan
Login.java
package com.rahmad.lab2menu;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.rahmad.lab2menu.app.AppController;
import com.rahmad.lab2menu.R;

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

import java.util.HashMap;
import java.util.Map;

/**
* Created by Kuncoro on 03/24/2017.
*/
public class Login extends AppCompatActivity {

ProgressDialog pDialog;
Button btn_register, btn_login;
EditText txt_username, txt_password;
Intent intent;

int success;
ConnectivityManager conMgr;

private String url = Server.URL + "login.php";

private static final String TAG = Login.class.getSimpleName();

private static final String TAG_SUCCESS = "success";


private static final String TAG_MESSAGE = "message";

public final static String TAG_USERNAME = "username";


public final static String TAG_ID = "id";

String tag_json_obj = "json_obj_req";

SharedPreferences sharedpreferences;
Boolean session = false;
String id, username;
public static final String my_shared_preferences = "my_shared_preferences";
public static final String session_status = "session_status";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);

conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);


{
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
} else {
Toast.makeText(getApplicationContext(), "No Internet Connection",
Toast.LENGTH_LONG).show();
}
}

btn_login = (Button) findViewById(R.id.btn_login);


btn_register = (Button) findViewById(R.id.btn_register);
txt_username = (EditText) findViewById(R.id.txt_username);
txt_password = (EditText) findViewById(R.id.txt_password);

// Cek session login jika TRUE maka langsung buka MainActivity


sharedpreferences = getSharedPreferences(my_shared_preferences,
Context.MODE_PRIVATE);
session = sharedpreferences.getBoolean(session_status, false);
id = sharedpreferences.getString(TAG_ID, null);
username = sharedpreferences.getString(TAG_USERNAME, null);

if (session) {
Intent intent = new Intent(Login.this, Main.class);
intent.putExtra(TAG_ID, id);
intent.putExtra(TAG_USERNAME, username);
finish();
startActivity(intent);
}

btn_login.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String username = txt_username.getText().toString();
String password = txt_password.getText().toString();

// mengecek kolom yang kosong


if (username.trim().length() > 0 && password.trim().length() > 0) {
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
checkLogin(username, password);
} else {
Toast.makeText(getApplicationContext() ,"No Internet
Connection", Toast.LENGTH_LONG).show();
}
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext() ,"Kolom tidak boleh
kosong", Toast.LENGTH_LONG).show();
}
}
});

btn_register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
intent = new Intent(Login.this, Register.class);
finish();
startActivity(intent);
}
});

private void checkLogin(final String username, final String password) {


pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
pDialog.setMessage("Logging in ...");
showDialog();

StringRequest strReq = new StringRequest(Request.Method.POST, url, new


Response.Listener<String>() {

@Override
public void onResponse(String response) {
Log.e(TAG, "Login Response: " + response.toString());
hideDialog();

try {
JSONObject jObj = new JSONObject(response);
success = jObj.getInt(TAG_SUCCESS);

// Check for error node in json


if (success == 1) {
String username = jObj.getString(TAG_USERNAME);
String id = jObj.getString(TAG_ID);

Log.e("Successfully Login!", jObj.toString());

Toast.makeText(getApplicationContext(),
jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();

// menyimpan login ke session


SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(session_status, true);
editor.putString(TAG_ID, id);
editor.putString(TAG_USERNAME, username);
editor.commit();

// Memanggil main activity


Intent intent = new Intent(Login.this, Main.class);
intent.putExtra(TAG_ID, id);
intent.putExtra(TAG_USERNAME, username);
finish();
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(),
jObj.getString(TAG_MESSAGE),
Toast.LENGTH_LONG).show();

}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();

hideDialog();

}
}) {

@Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("username", username);
params.put("password", password);

return params;
}

};

// Adding request to request queue


AppController.getInstance().addToRequestQueue(strReq, tag_json_obj);
}

private void showDialog() {


if (!pDialog.isShowing())
pDialog.show();
}

private void hideDialog() {


if (pDialog.isShowing())
pDialog.dismiss();
}
}

main_login.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context="com.rahmad.lab2menu.Main">

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

<ImageView
android:id="@+id/logo"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:background="@mipmap/ic_launcher" />
<TextView
android:id="@+id/TextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
android:text="www.rahmadzulhilmi.com"
android:textSize="18dip"
android:textStyle="bold" />

<View
android:id="@+id/View1"
android:layout_width="fill_parent"
android:layout_height="1dp"
android:layout_gravity="center"
android:background="#448AFF" />

<TextView
android:id="@+id/txt_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp"
android:text="ID"/>

<TextView
android:id="@+id/txt_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp"
android:text="Username"/>

<Button
android:id="@+id/btn_logout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="50dp"
android:background="#00555555"
android:text="Logout"
android:textStyle="bold" />

</LinearLayout>

</RelativeLayout>
7.Menu Register

Register.Java
package com.rahmad.lab2menu;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.rahmad.lab2menu.app.AppController;
import com.rahmad.lab2menu.R;

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

import java.util.HashMap;
import java.util.Map;

public class Register extends AppCompatActivity {

ProgressDialog pDialog;
Button btn_register, btn_login;
EditText txt_username, txt_password, txt_confirm_password;
Intent intent;

int success;
ConnectivityManager conMgr;

private String url = Server.URL + "register.php";

private static final String TAG = Register.class.getSimpleName();

private static final String TAG_SUCCESS = "success";


private static final String TAG_MESSAGE = "message";

String tag_json_obj = "json_obj_req";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);

conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);


{
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
} else {
Toast.makeText(getApplicationContext(), "No Internet Connection",
Toast.LENGTH_LONG).show();
}
}

btn_login = (Button) findViewById(R.id.btn_login);


btn_register = (Button) findViewById(R.id.btn_register);
txt_username = (EditText) findViewById(R.id.txt_username);
txt_password = (EditText) findViewById(R.id.txt_password);
txt_confirm_password = (EditText) findViewById(R.id.txt_confirm_password);

btn_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
intent = new Intent(Register.this, Login.class);
finish();
startActivity(intent);
}
});

btn_register.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String username = txt_username.getText().toString();
String password = txt_password.getText().toString();
String confirm_password = txt_confirm_password.getText().toString();

if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
checkRegister(username, password, confirm_password);
} else {
Toast.makeText(getApplicationContext(), "No Internet Connection",
Toast.LENGTH_SHORT).show();
}
}
});

private void checkRegister(final String username, final String password, final


String confirm_password) {
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
pDialog.setMessage("Register ...");
showDialog();

StringRequest strReq = new StringRequest(Request.Method.POST, url, new


Response.Listener<String>() {

@Override
public void onResponse(String response) {
Log.e(TAG, "Register Response: " + response.toString());
hideDialog();

try {
JSONObject jObj = new JSONObject(response);
success = jObj.getInt(TAG_SUCCESS);

// Check for error node in json


if (success == 1) {

Log.e("Successfully Register!", jObj.toString());

Toast.makeText(getApplicationContext(),
jObj.getString(TAG_MESSAGE),
Toast.LENGTH_LONG).show();

txt_username.setText("");
txt_password.setText("");
txt_confirm_password.setText("");
} else {
Toast.makeText(getApplicationContext(),
jObj.getString(TAG_MESSAGE),
Toast.LENGTH_LONG).show();

}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}

}
}, new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();

hideDialog();

}
}) {

@Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("username", username);
params.put("password", password);
params.put("confirm_password", confirm_password);

return params;
}

};

// Adding request to request queue


AppController.getInstance().addToRequestQueue(strReq, tag_json_obj);
}

private void showDialog() {


if (!pDialog.isShowing())
pDialog.show();
}

private void hideDialog() {


if (pDialog.isShowing())
pDialog.dismiss();
}

@Override
public void onBackPressed() {
intent = new Intent(Register.this, Login.class);
finish();
startActivity(intent);
}

}
regiuster.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"
android:padding="16dp">

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

<ImageView
android:id="@+id/logo"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:background="@mipmap/ic_launcher" />

<TextView
android:id="@+id/TextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
android:text="www.rahmadzulhilmi.com"
android:textSize="18dip"
android:textStyle="bold" />

<View
android:id="@+id/View1"
android:layout_width="fill_parent"
android:layout_height="1dp"
android:layout_gravity="center"
android:background="#448AFF" />

<TextView
android:id="@+id/TextView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="30dip"
android:text="REGISTER BELOW"
android:textSize="16dip" />

<EditText
android:id="@+id/txt_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp"
android:hint="Username"
android:inputType="textEmailAddress"
android:singleLine="true" />

<EditText
android:id="@+id/txt_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp"
android:hint="Password"
android:password="true"
android:singleLine="true" />

<EditText
android:id="@+id/txt_confirm_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp"
android:hint="Comfirmation Password"
android:password="true" />

<Button
android:id="@+id/btn_register"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="15dp"
android:background="#448AFF"
android:textColor="#fff"
android:text="Register"
android:textStyle="bold" />

<Button
android:id="@+id/btn_login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="15dp"
android:background="#00555555"
android:text="Login"
android:textStyle="bold" />

</LinearLayout>

</RelativeLayout>
8.Splash Screen

FullScreenActivity.java
package com.rahmad.lab2menu;

import android.annotation.SuppressLint;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;

import com.rahmad.lab2menu.R;

/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*/
public class FullscreenActivity extends AppCompatActivity {
/**
* Whether or not the system UI should be auto-hidden after
* {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
*/
private static final boolean AUTO_HIDE = true;

/**
* If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
* user interaction before hiding the system UI.
*/
private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

/**
* Some older devices needs a small delay between UI widget updates
* and a change of the status and navigation bar.
*/
private static final int UI_ANIMATION_DELAY = 300;
private final Handler mHideHandler = new Handler();
private View mContentView;
private final Runnable mHidePart2Runnable = new Runnable() {
@SuppressLint("InlinedApi")
@Override
public void run() {

// Delayed removal of status and navigation bar

// Note that some of these constants are new as of API 16 (Jelly Bean)
// and API 19 (KitKat). It is safe to use them, as they are inlined
// at compile-time and do nothing on earlier devices.
mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
};
private View mControlsView;
private final Runnable mShowPart2Runnable = new Runnable() {
@Override
public void run() {
// Delayed display of UI elements
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.show();
}
mControlsView.setVisibility(View.VISIBLE);
}
};
private boolean mVisible;
private final Runnable mHideRunnable = new Runnable() {
@Override
public void run() {
hide();
}
};
/**
* Touch listener to use for in-layout UI controls to delay hiding the
* system UI. This is to prevent the jarring behavior of controls going away
* while interacting with activity UI.
*/
private final View.OnTouchListener mDelayHideTouchListener = new
View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (AUTO_HIDE) {
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
return false;
}
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_fullscreen);

mVisible = true;
mControlsView = findViewById(R.id.fullscreen_content_controls);
mContentView = findViewById(R.id.fullscreen_content);

// Set up the user interaction to manually show or hide the system UI.
mContentView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
toggle();
}
});

// Upon interacting with UI controls, delay any scheduled hide()


// operations to prevent the jarring behavior of controls going away
// while interacting with the UI.
findViewById(R.id.dummy_button).setOnTouchListener(mDelayHideTouchListener);
}

@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);

// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
delayedHide(100);
}

private void toggle() {


if (mVisible) {
hide();
} else {
show();
}
}
private void hide() {
// Hide UI first
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.hide();
}
mControlsView.setVisibility(View.GONE);
mVisible = false;

// Schedule a runnable to remove the status and navigation bar after a delay
mHideHandler.removeCallbacks(mShowPart2Runnable);
mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY);
}

@SuppressLint("InlinedApi")
private void show() {
// Show the system bar
mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
mVisible = true;

// Schedule a runnable to display UI elements after a delay


mHideHandler.removeCallbacks(mHidePart2Runnable);
mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY);
}

/**
* Schedules a call to hide() in delay milliseconds, canceling any
* previously scheduled calls.
*/
private void delayedHide(int delayMillis) {
mHideHandler.removeCallbacks(mHideRunnable);
mHideHandler.postDelayed(mHideRunnable, delayMillis);
}
}

SplashScreen.java
package com.rahmad.lab2menu;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Window;

import com.rahmad.lab2menu.R;

public class SplashScreen extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_splash_screen);
/*menjalankan splash screen dan menu menggunakan delayed thread*/
new Handler().postDelayed(new Thread() {
@Override
public void run() {
Intent mainMenu= new Intent(SplashScreen.this,MainActivity.class);
startActivity(mainMenu);
finish();
overridePendingTransition(R.layout.fadein,R.layout.fadeout);
}
}, 3000);

activity_fullscreen.xml
<FrameLayout
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:background="@drawable/rea1"

tools:context="com.rahmad.lab2menu.FullscreenActivity">

<!-- The primary full-screen view. This can be replaced with whatever view is
needed to present your content, e.g. VideoView, SurfaceView, TextureView, etc. -->

<TextView
android:id="@+id/fullscreen_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/imageView2"
android:gravity="center"
android:keepScreenOn="true"
android:text="@string/dummy_content"
android:textColor="#33b5e5"
android:textSize="50sp"
android:textStyle="bold" />

<!-- This FrameLayout insets its children based on system windows using
android:fitsSystemWindows. -->

<FrameLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">

<LinearLayout android:id="@+id/fullscreen_content_controls" style="?


metaButtonBarStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center_horizontal"
android:background="@color/black_overlay"
android:orientation="horizontal"
tools:ignore="UselessParent">

<Button android:id="@+id/dummy_button" style="?metaButtonBarButtonStyle"


android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/dummy_button" />

</LinearLayout>
</FrameLayout>

</FrameLayout>

activity_splash_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/rea1">
</LinearLayout>

9.Database uasrahmad

You might also like