Sabtu, 10 Juli 2021

Android Studio - Tutorial CRUD SQLite

 Tugas ke-13.









1

Buka aplikasi Android Studio.




2

Pilih Create New Project, kemudian pilih Empty Activity, lalu klik Next.



3

Berikan nama sesuai selera (kalo ane CRUD_PHPMySQL). Ubah Language ke Java, kemudian pilih Finish.

 


4

Masukkan kode di bawah ke activity_main.xml.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="16dp"
    android:paddingBottom="16dp"
    tools:context=".MainActivity">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Nama Mahasiswa :"
        android:textSize="18dp"/>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editTextName"
        android:hint="Masukan Nama Anda"
        android:inputType="text" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="N R P :"
        android:textSize="18dp" />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editTextNRP"
        android:hint="Masukan NRP"
        android:inputType="number"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Kelas :"
        android:textSize="18dp" />
    <Spinner
        android:id="@+id/spinnerkelas"
        android:spinnerMode="dropdown"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Blog Url :"
        android:textSize="18dp"/>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editTextBlog"
        android:hint="Input Link URL Blog"
        android:inputType="text"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Tambah Data Mahasiswa"
        android:id="@+id/buttonAdd" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Daftar Mahasiswa"
        android:id="@+id/buttonView" />
</LinearLayout>



5

Masukkan kode di bawah ke MainActivity.java. Pada baris pertama tergantung nama aplikasi kalian, jadi jangan copy baris pertama!
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package arifsuhendraixg12.blogspot.com.crud_phpmysql;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.HashMap;

public   class MainActivity extends AppCompatActivity implements  View.OnClickListener {
    private EditText editTextName;
    private EditText editTextNRP;
    private EditText editTextBlog;
    private Button buttonAdd;
    private Button buttonView;
    private Spinner spinnerKelas;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editTextName = (EditText) findViewById(R.id.editTextName);
        editTextNRP = (EditText) findViewById(R.id.editTextNRP);
        editTextBlog = (EditText) findViewById(R.id.editTextBlog);
        buttonAdd = (Button) findViewById(R.id.buttonAdd);
        buttonView = (Button) findViewById(R.id.buttonView);
        spinnerKelas = (Spinner) findViewById(R.id.spinnerkelas);
        String[] spinnerItem = new String[]{"TI-1","TI-2","TI-3","TI-Mlm"};
        ArrayAdapter<String> adapter = new  ArrayAdapter<>(this, android.R.layout.simple_spinner_item,spinnerItem);
        spinnerKelas.setAdapter(adapter);

        buttonAdd.setOnClickListener(this);
        buttonView.setOnClickListener(this);
    }

    private void addMhs(){
        final String name = editTextName.getText().toString().trim();
        final String nrp = editTextNRP.getText().toString().trim();
        final String blog = editTextBlog.getText().toString().trim();
        final String kelas =(String) spinnerKelas.getSelectedItem();
        Log.d("kelas",kelas);

        class AddMhs extends AsyncTask<Void,Void,String>{
            ProgressDialog loading;
            @Override protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(MainActivity.this,"Menambahkan...","Tunggu...",false,false);
            }
            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                Toast.makeText(MainActivity.this,s,Toast.LENGTH_LONG).show();
            }
            @Override
            protected String doInBackground(Void... v) {
                HashMap<String,String> params = new HashMap<>();
                params.put(konfigurasi.KEY_MHS_NAMA,name);
                params.put(konfigurasi.KEY_MHS_NRP,nrp);
                params.put(konfigurasi.KEY_MHS_KELAS,kelas);
                params.put(konfigurasi.KEY_MHS_BLOG,blog);

                RequestHandler rh = new RequestHandler();
                String res = rh.sendPostRequest(konfigurasi.URL_ADD, params);
                Log.d("res",res);
                return res;
            }
        }
        AddMhs ae = new AddMhs();
        ae.execute();
    }
    @Override
    public void onClick(View v) {
        if(v == buttonAdd){
            addMhs();
        }
        if(v == buttonView){
            startActivity(new Intent(this,TampilSemuaMhs.class));
        }
    }
}
 

6

