Android Login User dan Upload Data Profile, Form, Spinner dan Multiple Image ke Server MySql

Android Login User dan Upload Data Profile, Form, Spinner dan Multiple Image ke Server MySql

Ada beberapa pertanyaan mengenai judul postingan kali ini, dikarenakan kita akan membahas beberapa fungsi riskan dan dijadikan satu dalam 1 kali upload data dari Android ke MySql database.

Dibeberapa forum membahas tentang tata cara bagaimana upload form data ke MySql, Upload Spinner data ke MySql, dan upload multiple image ke MySql. Semuanya hanya dibahas pada tahap-tahap yang berbeda namun sangat jarang sekali membahas tentang tata cara mengupload ketiga fitur tersebut dalam 1 tampilan dan satu database ke Server MySql.

Oke, dalam tahap ini pertama kali yang harus dilakukan adalah membuat tampilan Android. Aplikasi yang digunakan adalah Android Studio. Kita mengambil sample pembuatan form untuk membuat Work Order atau penugasan kerja pada suatu perusahaan. silahkan ikuti script code berikut ini . Tutorial ini sebagai bahan analisa kesalahan atau pertimbangan bagi anda yang ingin membuat code 4 in 1 dalam satu form saja. kekurangan dan kelebihan dalam tutorial ini silahkan anda cermati dan ditanyakan pada kami apabila ada yang tidak anda pahami.

Membuat Login User

Pertama kita buat login user pada Android untuk mendapatkan detail profile yang akan diupload pada form.

Buat Activity Baru dengan nama LoginActivity, kemudian pilih layout dan pilih activity_login.xml, kemudian ketikkan code berikut:

Source Code activity_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"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="@drawable/back_login"
    android:paddingLeft="30dp"
    android:paddingRight="30dp"
    android:paddingTop="80dp"
    tools:context=".LoginActivity">

    <ImageView
        android:id="@+id/logo"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_alignParentTop="true"
        android:layout_marginTop="80dp"
        android:layout_marginBottom="30dp"
        android:src="@drawable/profile" />

    <android.support.design.widget.TextInputLayout
        android:id="@+id/layoutemail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/logo">
        <EditText
            android:inputType="textEmailAddress"
            android:hint="Email"
            android:layout_margin="5dp"
            android:background="#45ffffff"
            android:textColor="#fff"
            android:id="@+id/email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="10dp" />
    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/layoutpassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/layoutemail"
        app:passwordToggleEnabled="true">
        <EditText
            android:inputType="textPassword"
            android:hint="Password"
            android:textColor="#fff"
            android:id="@+id/password"
            android:background="#45ffffff"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:layout_margin="5dp"/>
    </android.support.design.widget.TextInputLayout>

    <ProgressBar
        android:id="@+id/loading"
        android:layout_marginTop="35dp"
        android:layout_below="@id/link_regist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:visibility="gone"/>

    <Button
        android:id="@+id/btn_login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/layoutpassword"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="47dp"
        android:layout_marginBottom="5dp"
        android:background="@drawable/btn_rounded"
        android:text="LOGIN"
        android:textColor="#fff" />

    <TextView
        android:id="@+id/link_regist"
        android:layout_marginBottom="20dp"
        android:gravity="center"
        android:layout_marginTop="30dp"
        android:layout_below="@+id/btn_login"
        android:textColor="#fff"
        android:text="not having account ? Register"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>

Kemudian pada java folder pilih LoginActivity.java kemudan ketikkan source code berikut :

Source Code LoginActivity.java

package com.grandliviohotel.knowledge.shareworkknowledge;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
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 org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

public class LoginActivity extends AppCompatActivity {

    private EditText email, password;
    private Button btn_login;
    private TextView link_regist;
    private ProgressBar loading;
    private static String URL_LOGIN = "http://knowledge.grandliviohotel.com/profile/login.php";
    SessionManager sessionManager;

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

        sessionManager = new SessionManager(this);

        loading = findViewById(R.id.loading);
        email = findViewById(R.id.email);
        password = findViewById(R.id.password);
        btn_login = findViewById(R.id.btn_login);
        link_regist = findViewById(R.id.link_regist);

        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String mEmail = email.getText().toString().trim();
                String mPass = password.getText().toString().trim();

                if (!mEmail.isEmpty() || !mPass.isEmpty()) {
                    Login(mEmail, mPass);
                } else {
                    email.setError("Please insert email");
                    password.setError("Please insert password");
                }
            }
        });

        link_regist.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
            }
        });

    }

    private void Login(final String email, final String password) {

        loading.setVisibility(View.VISIBLE);
        btn_login.setVisibility(View.GONE);

        StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_LOGIN,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            String success = jsonObject.getString("success");
                            JSONArray jsonArray = jsonObject.getJSONArray("login");

                            if (success.equals("1")) {

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

                                    JSONObject object = jsonArray.getJSONObject(i);

                                    String name = object.getString("name").trim();
                                    String email = object.getString("email").trim();
                                    String alamat = object.getString("alamat").trim();
                                    String phone = object.getString("phone").trim();
                                    String departement = object.getString("departement").trim();
                                    String jabatan = object.getString("jabatan").trim();
                                    String photo = object.getString("photo").trim();
                                    String id = object.getString("id").trim();

                                    sessionManager.createSession(name, email, alamat, phone, departement, jabatan, id);

                                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                    intent.putExtra("name", name);
                                    intent.putExtra("email", email);

                                    startActivity(intent);
                                    finish();

                                    loading.setVisibility(View.GONE);


                                }

                            } else {
                                loading.setVisibility(View.GONE);
                                btn_login.setVisibility(View.VISIBLE);
                                Toast.makeText(LoginActivity.this, "Please Check Email & Password", Toast.LENGTH_LONG).show();

                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        loading.setVisibility(View.GONE);
                        btn_login.setVisibility(View.VISIBLE);
                        Toast.makeText(LoginActivity.this, "Error " +error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                })
        {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("email", email);
                params.put("password", password);
                return params;
            }
        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);

    }
}

Pada source code diatas dapat dilihat ada pilihan link register pada bagian xml code, Tetapi dikarenakan tidak perlunya register untuk dibahas, maka kami tidak akan membahas tentang register code nya disini.

Oke, tahap selanjutnya kita membuat xml form nya. yang akan berisikan detail profile, form, spinner, multiple image. silahkan membuat Activity baru kemudian pilih layout dan ketikkan code dibawah ini.

Source Code Form XML

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

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:background="?attr/colorPrimary"
        app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto" />

    <ScrollView
        android:id="@+id/scl_wo_detail"
        android:layout_below="@id/toolbar"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:fadeScrollbars="true"
        android:scrollbars="none">


        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/toolbar"
            android:foreground="?android:attr/selectableItemBackground">


            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="100dp"
                android:background="#F3141414">

                <EditText
                    android:id="@+id/txt_id"
                    android:visibility="gone"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="@android:drawable/editbox_background_normal"/>
                <EditText
                    android:id="@+id/edtName"
                    android:padding="5dp"
                    android:layout_width="280dp"
                    android:layout_height="40dp"
                    android:layout_alignParentTop="true"
                    android:layout_alignParentBottom="true"
                    android:layout_marginStart="8dp"
                    android:layout_marginLeft="8dp"
                    android:layout_marginTop="47dp"
                    android:layout_marginBottom="17dp"
                    android:background="#f2acabab"
                    android:ems="10"
                    android:editable="false"
                    android:inputType="none"/>

                <TextView
                    android:id="@+id/textView3"
                    android:layout_width="140dp"
                    android:layout_height="30dp"
                    android:layout_alignParentStart="true"
                    android:layout_alignParentLeft="true"
                    android:layout_alignParentTop="true"
                    android:layout_marginStart="15dp"
                    android:layout_marginLeft="15dp"
                    android:layout_marginTop="14dp"
                    android:layout_marginBottom="41dp"
                    android:text="Your Name"
                    android:textColor="#fff" />

                <TextView
                    android:id="@+id/textView4"
                    android:layout_width="120dp"
                    android:layout_height="30dp"
                    android:layout_alignParentTop="true"
                    android:layout_alignParentEnd="true"
                    android:layout_alignParentRight="true"
                    android:layout_marginStart="140dp"
                    android:layout_marginLeft="22dp"
                    android:layout_marginTop="14dp"
                    android:layout_marginEnd="10dp"
                    android:layout_marginRight="83dp"
                    android:layout_marginBottom="42dp"
                    android:layout_toEndOf="@+id/textView3"
                    android:layout_toRightOf="@+id/textView3"
                    android:text="Date"
                    android:textColor="#fff" />

                <EditText
                    android:id="@+id/btnDate"
                    android:layout_width="100dp"
                    android:layout_height="40dp"
                    android:layout_alignParentTop="true"
                    android:layout_alignParentEnd="true"
                    android:layout_alignParentRight="true"
                    android:layout_marginTop="45dp"
                    android:layout_marginEnd="10dp"
                    android:layout_marginRight="111dp"
                    android:layout_marginBottom="10dp"
                    android:background="@drawable/btn_rounded"
                    android:drawableRight="@drawable/ic_date"
                    android:hint="Set Date"
                    android:textSize="15dp"
                    android:editable="false"
                    android:textAlignment="center"
                    android:textColorHint="#ffffff"
                    android:drawableEnd="@drawable/ic_date" />




            </RelativeLayout>

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

                <TextView
                    android:id="@+id/textView6"
                    android:layout_width="wrap_content"
                    android:layout_height="32dp"
                    android:layout_alignParentStart="true"
                    android:layout_alignParentLeft="true"
                    android:layout_alignParentTop="true"
                    android:layout_alignParentEnd="true"
                    android:layout_alignParentRight="true"
                    android:layout_marginStart="13dp"
                    android:layout_marginLeft="13dp"
                    android:layout_marginTop="107dp"
                    android:layout_marginEnd="265dp"
                    android:layout_marginRight="265dp"
                    android:text="Project Area" />


                <EditText
                    android:id="@+id/prj_area"
                    android:layout_width="387dp"
                    android:layout_height="40dp"
                    android:padding="5dp"
                    android:layout_alignParentStart="true"
                    android:layout_alignParentLeft="true"
                    android:layout_alignParentTop="true"
                    android:layout_alignParentEnd="true"
                    android:layout_alignParentRight="true"
                    android:layout_alignParentBottom="true"
                    android:layout_marginStart="10dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginTop="135dp"
                    android:layout_marginEnd="10dp"
                    android:layout_marginRight="14dp"
                    android:layout_marginBottom="0dp"
                    android:background="#41B9B6B6"
                    android:ems="10"
                    android:inputType="text" />


            </RelativeLayout>


            <TextView
                android:id="@+id/textView8"
                android:layout_width="163dp"
                android:layout_height="24dp"
                android:layout_alignParentStart="true"
                android:layout_alignParentLeft="true"
                android:layout_alignParentTop="true"
                android:layout_alignParentEnd="true"
                android:layout_alignParentRight="true"
                android:layout_marginStart="12dp"
                android:layout_marginLeft="12dp"
                android:layout_marginTop="188dp"
                android:layout_marginEnd="266dp"
                android:layout_marginRight="266dp"
                android:text="Departement From :" />

            <TextView
                android:id="@+id/textView"
                android:layout_width="wrap_content"
                android:layout_height="32dp"
                android:layout_alignParentStart="true"
                android:layout_alignParentLeft="true"
                android:layout_alignParentTop="true"
                android:layout_alignParentEnd="true"
                android:layout_alignParentRight="true"
                android:layout_marginStart="10dp"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="272dp"
                android:layout_marginEnd="267dp"
                android:layout_marginRight="267dp"
                android:text="Priority" />

            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="32dp"
                android:layout_alignParentStart="true"
                android:layout_alignParentLeft="true"
                android:layout_alignParentTop="true"
                android:layout_alignParentEnd="true"
                android:layout_alignParentRight="true"
                android:layout_marginStart="9dp"
                android:layout_marginLeft="9dp"
                android:layout_marginTop="351dp"
                android:layout_marginEnd="268dp"
                android:layout_marginRight="268dp"
                android:text="Description" />

            <TextView
                android:id="@+id/textView10"
                android:layout_width="wrap_content"
                android:layout_height="32dp"
                android:layout_alignParentStart="true"
                android:layout_alignParentLeft="true"
                android:layout_alignParentTop="true"
                android:layout_alignParentEnd="true"
                android:layout_alignParentRight="true"
                android:layout_marginStart="210dp"
                android:layout_marginLeft="210dp"
                android:layout_marginTop="273dp"
                android:layout_marginEnd="67dp"
                android:layout_marginRight="67dp"
                android:text="Work Category" />

            <TextView
                android:id="@+id/textView9"
                android:layout_width="wrap_content"
                android:layout_height="32dp"
                android:layout_alignParentStart="true"
                android:layout_alignParentLeft="true"
                android:layout_alignParentTop="true"
                android:layout_alignParentEnd="true"
                android:layout_alignParentRight="true"
                android:layout_marginStart="209dp"
                android:layout_marginLeft="209dp"
                android:layout_marginTop="188dp"
                android:layout_marginEnd="69dp"
                android:layout_marginRight="69dp"
                android:text="Departement to :" />


            <LinearLayout
                android:layout_width="190dp"
                android:layout_height="40dp"
                android:layout_alignParentStart="true"
                android:layout_alignParentLeft="true"
                android:layout_marginStart="10dp"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="220dp"
                android:background="#41B9B6B6">


                <TextView
                    android:id="@+id/dpt_from"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:inputType="none"
                    android:padding="10dp"
                    android:editable="false">

                </TextView>
            </LinearLayout>

            <LinearLayout
                android:layout_width="190dp"
                android:layout_height="40dp"
                android:layout_alignParentStart="true"
                android:layout_alignParentLeft="true"
                android:layout_marginStart="208dp"
                android:layout_marginLeft="206dp"
                android:layout_marginTop="220dp"
                android:background="#41B9B6B6">

                <Spinner
                    android:id="@+id/spinner2"
                    android:layout_width="200dp"
                    android:layout_height="wrap_content"
                    android:entries="@array/departement" />

                <EditText
                    android:id="@+id/dpt_to"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="10dp"
                    android:layout_weight="1"
                    android:editable="false"
                    android:ems="10"
                    android:inputType="text"
                    android:padding="7dp"
                    android:textSize="14sp"
                    android:visibility="invisible">

                </EditText>
            </LinearLayout>


            <LinearLayout
                android:layout_width="190dp"
                android:layout_height="40dp"
                android:layout_alignParentStart="true"
                android:layout_alignParentLeft="true"
                android:layout_marginStart="10dp"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="300dp"
                android:background="#41B9B6B6">

                <Spinner
                    android:id="@+id/spinner3"
                    android:layout_width="200dp"
                    android:layout_height="wrap_content"
                    android:entries="@array/work_priority" />

                <EditText
                    android:id="@+id/Text_Priority"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="10dp"
                    android:layout_weight="1"
                    android:editable="false"
                    android:ems="10"
                    android:inputType="text"
                    android:padding="7dp"
                    android:textSize="14sp"
                    android:visibility="invisible">

                </EditText>
            </LinearLayout>

            <LinearLayout
                android:layout_width="190dp"
                android:layout_height="40dp"
                android:layout_alignParentStart="true"
                android:layout_alignParentLeft="true"
                android:layout_marginStart="208dp"
                android:layout_marginLeft="206dp"
                android:layout_marginTop="300dp"
                android:background="#41B9B6B6">

                <Spinner
                    android:id="@+id/spinner_category"
                    android:layout_width="200dp"
                    android:layout_height="wrap_content" />

                <EditText
                    android:id="@+id/txt_ctg"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="10dp"
                    android:layout_weight="1"
                    android:ems="10"
                    android:padding="7dp"
                    android:entries="@array/work_category">

                </EditText>
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="200dp"
                android:layout_marginTop="380dp"
                android:layout_marginEnd="10dp"
                android:layout_marginStart="10dp">

                <EditText
                    android:id="@+id/edt_Desc_Work"
                    android:layout_width="match_parent"
                    android:layout_height="200dp"
                    android:background="#41B9B6B6"
                    android:gravity="top"
                    android:padding="5dp"
                    android:inputType="textMultiLine" />

            </LinearLayout>


            <ImageView
                android:id="@+id/ivCamera"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_alignParentTop="true"
                android:layout_marginStart="20dp"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="600dp"
                android:layout_marginEnd="10dp"
                android:layout_marginRight="10dp"
                android:src="@android:drawable/ic_menu_camera" />

            <ImageView
                android:id="@+id/imgView"
                android:layout_width="80dp"
                android:layout_height="80dp"
                android:screenOrientation="landscape"
                android:layout_marginStart="100dp"
                android:layout_marginLeft="100dp"
                android:layout_marginTop="600dp"
                />

            <Button
                android:id="@+id/submit_wo"
                android:layout_width="133dp"
                android:layout_height="45dp"
                android:layout_alignParentTop="true"
                android:layout_alignParentEnd="true"
                android:layout_alignParentRight="true"
                android:layout_gravity="left"
                android:layout_marginTop="600dp"
                android:layout_marginEnd="14dp"
                android:layout_marginRight="14dp"
                android:layout_marginBottom="47dp"
                android:background="@drawable/btn_rounded"
                android:text="SUBMIT"
                android:textColor="#fff"
                android:textSize="20sp"
                tools:ignore="RtlHardcoded" />


        </RelativeLayout>

    </ScrollView>