Selanjutnya kita buat layout untuk menampilkan seluruh database. Klik kanan folder java > New > Activity > Empty Activity. Lalu kita beri nama "TampilSemuaMhs" dan masukkan kode di bawah untuk TampilSemuaMhs.java.
 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package arifsuhendraixg12.blogspot.com.crud_phpmysql;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;

public class TampilSemuaMhs extends AppCompatActivity implements ListView.OnItemClickListener{
    private ListView listView;
    private String JSON_STRING;

    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tampil_semua_mhs);
        listView = (ListView) findViewById(R.id.listView);
        listView.setOnItemClickListener(this);
        getJSON();
    }

    private void showMhs(){
        JSONObject jsonObject = null;
        ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
        try {
            jsonObject = new JSONObject(JSON_STRING);
            JSONArray result = jsonObject.getJSONArray(konfigurasi.TAG_JSON_ARRAY);
            for(int i = 0; i<result.length(); i++){
                JSONObject jo = result.getJSONObject(i);
                String id = jo.getString(konfigurasi.TAG_ID);

                String name = jo.getString(konfigurasi.TAG_NAMA);
                HashMap<String,String> mhs = new HashMap<>();
                mhs.put(konfigurasi.TAG_ID,id);
                mhs.put(konfigurasi.TAG_NAMA,name);
                list.add(mhs);
            }
        }
        catch (JSONException e) { e.printStackTrace();
        }
        ListAdapter adapter = new SimpleAdapter(
                TampilSemuaMhs.this, list, R.layout.list_item,
                new String[]{konfigurasi.TAG_ID,konfigurasi.TAG_NAMA},
                new int[]{R.id.id, R.id.name});
        listView.setAdapter(adapter);
    }
    private void getJSON(){
        class GetJSON extends AsyncTask<Void,Void,String>{
            ProgressDialog loading;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(TampilSemuaMhs.this,"Mengambil Data","Mohon Tunggu...",false,false);
            }
            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                JSON_STRING = s;
                showMhs();
            }
            @Override protected String doInBackground(Void... params) { RequestHandler rh = new RequestHandler();
                Log.d("testing","test");
                String s = rh.sendGetRequest(konfigurasi.URL_GET_ALL);
                Log.d("response",s);

                return s;
            }
        }
        GetJSON gj = new GetJSON();
        gj.execute();
    }
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(this, TampilMhs.class);
        HashMap<String,String> map =(HashMap)parent.getItemAtPosition(position);
        String mhsId = map.get(konfigurasi.TAG_ID).toString();
        intent.putExtra(konfigurasi.MHS_ID,mhsId);
        startActivity(intent);
    }
}



7

Untuk layout activity_tampil_semua_mhs.xml, masukkan kode di dibawah.
 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<?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:orientation="vertical"
    android:layout_height="match_parent"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="16dp"
    android:paddingBottom="16dp"
    tools:context=".TampilSemuaMhs">

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



8

Kita buat layout lagi caranya sama seperti sebelumnya, untuk Activity Name diisi "ListView" dan Layout Name diisi "list_item". Isikan kode di bawah untuk list_item.xml, sedangkan untuk ListView.java dibiarkan apa adanya saja.
 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>



9

Kita buat layout lagi, untuk Activity Name diisi "TampilMhs" dan Layout Name biarkan sistem otomatis yang mengisi. Masukkan kode di bawah pada TampilMhs.java.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
package arifsuhendraixg12.blogspot.com.crud_phpmysql;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;