</RelativeLayout>

Kemudian pada java filenya ketikkan kode berikut :

Source Code Form JAVA

package com.grandliviohotel.knowledge.shareworkknowledge;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
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.grandliviohotel.knowledge.shareworkknowledge.Utilities.AppController;

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

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class ActivityCreateWorkOrder extends AppCompatActivity {

    SessionManager sessionManager;
    String getId;
    private static String URL_READ = "http://knowledge.grandliviohotel.com/profile/read_detail.php";

    Button submit_wo;
    ImageView ivCamera,imgView ;
    EditText edtName,prj_area,dpt_to,Text_Priority,txt_ctg,edt_Desc_Work;
    ScrollView scl_wo_detail;
    TextView dpt_from;

    String Category_ID,staff_name,date,project_area,departement_from,departement_to,priority_work,image_path,description_work;

    Bitmap bitmap, decoded;
    int success;
    private int GALLERY = 1, CAMERA = 2;
    int bitmap_size = 100; // range 1 - 100

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

    private String UPLOAD_URL = "http://knowledge.grandliviohotel.com/add_work_order.php";

    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";

    private String KEY_CATEGORY= "Category_ID";
    private String KEY_IMAGE = "image_path";
    private String KEY_NAME = "staff_name";
    private String KEY_DATE = "date_n_time";
    private String KEY_PROJECT_AREA = "project_area";
    private String KEY_DPT_FROM = "departement_from";
    private String KEY_DPT_TO = "departement_to";
    private String KEY_PRIORITY_WORK = "priority_work";
    private String KEY_DESCRIPTION_WORK = "description_work";
    private static final String KEY_EMPTY = "";

    String tag_json_obj = "json_obj_req";

    static EditText btnDate;
    private static int mYear;
    private static int mMonth;
    private static int mDay;
    public static final String DATE_DIALOG_ID = "datePicker";

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

        sessionManager = new SessionManager(this);
        sessionManager.checkLogin();
        HashMap<String, String> user = sessionManager.getUserDetail();
        getId = user.get(sessionManager.ID);


        final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        final android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
            getSupportActionBar().setTitle(R.string.create_Wo);
        }

        ivCamera = (ImageView) findViewById(R.id.ivCamera);

        edtName = (EditText) findViewById(R.id.edtName);
        prj_area = (EditText) findViewById(R.id.prj_area);
        dpt_from = (TextView) findViewById(R.id.dpt_from);
        dpt_to = (EditText) findViewById(R.id.dpt_to);
        Text_Priority = (EditText) findViewById(R.id.Text_Priority);
        txt_ctg = (EditText) findViewById(R.id.txt_ctg);
        btnDate = (EditText) findViewById(R.id.btnDate);
        edt_Desc_Work = (EditText) findViewById(R.id.edt_Desc_Work);
        submit_wo = (Button) findViewById(R.id.submit_wo);
        scl_wo_detail = (ScrollView) findViewById(R.id.scl_wo_detail);
        imgView = (ImageView) findViewById(R.id.imgView);



        //--------------------------SPINNER START--------------------------//



        Spinner spinnerdpt2 = (Spinner) findViewById(R.id.spinner2);
        ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(this,
                R.array.departement_to,android.R.layout.simple_spinner_item);
        adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerdpt2.setAdapter(adapter1);
        spinnerdpt2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
                // TODO Auto-generated method stub
                switch(arg2) {
                    case 0 :
                        dpt_to.setText(R.string.select_departement_to);
                        break;
                    case 1 :
                        dpt_to.setText(R.string.accounting_to);
                        break;
                    case 2 :
                        dpt_to.setText(R.string.admin_general_to);
                        break;
                    case 3 :
                        dpt_to.setText(R.string.sales_marketing_to);
                        break;
                    case 4 :
                        dpt_to.setText(R.string.front_office_to);
                        break;
                    case 5 :
                        dpt_to.setText(R.string.fb_service_to);
                        break;
                    case 6 :
                        dpt_to.setText(R.string.fb_product_to);
                        break;
                    case 7 :
                        dpt_to.setText(R.string.engineering_to);
                        break;
                    case 8 :
                        dpt_to.setText(R.string.housekeeping_to);
                        break;
                    case 9 :
                        dpt_to.setText(R.string.human_resource_to);
                        break;
                    case 10 :
                        dpt_to.setText(R.string.security_to);
                        break;
                    default :
                        dpt_to.setText(R.string.all_departement_to);
                        break;
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
            }
        });

        Spinner spinnerWp4 = (Spinner) findViewById(R.id.spinner3);
        ArrayAdapter<CharSequence> adapter3 = ArrayAdapter.createFromResource(this,
                R.array.work_priority,android.R.layout.simple_spinner_item);
        adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerWp4.setAdapter(adapter3);
        spinnerWp4.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
                // TODO Auto-generated method stub
                switch(arg2) {
                    case 0 :
                        Text_Priority.setText(R.string.select_priority);
                        break;
                    case 1 :
                        Text_Priority.setText(R.string.urgent);
                        break;
                    case 2 :
                        Text_Priority.setText(R.string.low_priority);
                        break;
                    case 3 :
                        Text_Priority.setText(R.string.medium_priority);
                        break;
                    default :
                        Text_Priority.setText(R.string.high_priority);
                        break;
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
            }
        });

        Spinner spinnerCtg = (Spinner) findViewById(R.id.spinner_category);
        ArrayAdapter<CharSequence> adapter4 = ArrayAdapter.createFromResource(this,
                R.array.work_category,android.R.layout.simple_spinner_item);
        adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerCtg.setAdapter(adapter4);
        spinnerCtg.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
                // TODO Auto-generated method stub
                switch(arg2) {
                    case 0 :
                        txt_ctg.setText(R.string.select_category);
                        break;
                    case 1 :
                        txt_ctg.setText("1");
                        break;
                    case 2 :
                        txt_ctg.setText("2");
                        break;
                    case 3 :
                        txt_ctg.setText("3");
                        break;
                    case 4 :
                        txt_ctg.setText("4");
                        break;
                    default :
                        txt_ctg.setText("5");
                        break;
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
            }
        });

        //---------------------------SPINNER FINISH-------------------//


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

        // event listener to handle date button when pressed
        btnDate.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                // show date picker dialog
                DialogFragment newFragment = new DatePickerFragment();
                newFragment.show(getSupportFragmentManager(), DATE_DIALOG_ID);
            }
        });

        submit_wo.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                Category_ID = txt_ctg.getText().toString();
                staff_name = edtName.getText().toString();
                project_area = prj_area.getText().toString();
                departement_from = dpt_from.getText().toString();
                departement_to = dpt_to.getText().toString();
                priority_work = Text_Priority.getText().toString();
                date = btnDate.getText().toString();
                description_work = edt_Desc_Work.getText().toString();

                if(validateInputs()){
                    uploadWork();
                }
            }
        });
    }

    private boolean validateInputs() {

        if(KEY_EMPTY.equals(project_area)){
            prj_area.setError("Form cannot be empty");
            prj_area.requestFocus();
            return false;
        }
        if(KEY_EMPTY.equals(date)){
            btnDate.setError("Date cannot be empty");
            btnDate.requestFocusFromTouch();
            return false;
        }
        if(KEY_EMPTY.equals(description_work)){
            edt_Desc_Work.setError("Form cannot be empty");
            edt_Desc_Work.requestFocus();
            return false;
        }


        return true;

    }


    private void uploadWork() {
        //menampilkan progress dialog
        final ProgressDialog loading = ProgressDialog.show(this, "Uploading...", "Please wait...", false, false);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.e(TAG, "Response: " + response.toString());
                        try {
                            JSONObject jObj = new JSONObject(response);
                            success = jObj.getInt(TAG_SUCCESS);
                            if (success == 1) {
                                Log.e("v Add", jObj.toString());
                                Toast.makeText(ActivityCreateWorkOrder.this, jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
                                finish();
                                startActivity(getIntent());

                            } else {
                                Toast.makeText(ActivityCreateWorkOrder.this, jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        //menghilangkan progress dialog
                        loading.dismiss();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        //menghilangkan progress dialog
                        loading.dismiss();
                        //menampilkan toast
                        Toast.makeText(ActivityCreateWorkOrder.this,"Please Complete Form & Image".toString(), Toast.LENGTH_LONG).show();
                        Log.e(TAG, error.getMessage());
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                //membuat parameters
                Map<String, String> params = new HashMap<String, String>();
                //menambah parameter yang di kirim ke web servis
                params.put(KEY_CATEGORY, txt_ctg.getText().toString().trim());
                params.put(KEY_NAME, edtName.getText().toString().trim());
                params.put(KEY_DATE, btnDate.getText().toString().trim());
                params.put(KEY_PROJECT_AREA, prj_area.getText().toString().trim());
                params.put(KEY_DPT_FROM, dpt_from.getText().toString().trim());
                params.put(KEY_DPT_TO, dpt_to.getText().toString().trim());
                params.put(KEY_PRIORITY_WORK, Text_Priority.getText().toString().trim());
                params.put(KEY_DESCRIPTION_WORK, edt_Desc_Work.getText().toString().trim());
                params.put(KEY_IMAGE, getStringImage(decoded));

                //kembali ke parameters
                Log.e(TAG, "" + params);
                return params;
            }
        };

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

    private void getUserDetail(){

        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Loading...");
        progressDialog.show();

        StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_READ,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        progressDialog.dismiss();
                        Log.i(TAG, response.toString());

                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            String success = jsonObject.getString("success");
                            JSONArray jsonArray = jsonObject.getJSONArray("read");

                            if (success.equals("1")){

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

                                    JSONObject object = jsonArray.getJSONObject(i);

                                    String strName = object.getString("name").trim();
                                    String dptFrom = object.getString("departement").trim();
                                    edtName.setText(strName);
                                    dpt_from.setText(dptFrom);
                                }

                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                            progressDialog.dismiss();
                            Toast.makeText(ActivityCreateWorkOrder.this, "Error Reading Detail "+e.toString(), Toast.LENGTH_SHORT).show();
                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        progressDialog.dismiss();
                        Toast.makeText(ActivityCreateWorkOrder.this, "Error Reading Detail "+error.toString(), Toast.LENGTH_SHORT).show();
                    }
                })
        {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String > params = new HashMap<>();
                params.put("id", getId);
                return params;
            }
        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);

    }

    @Override
    protected void onResume() {
        super.onResume();
        getUserDetail();
    }

    private void showPictureDialog(){
        AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
        pictureDialog.setTitle("Select Image");
        String[] pictureDialogItems = {
                "From gallery",
                "From camera" };
        pictureDialog.setItems(pictureDialogItems,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                choosePhotoFromGallery();
                                break;
                            case 1:
                                takePhotoFromCamera();
                                break;
                        }
                    }
                });
        pictureDialog.show();
    }

    public String getStringImage(Bitmap bmp) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, bitmap_size, baos);
        byte[] imageBytes = baos.toByteArray();
        String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
        return encodedImage;
    }

    public void choosePhotoFromGallery() {
        Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(galleryIntent, GALLERY);
    }

    private void takePhotoFromCamera() {

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, CAMERA);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == GALLERY && resultCode == RESULT_OK && data != null && data.getData() != null) {
            Uri filePath = data.getData();
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);  //mengambil fambar dari Gallery
                setToImageView(getResizedBitmap(bitmap, 1024)); // 512 adalah resolusi tertinggi setelah image di resize, bisa di ganti.
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if(requestCode == CAMERA && resultCode == RESULT_OK){
            Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

            File destination = new File(Environment.getExternalStorageDirectory(),
                    System.currentTimeMillis() + ".jpg");

            FileOutputStream fo;
            try {
                destination.createNewFile();
                fo = new FileOutputStream(destination);
                fo.write(bytes.toByteArray());
                fo.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(bytes.toByteArray()));
            imgView.setImageBitmap(decoded);

            //Bitmap bitmap = (Bitmap)data.getExtras().get("data");
            //setToImageView(getResizedBitmap(bitmap,1080));
           // imgView.setImageURI(image_uri);
        }


    }

    private void setToImageView(Bitmap bmp) {
        //compress image
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(bytes.toByteArray()));
        imgView.setImageBitmap(decoded);
    }

    // fungsi resize image
    public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
        int width = image.getWidth();
        int height = image.getHeight();
        float bitmapRatio = (float) width / (float) height;
        if (bitmapRatio > 1) {
            width = maxSize;
            height = (int) (width / bitmapRatio);
        } else {
            height = maxSize;
            width = (int) (height * bitmapRatio);
        }
        return Bitmap.createScaledBitmap(image, width, height, false);
    }

    // method to create date picker dialog
    public static class DatePickerFragment extends DialogFragment
            implements DatePickerDialog.OnDateSetListener {
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // set default date
            final Calendar c = Calendar.getInstance();
            int year = c.get(Calendar.YEAR);
            int month = c.get(Calendar.MONTH);
            int day = c.get(Calendar.DAY_OF_MONTH);
            // Create a new instance of DatePickerDialog and return it
            return new DatePickerDialog(getActivity(), this, year, month, day);
        }
        public void onDateSet(DatePicker view, int year, int month, int day) {
            // get selected date
            mYear = year;
            mMonth = month;
            mDay = day;
            // show selected date to date button
            btnDate.setText(new StringBuilder()
                    .append(mYear).append("-")
                    .append(mMonth + 1).append("-")
                    .append(mDay).append(" "));
        }
    }

    // when back button pressed close database and back to previous page
    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        super.onBackPressed();
        finish();
    }

    @Override
    public void onConfigurationChanged(final Configuration newConfig)
    {
        // Ignore orientation change to keep activity from restarting
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        //mla.imageLoader.clearCache();
        super.onDestroy();
    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }
}

Untuk Data Spinner, silahkan menambahkan code berikut pada string.xml

Membuat string.xml

<resources>
    <string name="app_name">SHARE WORK KNOWLEDGE</string>
    <string name="navigation_drawer_open">Open navigation drawer</string>
    <string name="navigation_drawer_close">Close navigation drawer</string>
    <string name="nav_header_title">Android Studio</string>
    <string name="nav_header_subtitle">android.studio@android.com</string>
    <string name="nav_header_desc">Navigation header</string>
    <string name="action_settings">Settings</string>

    <string name="select_departement">-</string>
    <string name="accounting">Accounting</string>
    <string name="admin_general">Admin General</string>
    <string name="sales_marketing">Sales Marketing</string>
    <string name="front_office">Front Office</string>
    <string name="fb_service">FB Service</string>
    <string name="fb_product">FB Product</string>
    <string name="engineering">Engineering</string>
    <string name="housekeeping">Housekeeping</string>
    <string name="human_resource">Human Resource</string>
    <string name="security">Security</string>
    <string name="all_departement">All Departement</string>


    <string name="select_departement_to">-</string>
    <string name="accounting_to">Accounting</string>
    <string name="admin_general_to">Admin General</string>
    <string name="sales_marketing_to">Sales Marketing</string>
    <string name="front_office_to">Front Office</string>
    <string name="fb_service_to">FB Service</string>
    <string name="fb_product_to">FB Product</string>
    <string name="engineering_to">Engineering</string>
    <string name="housekeeping_to">Housekeeping</string>
    <string name="human_resource_to">Human Resource</string>
    <string name="security_to">Security</string>
    <string name="all_departement_to">All Departement</string>

    <string name="select_priority">-</string>
    <string name="urgent">Urgent</string>
    <string name="low_priority">low Priority</string>
    <string name="medium_priority">Medium Priority</string>
    <string name="high_priority">High Priority</string>

    <string name="select_jabatan">-</string>
    <string name="staff">Staff</string>
    <string name="Supervisor">Supervisor</string>
    <string name="Coordinator">Coordinator</string>
    <string name="Asst_Manager">Assistance Manager</string>
    <string name="Manager">Manager</string>
    <string name="general_manager">General Manager</string>
    <string name="director">Director</string>


    <string name="select_category">-</string>
    <string name="office_work">1 Office Work</string>
    <string name="general_cleaning">2 General Cleaning</string>
    <string name="maintenance">3 Maintenance</string>
    <string name="general_event">4 General Event</string>
    <string name="training">5 Training</string>

    <string name="select_status">-</string>
    <string name="finish">Finish</string>

    <string name="set_date">Set Date</string>
    <string name="set_time">Set Time</string>

    <string name="choose_date_or_time">Choose Date or Time:</string>
    <string name="button_choosedatetime">Choose Date/Time</string>
    <string name="red" />
    <string name="create_Wo">Create Work Order</string>
    <string name="list_Wo">List Work Order</string>

    <string name="menu_create_wo">Work Order</string>
    <string name="title_category">Category</string>
    <string name="title_list_menu">List Work Order</string>
    <string name="option_yes">Yes</string>
    <string name="option_no">No</string>

    <string name="form_alert">Please, complete the form first.</string>
    <string name="sending_alert">Sending data. Please wait …</string>
    <string name="ok_alert">Your Work Order has been successfully sent.</string>
    <string name="failed_alert">Your Work Order has not been sent.</string>
    <string name="work_list">List Work Order</string>