public class TampilMhs extends AppCompatActivity implements View.OnClickListener{
    private EditText editTextId;
    private EditText editTextName;
    private EditText editTextNRP;
    private EditText editTextKelas;
    private EditText editTextBlog;
    private Button buttonUpdate;
    private Button buttonDelete;
    private String id;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tampil_mhs);
        Intent intent = getIntent();
        id = intent.getStringExtra(konfigurasi.MHS_ID);
        editTextId = (EditText) findViewById(R.id.editTextId);
        editTextName = (EditText) findViewById(R.id.editTextName);
        editTextNRP = (EditText) findViewById(R.id.editTextNRP);
        editTextKelas = (EditText) findViewById(R.id.editTextKelas);
        editTextBlog = (EditText) findViewById(R.id.editTextBlog);
        buttonUpdate = (Button) findViewById(R.id.buttonUpdate);
        buttonDelete = (Button) findViewById(R.id.buttonDelete);
        buttonUpdate.setOnClickListener(this);
        buttonDelete.setOnClickListener(this);
        editTextId.setText(id);
        getMhs();
    }
    private void getMhs(){
        class GetMhs extends AsyncTask<Void,Void,String>{ ProgressDialog loading;
            @Override
            protected void onPreExecute() { super.onPreExecute();
                loading = ProgressDialog.show(TampilMhs.this,"Fetching...","Wait...",false,false);
            }
            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                showMhs(s);
            }
            @Override
            protected String doInBackground(Void... params) { RequestHandler rh = new RequestHandler();
                String s = rh.sendGetRequestParam(konfigurasi.URL_GET_EMP,id);
                return s;
            }
        }
        GetMhs ge = new GetMhs();
        ge.execute();
    }
    private void showMhs(String json){
        try {
            JSONObject jsonObject = new JSONObject(json);
            JSONArray result = jsonObject.getJSONArray(konfigurasi.TAG_JSON_ARRAY);
            JSONObject c = result.getJSONObject(0);
            String name = c.getString(konfigurasi.TAG_NAMA);
            String nrp = c.getString(konfigurasi.TAG_NRP);
            String kelas = c.getString(konfigurasi.TAG_KELAS);
            String blog = c.getString(konfigurasi.TAG_BLOG);
            editTextName.setText(name);
            editTextNRP.setText(nrp);
            editTextKelas.setText(kelas);
            editTextBlog.setText(blog);
        }
        catch (JSONException e) { e.printStackTrace();
        }
    }
    private void updateMhs(){
        final String name = editTextName.getText().toString().trim();
        final String nrp = editTextNRP.getText().toString().trim();
        final String kelas = editTextKelas.getText().toString().trim();
        final String blog = editTextBlog.getText().toString().trim();
        class UpdateMhs extends AsyncTask<Void,Void,String>{ ProgressDialog loading;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(TampilMhs.this,"Updating...","Wait...",false,
                        false);
            }
            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                Toast.makeText(TampilMhs.this,s,Toast.LENGTH_LONG).show();
            }
            @Override
            protected String doInBackground(Void... params) { HashMap<String,String> hashMap = new HashMap<>();
                hashMap.put(konfigurasi.KEY_MHS_ID,id);
                hashMap.put(konfigurasi.KEY_MHS_NAMA,name);
                hashMap.put(konfigurasi.KEY_MHS_NRP,nrp);
                hashMap.put(konfigurasi.KEY_MHS_KELAS,kelas);
                hashMap.put(konfigurasi.KEY_MHS_BLOG,blog);
                RequestHandler rh = new RequestHandler();
                String s = rh.sendPostRequest(konfigurasi.URL_UPDATE_EMP,hashMap);
                return s;
            }
        }
        UpdateMhs ue = new UpdateMhs();
        ue.execute();
    }
    private void deleteMhs(){
        class DeleteMhs extends AsyncTask<Void,Void,String> { ProgressDialog loading;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(TampilMhs.this, "Updating...", "Tunggu...", false, false);
            }
            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                Toast.makeText(TampilMhs.this, s, Toast.LENGTH_LONG).show();
            }
            @Override
            protected String doInBackground(Void... params) { RequestHandler rh = new RequestHandler();
                String s = rh.sendGetRequestParam(konfigurasi.URL_DELETE_EMP, id);
                return s;
            }
        }
        DeleteMhs de = new DeleteMhs();
        de.execute();
    }
    private void confirmDeleteMhs(){
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage("Apakah Kamu Yakin Ingin Menghapus Data ini?");
        alertDialogBuilder.setPositiveButton("Ya", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        deleteMhs();
                        startActivity(new Intent(TampilMhs.this,TampilSemuaMhs.class));
                    }
                }
        );
        alertDialogBuilder.setNegativeButton("Tidak", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int arg1) { } });
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }
    @Override
    public void onClick(View v) { if(v == buttonUpdate){ updateMhs();
    }
        if(v == buttonDelete){ confirmDeleteMhs();
        }
    }
}