</resources>

Kemudian pada Array Spinner silahkan membuat array.xml pada folder values dan ketikkan code berikut :

Source Code Array.xml

<string-array name="departement">
    <item>@string/select_departement</item>
    <item>@string/accounting</item>
    <item>@string/admin_general</item>
    <item>@string/sales_marketing</item>
    <item>@string/front_office</item>
    <item>@string/fb_service</item>
    <item>@string/fb_product</item>
    <item>@string/engineering</item>
    <item>@string/housekeeping</item>
    <item>@string/human_resource</item>
    <item>@string/security</item>
    <item>@string/all_departement</item>
</string-array>

<string-array name="departement_to">
    <item>@string/select_departement</item>
    <item>@string/accounting</item>
    <item>@string/admin_general</item>
    <item>@string/sales_marketing</item>
    <item>@string/front_office</item>
    <item>@string/fb_service</item>
    <item>@string/fb_product</item>
    <item>@string/engineering</item>
    <item>@string/housekeeping</item>
    <item>@string/human_resource</item>
    <item>@string/security</item>
    <item>@string/all_departement</item>
</string-array>

<string-array name="work_priority">
    <item>@string/select_priority</item>
    <item>@string/urgent</item>
    <item>@string/low_priority</item>
    <item>@string/medium_priority</item>
    <item>@string/high_priority</item>