10

Untuk activity_tampil_mhs.xml masukkan kode di bawah.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?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:orientation="vertical"
    android:layout_height="match_parent"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="16dp"
    android:paddingBottom="16dp"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ID Mahasiswa :" />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editTextId" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Nama Mahasiswa :" />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editTextName" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="N R P :" />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editTextNRP" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Kelas :" />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editTextKelas" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Blog URL :" />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editTextBlog" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Update Data Mahasiswa"
        android:id="@+id/buttonUpdate" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hapus Data"
        android:id="@+id/buttonDelete" />
</LinearLayout>


11

Buat class baru bernama "konfigurasi" dan masukkan kode berikut.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package arifsuhendraixg12.blogspot.com.crud_phpmysql;

public class konfigurasi {
    public static final String URL_ADD="http://android.unggasid.com/mhs/tambahMhs.php";
    public static final String URL_GET_ALL = "http://android.unggasid.com/mhs/tampilSemuaMhs.php";
    public static final String URL_GET_EMP ="http://android.unggasid.com/mhs/tampilMhs.php?id=";
    public static final String URL_UPDATE_EMP = "http://android.unggasid.com/mhs/updateMhs.php";
    public static final String URL_DELETE_EMP = "http://android.unggasid.com/mhs/hapusMhs.php?id=";

    public static final String KEY_MHS_ID = "id";
    public static final String KEY_MHS_NAMA = "name";
    public static final String KEY_MHS_NRP = "nrp";
    public static final String KEY_MHS_KELAS = "kelas";
    public static final String KEY_MHS_BLOG = "blog";

    public static final String TAG_JSON_ARRAY="result";
    public static final String TAG_ID = "id";
    public static final String TAG_NAMA = "name";
    public static final String TAG_NRP = "nrp";
    public static final String TAG_KELAS = "kelas";
    public static final String TAG_BLOG = "blog";

    public static final String MHS_ID = "mhs_id";
}


12

Buat class baru bernama "RequestHandler", dan masukkan kode berikut.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package arifsuhendraixg12.blogspot.com.crud_phpmysql;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;

public class RequestHandler {
    //Metode yang digunakan mengirim httpPostRequest
    public String sendPostRequest(String requestURL, HashMap<String, String> postDataParams)
    {
        URL url;
        StringBuilder sb = new StringBuilder();
        try {
            url = new URL(requestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));
            writer.flush();
            writer.close();
            os.close();
            int responseCode = conn.getResponseCode();
            if (responseCode == HttpsURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                sb = new StringBuilder();
                String response;
                while ((response = br.readLine()) != null){ sb.append(response);
                }
            }
        }
        catch (Exception e) { e.printStackTrace();
        }
        return sb.toString();
    }
    public String sendGetRequest(String requestURL){
        StringBuilder sb =new StringBuilder();
        try {
            URL url = new URL(requestURL);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String s;
            while((s=bufferedReader.readLine())!=null){ sb.append(s+"\n");
            }
        }
        catch(Exception e){ }
        return sb.toString();
    }
    public String sendGetRequestParam(String requestURL, String id){ StringBuilder sb =new StringBuilder();
        try {
            URL url = new URL(requestURL+id);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String s; while((s=bufferedReader.readLine())!=null){ sb.append(s+"\n");
            }
        }
        catch(Exception e){ }
        return sb.toString();
    }
    private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException { StringBuilder result = new StringBuilder();
        boolean first = true;
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (first)
                first = false;
            else
                result.append("&");
            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }
        return result.toString();
    }
}


13

Sesuaikan AndroidManifest seperti berikut. Tambahkan baris 4 dan baris 10 ke milik kalian.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="arifsuhendraixg12.blogspot.com.crud_phpmysql">
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:usesCleartextTraffic="true"
        android:supportsRtl="true"
        android:theme="@style/Theme.CRUD_PHPMySQL">
        <activity android:name=".TampilMhs"></activity>
        <activity android:name=".ListView" />
        <activity android:name=".TampilSemuaMhs" />
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>


14

Sisanya tinggal di Run dalam emulator atau langsuung di hp kalian. Untuk full demo ada di dalam video.




Tidak ada komentar:

Posting Komentar