</string-array>

<string-array name="work_category">
    <item>@string/select_category</item>
    <item>@string/office_work</item>
    <item>@string/general_cleaning</item>
    <item>@string/maintenance</item>
    <item>@string/general_event</item>
    <item>@string/training</item>

</string-array>

<string-array name="jabatan">
    <item>@string/select_jabatan</item>
    <item>@string/staff</item>
    <item>@string/Supervisor</item>
    <item>@string/Coordinator</item>
    <item>@string/Asst_Manager</item>
    <item>@string/Manager</item>
    <item>@string/general_manager</item>
    <item>@string/director</item>
</string-array>

<string-array name="work_status">
    <item>@string/select_status</item>
    <item>@string/finish</item>

</string-array>

Oke, code-code diatas sudah termasuk spinner, datePicker, dan multiple image beserta data profile. Tutorial ini tidak memberikan source code secara langsung, tapi memberikan gambaran bagaimana semua fitur tersebut dapat disatukan dengan baik dan benar. Ini dapat menjadi bahan referensi apabila anda mendapatkan permasalahan apabila ingin membuat aplikasi seperti ini.

Sebagai pelengkap kita harus mengisi SessionManager.java untuk verifikasi login user dan data profile user. code nya sebagai berikut :

Source Code SessionManager.java

package com.grandliviohotel.knowledge.shareworkknowledge;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;

import java.util.HashMap;

public class SessionManager {

    SharedPreferences sharedPreferences;
    public SharedPreferences.Editor editor;
    public Context context;
    int PRIVATE_MODE = 0;

    private static final String PREF_NAME = "LOGIN";
    private static final String LOGIN = "IS_LOGIN";
    public static final String NAME = "NAME";
    public static final String EMAIL = "EMAIL";
    public static final String PASSWORD = "PASSWORD";
    public static final String ALAMAT = "ALAMAT";
    public static final String NO_TELP = "NO_TELP";
    public static final String DEPARTEMENT = "DEPARTEMENT";
    public static final String JABATAN = "JABATAN";
    public static final String PHOTO = "PHOTO";
    public static final String ID = "ID";

    public SessionManager(Context context) {
        this.context = context;
        sharedPreferences = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = sharedPreferences.edit();
    }

    public void createSession(String name, String email, String alamat, String phone, String departement, String jabatan, String id){

        editor.putBoolean(LOGIN, true);
        editor.putString(NAME, name);
        editor.putString(EMAIL, email);
        editor.putString(ALAMAT, alamat);
        editor.putString(NO_TELP, phone);
        editor.putString(DEPARTEMENT, departement);
        editor.putString(JABATAN, jabatan);
        editor.putString(ID, id);
        editor.apply();

    }


    public boolean isLoggin(){
        return sharedPreferences.getBoolean(LOGIN, false);
    }

    public void checkLogin(){

        if (!this.isLoggin()){
            Intent i = new Intent(context, LoginActivity.class);
            context.startActivity(i);
            ((MainActivity) context).finish();
        }
    }

    public HashMap<String, String> getUserDetail(){

        HashMap<String, String> user = new HashMap<>();
        user.put(NAME, sharedPreferences.getString(NAME, null));
        user.put(EMAIL, sharedPreferences.getString(EMAIL, null));
        user.put(ALAMAT, sharedPreferences.getString(ALAMAT, null));
        user.put(NO_TELP, sharedPreferences.getString(NO_TELP, null));
        user.put(DEPARTEMENT, sharedPreferences.getString(DEPARTEMENT, null));
        user.put(JABATAN, sharedPreferences.getString(JABATAN, null));
        user.put(ID, sharedPreferences.getString(ID, null));

        return user;
    }

    public void logout(){

        editor.clear();
        editor.commit();
        Intent i = new Intent(context, LoginActivity.class);
        context.startActivity(i);
        ((MainActivity) context).finish();

    }

}

untuk kekurangan code pada drawable, silahkan anda cari atau edit sesuai dengan keinginan anda. Tahap selanjutnya kita akan masuk ke file PHP. silahkan ikuti code berikut ini. Disini saya asumsikan bahwa anda sudah bisa membuat database sendiri dan mengkoneksikan php ke database mySql anda. jadi saya tidak memberikan tutorial tersebut.

Membuat File Login.php

Silahkan membuat file baru pada hosting anda dengan cara buat folder Profile > login.php kemudian ketikkan code berikut.
buatlah row pada MySql database anda sesuai dengan yang anda inginkan, namun tetap terisi email dan password seperti code dibawah ini.

<?php

if ($_SERVER['REQUEST_METHOD']=='POST') {

    $email = $_POST['email'];
    $password = $_POST['password'];

    require_once 'connect.php';

    $sql = "SELECT * FROM tbl_user WHERE email='$email' ";

    $response = mysqli_query($conn, $sql);

    $result = array();
    $result['login'] = array();
    
    if ( mysqli_num_rows($response) === 1 ) {
        
        $row = mysqli_fetch_assoc($response);

        if ( password_verify($password, $row['password']) ) {
            
            $index['name'] = $row['name'];
            $index['email'] = $row['email'];
            $index['password'] = $row['password'];
            $index['alamat'] = $row['alamat'];
            $index['phone'] = $row['phone'];
            $index['departement'] = $row['departement'];
            $index['jabatan'] = $row['jabatan'];
            $index['photo'] = $row['photo'];
            $index['id'] = $row['id'];

            array_push($result['login'], $index);

            $result['success'] = "1";
            $result['message'] = "success";
            echo json_encode($result);

            mysqli_close($conn);

        } else {

            $result['success'] = "0";
            $result['message'] = "Please Check Email and Password";
            echo json_encode($result);

            mysqli_close($conn);

        }

    }

}

?>

Selanjutnya silahkan anda membuat tabel database baru untuk menyimpan data dari form yang dibuat sebelumnya. Kemudian silahkan anda membuat file php pada hosting anda dengan nama terserah anda. namun ingat, nama file yang anda buat harus sama dengan nama destinasi php pada file java Android. silahkan cermati code android diatas.

Oke selanjutnya kita membuat file php, kami membuat file php dengan nama add_work_order.php dikarenakan sesuai dengan code aplikasi diatas.

Membuat PHP Upload Form

<?php
	include 'db/db_connect.php'; 
	class emp{}
	$Category_ID = $_POST['Category_ID'];
	$staff_name = $_POST['staff_name'];
	$date_n_time = $_POST['date_n_time'];
	$project_area = $_POST['project_area'];
	$departement_from = $_POST['departement_from'];
	$departement_to = $_POST['departement_to'];
	$priority_work = $_POST['priority_work'];
	$image_path = $_POST['image_path'];
	$description_work = $_POST['description_work'];
	$query = "set names 'utf8'";
	if (empty($staff_name)) { 
		$response = new emp();
		$response->success = 0;
		$response->message = "Please dont empty."; 
		die(json_encode($response));
	} else {
		$random = random_word(20);
		$path = "images_work/".$random.".png";
		$actualpath = "../../$path";
		$query = mysqli_query($con, "INSERT INTO tbl_work (Category_ID,staff_name,date_n_time,project_area,departement_from,departement_to,priority_work,image_path,description_work) 
		VALUE ('$Category_ID','$staff_name','$date_n_time','$project_area','$departement_from','$departement_to','$priority_work','$actualpath','$description_work')");
		if ($query){
	file_put_contents($path,base64_decode($image_path));
			$response = new emp();
			$response->success = 1;
			$response->message = "Successfully";
			die(json_encode($response));
		} else{ 
			$response = new emp();
			$response->success = 0;
			$response->message = "Please Check Your Connection";
			die(json_encode($response)); 
		}
		$query .= mysqli_query ($con, "SELECT description_work, COUNT ( * ) AS jumlah FROM tbl_work GROUP BY description_work HAVING COUNT ('description_work') > 1 LIMIT 0,50");
		$r = mysqli_query($query);
		while($d = mysqli_fetch_array($r))  
            {  
                echo $d['description_work']." , ".$d['jumlah'];  
                $limit=$d['jumlah']-1;  
                $query="DELETE FROM tbl_work WHERE description_work='".$d['description_work']."' LIMIT ".$limit;  
                if(mysqli_query($$query)) echo ", dihapus <br/>";  
                else echo ", gagal";  
            }  
	}	
	// fungsi random string pada gambar untuk menghindari nama file yang sama
	function random_word($id = 20){
		$pool = '1234567890abcdefghijkmnpqrstuvwxyz';
		$word = '';
		for ($i = 0; $i < $id; $i++){
			$word .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
		}
		return $word; 
	}
	mysqli_close($con);
?>	

nah sudah selesai. Apabila anda cermati sekali, code-code yang kami berikan diatas dapat anda pahami dengan mudah, namun tetap code ini harus anda implementasikan secara berurutan. setiap eror yang terjadi pasti mengenai data source yang belum lengkap. namun itu kami anggap normal dikarenakan kami tidak menampilkan kode secara keseluruhan pada postingan kali ini.

Apabila dan menginginkan Source Code secara lengkap, anda dapat mengirimkan email kepada kami di info@devatapixel.com, source code diatas merupakan aplikasi Work Order dan Share Work Knowledge yang sudah kami buat sebelumnya.