Membuat aplikasi kamus android dengan android studio dan database mysql

Selamat sore teman-teman, apa kabar semuanya…mudah-mudahan pada baik semuanya ya…amin.
Kali ini kita akan membuat aplikasi berbasis android yaitu aplikasi kamus dengan menggunakan database mysql. Dalam aplikasi ini nantinya sudah terdapat proses CRUD alias create update dan delete data. Jadi aplikasi ini nantinya bisa digunakan sebagai referensi teman-teman yang ingin belajar CRUD di android dengan database MYSQL.

Sedikit screenshot dari aplikasinya:
       
Langsung aja pertama kita buat dulu databasenya di mysql:
Buat database dengan nama ‘kamus’, 


Kemudian buat tabel ‘data’ dengan rincian sebagai berikut:
 

Setelah databasenya kita buat, langkah selanjutnya adalah membuat aplikasi yang akan membaca database tersebut, disini saya menggunakan Android studio untuk pembuatan aplikasi tersebut. Oke setelah android studio dijalankan langkah selanjutnya adalah membuat project baru dengan cara pilih: start a new Android studio project:


Dan kemudian atur Application name, company name, dan package name seperti dibawah ini:
 
Oh iya untuk project location nya disesuaikan dengan kebutuhan ya, tetapi alangkah baiknya ditentukan seperti yang saya contohkan diatas. Oke…setelah itu tekan next, kemudian pilih minimum sdk, disini saya menggunakan API 18:

Kemudian tekan next lagi, kemudian pilih blank activity
 
Dan Finish.
 
Oke…tunggu beberapa saat untuk gradle melakukan sinkronisasi terhadap project kita. Jika jendela project sudah terbuka, sekarang kita mulai membuat layout untuk aplikasinya.
activity_main.xml
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<linearlayout android:background="#009968" android:gravity="center_horizontal" android:id="@+id/LinearLayout1" android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" tools:context=".MainActivity" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
 
    <linearlayout android:gravity="center_vertical" android:layout_height="wrap_content" android:layout_marginbottom="8dp" android:layout_width="match_parent">
 
        <edittext android:ems="10" android:hint="cari kata" android:id="@+id/input" android:layout_height="wrap_content" android:layout_weight="1" android:layout_width="wrap_content" android:textcolor="@color/background_material_light" android:textcolorhint="@color/background_material_light">
 
            <requestfocus>
        </requestfocus></edittext>
 
        <imagebutton android:background="@android:drawable/btn_default" android:id="@+id/bSearch" android:layout_height="wrap_content" android:layout_weight="1" android:layout_width="wrap_content" android:src="@android:drawable/ic_menu_search">
    </imagebutton></linearlayout>
 
    <textview android:id="@+id/output" android:layout_height="wrap_content" android:layout_width="match_parent" android:text="terjemahan sunda" android:textappearance="?android:attr/textAppearanceMedium" android:textcolor="@color/background_material_light">
 
    <view android:background="@android:color/darker_gray" android:id="@+id/view1" android:layout_height="2dp" android:layout_width="wrap_content">
 
    <button android:background="@android:drawable/btn_default" android:drawableleft="@android:drawable/ic_input_add" android:id="@+id/bTambah" android:layout_height="wrap_content" android:layout_margintop="10dp" android:layout_width="wrap_content" android:text="tambah kata">
 
</button></view></textview></linearlayout>
activity_tambah.xml
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!--?xml version="1.0" encoding="utf-8"?-->
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" xmlns:app="http://schemas.android.com/tools" android:gravity="center_horizontal" android:background="#009968">
 
    <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Bhs. Indonesia" android:textappearance="?android:attr/textAppearanceMedium" android:textcolor="@color/background_material_light">
 
    <edittext android:id="@+id/addIndo" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:textcolor="@color/background_material_light">
 
        <requestfocus>
    </requestfocus></edittext>
 
    <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Bhs. Sunda" android:textappearance="?android:attr/textAppearanceMedium" android:textcolor="@color/background_material_light">
 
    <edittext android:id="@+id/addSunda" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:textcolor="@color/background_material_light">
 
    <button android:id="@+id/bSimpan" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="simpan" android:background="@android:drawable/btn_default" android:drawableleft="@android:drawable/ic_menu_save">
 
    <listview android:id="@+id/listView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="4dp" app:listitem="@layout/item_custom_listview">
 
    </listview>
 
 
</button></edittext></textview></textview></linearlayout>
dialog_delete.xml
?
1
2
3
4
5
6
7
8
9
10
11
12
13
<!--?xml version="1.0" encoding="utf-8"?-->
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_horizontal">
 
    <tablelayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margintop="10dp">
        <tablerow>
            <button android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/btYa" android:text="Ya" android:layout_marginright="20dp" android:background="@android:drawable/btn_default">
 
            </button><button android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/btTidak" android:text="Tidak" android:background="@android:drawable/btn_default">
         
     
 
 
</button></tablerow></tablelayout></linearlayout>
dialog_edit.xml
?
1
2
3
4
5
6
7
8
9
10
11
<!--?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" android:gravity="center_horizontal">
 
    <edittext android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/edIndo" android:hint="Bahasa Indonesia">
 
    <edittext android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/edSunda" android:hint="Bahasa Sunda">
 
    <button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/btUpdate" android:text="Update" android:background="@android:drawable/btn_default" android:drawableleft="@android:drawable/ic_menu_rotate">
 
 
</button></edittext></edittext></linearlayout>
dialog_option.xml
?
1
2
3
4
5
6
7
8
9
<!--?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">
 
    <button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/opUpdate" android:text="Update" android:background="@android:drawable/btn_default_small">
 
    </button><button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/opDelete" android:text="Delete" android:background="@android:drawable/btn_default_small">
 
 
</button></linearlayout>
item_custom_listview.xml
?
1
2
3
4
5
6
7
8
9
10
11
12
13
<!--?xml version="1.0" encoding="utf-8"?-->
<tablelayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/TableLayout1" android:layout_width="match_parent" android:layout_height="match_parent">
 
    <tablerow android:id="@+id/tableRow1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="4dp">
 
        <textview android:id="@+id/outIndo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="4dp" android:text="kata indonesia" android:textappearance="?android:attr/textAppearanceMedium" android:textcolor="@color/background_material_light">
 
        <textview android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_margin="4dp" android:gravity="center_vertical" android:text="=" android:textappearance="?android:attr/textAppearanceMedium" android:textcolor="@color/background_material_light">
 
        <textview android:id="@+id/outSunda" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="4dp" android:text="kata jawa" android:textappearance="?android:attr/textAppearanceMedium" android:textcolor="@color/background_material_light">
    </textview></textview></textview></tablerow>
 
</tablelayout>
Setelah membuat semua layout, langkah selanjutnya adalah membuat class-class yang diperlukan:
EntitasKamus.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
package com.infinityware.org.kamusku;
 
/**
 * Created by Andrya on 9/13/2015.
 */
public class EntitasKamus {
    String indo = "";
    String sunda = "";
    String id = "";
 
    public void setId(String ids){
        this.id = ids;
    }
 
    public String getId(){
        return this.id;
    }
 
    public void setIndo(String in){
        this.indo = in;
    }
 
    public String getIndo(){
        return this.indo;
    }
 
    public void setSunda(String sun){
        this.sunda = sun;
    }
 
    public String getSunda(){
        return this.sunda;
    }
 
}
JSONParser.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
package com.infinityware.org.kamusku;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
 
/**
 * Created by Andrya on 9/13/2015.
 */
public class JSONParser {
    private JSONObject jsonObject;
    String jsonString;
    InputStream is;
 
    public JSONObject getJsonObject(String method, String url, List<namevaluepair> param) throws IOException{
 
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(param));
            HttpResponse httpResponse = client.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }catch(UnsupportedEncodingException e){
            e.printStackTrace();
        }catch(ClientProtocolException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }
 
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"));
            StringBuilder sb = new StringBuilder();
            String line = "";
            while ((line = reader.readLine()) != null) {
                sb.append(line + "/n");
            }
            jsonString = sb.toString();
 
            jsonObject = null;
        }catch(Exception e){
            e.printStackTrace();
        }
        try {
            jsonObject = new JSONObject(jsonString);
        } catch (JSONException e) {
            e.printStackTrace();
        }
 
        return jsonObject;
    }
 
}
 
</namevaluepair>
AmbilData.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
package com.infinityware.org.kamusku;
 
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
 
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
 
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
 
/**
 * Created by Andrya on 9/13/2015.
 */
public class InUpDelData extends AsyncTask<string,string,string> {
 
    ProgressDialog pg;
    Context context;
    JSONParser jsonParser;
    JSONObject jsonObject;
    String act;
 
    public void init(Context c,String ids, String indo, String sunda, String action){
        context = c;
        act = action;
        InUpDelData inUpDelData = this;
        inUpDelData.execute(indo,sunda,action,ids);
    }
 
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pg = new ProgressDialog(context);
        pg.setTitle("Menyimpan Data");
        pg.setMessage("Mohon Tunggu");
        pg.show();
    }
 
    @Override
    protected String doInBackground(String... params) {
        jsonParser = new JSONParser();
        jsonObject = null;
 
        String indo,sunda,aksi,sukses,id;
        sukses = "";
        indo = (String) params[0];
        sunda = (String) params[1];
        aksi = (String) params[2];
        id = (String) params[3];
 
        List<namevaluepair> param = new ArrayList<namevaluepair>();
        param.add(new BasicNameValuePair("bIndo",indo));
        param.add(new BasicNameValuePair("bSunda",sunda));
        param.add(new BasicNameValuePair("action",aksi));
        param.add(new BasicNameValuePair("id",id));
 
        try {
            jsonObject = jsonParser.getJsonObject("POST",url,param);
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        try {
            int stat = jsonObject.getInt("status");
            if(stat == 1){
                sukses = "sukses";
            }else{
                sukses = "gagal";
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
 
 
 
        return sukses;
    }
 
    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        if(s=="sukses"){
            if(act=="delete"){
                Toast.makeText(context,"Kata berhasil dihapus!", Toast.LENGTH_LONG).show();
            }else {
                Toast.makeText(context, "Kata berhasil disimpan!", Toast.LENGTH_LONG).show();
            }
        }else{
            if(act=="delete"){
                Toast.makeText(context,"Kata gagal dihapus!", Toast.LENGTH_LONG).show();
            }else {
                Toast.makeText(context, "Kata gagal disimpan!", Toast.LENGTH_LONG).show();
            }
        }
        pg.dismiss();
    }
}
 
</namevaluepair></namevaluepair></string,string,string>
KamusBaseAdapter.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
package com.infinityware.org.kamusku;
 
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
 
import java.util.ArrayList;
 
/**
 * Created by Andrya on 9/13/2015.
 */
public class KamusBaseAdapter extends BaseAdapter {
 
    ArrayList<entitaskamus> searchArrayList;
    LayoutInflater mInflater;
 
    public KamusBaseAdapter(Context context, ArrayList<entitaskamus> result){
        searchArrayList = result;
        mInflater = LayoutInflater.from(context);
    }
 
    @Override
    public int getCount() {
        return searchArrayList.size();
    }
 
    @Override
    public Object getItem(int position) {
        return searchArrayList.get(position);
    }
 
    @Override
    public long getItemId(int position) {
        return position;
    }
 
    @Override
    public View getView(int position, View v, ViewGroup parent) {
        ViewHolder holder;
 
        if(v==null){
            v = mInflater.inflate(R.layout.item_custom_listview,null);
            holder = new ViewHolder();
 
            holder.bIndo = (TextView) v.findViewById(R.id.outIndo);
            holder.bSunda = (TextView) v.findViewById(R.id.outSunda);
 
            v.setTag(holder);
 
        }else{
            holder = (ViewHolder) v.getTag();
 
        }
        holder.bIndo.setText(searchArrayList.get(position).getIndo());
        holder.bSunda.setText(searchArrayList.get(position).getSunda());
        return v;
    }
 
    class ViewHolder{
        TextView bIndo,bSunda;
    }
}
 
</entitaskamus></entitaskamus>
MainActivity.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
package com.infinityware.org.kamusku;
 
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import com.infinityware.org.kamusku.AmbilData.JSONObjectResult;
 
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
 
import java.util.ArrayList;
 
 
public class MainActivity extends Activity {
 
    EntitasKamus kamus = new EntitasKamus();
    ArrayList<entitaskamus> listKamus = new ArrayList<entitaskamus>();
 
    EditText indo;
    TextView sunda;
    Button btTambah;
    ImageButton btTrans;
    //String url = "http://10.0.2.2/KamusAndroid/kamus.php"; //INI UNTUK Emulator
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        indo = (EditText) findViewById(R.id.input);
        sunda = (TextView) findViewById(R.id.output);
        btTambah = (Button) findViewById(R.id.bTambah);
        btTrans = (ImageButton) findViewById(R.id.bSearch);
 
        btTambah.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent in = new Intent(MainActivity.this, TambahActivity.class);
                Bundle b = new Bundle();
                b.putString("var","kosong");
                in.putExtras(b);
                startActivity(in);
 
            }
        });
 
        btTrans.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AmbilData ambilData = new AmbilData();
                ambilData.init(indo.getText().toString(),url,MainActivity.this,jres);
                indo.setText("");
            }
        });
 
    }
 
    JSONObjectResult jres = new JSONObjectResult() {
        @Override
        public void gotJSONObject(JSONObject jsonObject) {
            try {
                JSONArray jsonArray = jsonObject.getJSONArray("kamus");
                for(int i=0; i< <jsonArray.length(); i++){
                    sunda.setText(jsonArray.getJSONObject(i).getString("sunda"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };
 
}
 
</entitaskamus></entitaskamus>
TambahActivity.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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
package com.infinityware.org.kamusku;
 
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
 
import com.infinityware.org.kamusku.AmbilData.JSONObjectResult;
 
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
 
import java.util.ArrayList;
 
/**
 * Created by Andrya on 9/13/2015.
 */
public class TambahActivity extends Activity {
 
    ArrayList<entitaskamus> listKamus = new ArrayList<entitaskamus>();
    EntitasKamus kamus;
    int count = 0;
    ListView lv;
    Button btSimpan;
    EditText bIndo,bSunda;
    //String url = "http://10.0.2.2/KamusAndroid/kamus.php"; //INI UNTUK Emulator
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tambah);
 
        lv = (ListView) findViewById(R.id.listView1);
        bIndo = (EditText) findViewById(R.id.addIndo);
        bSunda = (EditText) findViewById(R.id.addSunda);
        btSimpan = (Button) findViewById(R.id.bSimpan);
 
        loadKamus();
 
        btSimpan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InUpDelData inUpDelData = new InUpDelData();
                inUpDelData.init(TambahActivity.this,"",bIndo.getText().toString(),
                        bSunda.getText().toString(),"insert");
                loadKamus();
                bIndo.setText("");
                bSunda.setText("");
            }
        });
 
    }
 
    //MEMUAT KATA DALAM DATABASE
    public void loadKamus(){
        Bundle b = this.getIntent().getExtras();
        String var = b.getString("var");
        final AmbilData ambilData = new AmbilData();
        ambilData.init(var,url,TambahActivity.this,jres);
    }
 
    //DEKLARASI UNTUK ABSTRACT CLASS
    public JSONObjectResult jres = new JSONObjectResult() {
        @Override
        public void gotJSONObject(JSONObject jsonObject) {
            try {
                JSONArray jsonArray = jsonObject.getJSONArray("kamus");
                    for(int i=0; i < <jsonArray.length();i++){
                    kamus = new EntitasKamus();
                    kamus.setId(jsonArray.getJSONObject(i).getString("id"));
                    kamus.setIndo(jsonArray.getJSONObject(i).getString("indonesia"));
                    kamus.setSunda(jsonArray.getJSONObject(i).getString("sunda"));
 
                    listKamus.add(kamus);
                }
 
            } catch (JSONException e) {
                e.printStackTrace();
            }
 
            if(count>0){
                listKamus.clear();
                KamusBaseAdapter kamusBaseAdapter = new KamusBaseAdapter(TambahActivity.this,listKamus);
                lv.setAdapter(kamusBaseAdapter);
                loadKamus();
                count = -1;
            }else{
                KamusBaseAdapter kamusBaseAdapter = new KamusBaseAdapter(TambahActivity.this,listKamus);
                lv.setAdapter(kamusBaseAdapter);
            }
 
            lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<!--?--> parent, View view, int position, long id) {
                    String ids,indo,sunda;
                    ids = listKamus.get(position).getId();
                    indo = listKamus.get(position).getIndo();
                    sunda = listKamus.get(position).getSunda();
                    dialogOption(ids,indo,sunda);
                    return false;
                }
            });
 
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<!--?--> parent, View view, int position, long id) {
 
                }
            });
 
            count +=1;
        }
    };
 
 
    //DIALOG PILIH AKSI
    public void dialogOption(final String id, final String indo, final String sunda){
        final Dialog dlg = new Dialog(this);
        dlg.setContentView(R.layout.dialog_option);
        dlg.setTitle("Pilih Aksi");
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(dlg.getWindow().getAttributes());
        lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
        lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        dlg.getWindow().setAttributes(lp);
 
        Button update,delete;
        update = (Button) dlg.findViewById(R.id.opUpdate);
        delete = (Button) dlg.findViewById(R.id.opDelete);
 
        update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogUpdate(id, indo, sunda);
                dlg.dismiss();
            }
        });
 
        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogDelete(id);
                dlg.dismiss();
            }
        });
 
        dlg.show();
    }
 
    //DIALOG UPDATE
    public void dialogUpdate(final String id, String indo, String sunda){
        final Dialog dialog = new Dialog(TambahActivity.this);
        dialog.setContentView(R.layout.dialog_edit);
        dialog.setTitle("Perbaharaui Kata");
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(dialog.getWindow().getAttributes());
        lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
        dialog.getWindow().setAttributes(lp);
 
        final EditText edIndo,edSunda;
 
        edIndo = (EditText) dialog.findViewById(R.id.edIndo);
        edSunda = (EditText) dialog.findViewById(R.id.edSunda);
        Button btUpdate, btBack;
 
        edIndo.setText(indo);
        edSunda.setText(sunda);
 
        btUpdate = (Button) dialog.findViewById(R.id.btUpdate);
 
 
        btUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InUpDelData inUpDelData = new InUpDelData();
                inUpDelData.init(TambahActivity.this, id, edIndo.getText().toString()
                        , edSunda.getText().toString(), "update");
                dialog.dismiss();
                loadKamus();
            }
        });
 
 
        dialog.show();
    }
 
    //DIALOG DELETE
    public void dialogDelete(final String id){
        final Dialog dlg = new Dialog(this);
        dlg.setContentView(R.layout.dialog_delete);
        dlg.setTitle("Apakah anda yakin?");
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(dlg.getWindow().getAttributes());
        lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
        lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        dlg.getWindow().setAttributes(lp);
 
        Button btYa, btTidak;
 
        btYa = (Button) dlg.findViewById(R.id.btYa);
        btTidak = (Button) dlg.findViewById(R.id.btTidak);
 
        btYa.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dlg.dismiss();
                InUpDelData inUpDelData = new InUpDelData();
                inUpDelData.init(TambahActivity.this,id,"","","delete");
 
                loadKamus();
            }
        });
 
        btTidak.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dlg.dismiss();
            }
        });
 
        dlg.show();
    }
 
}
 
 
 
 
 
</entitaskamus></entitaskamus>
InUpDelData.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
package com.infinityware.org.kamusku;
 
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
 
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
 
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
 
/**
 * Created by Andrya on 9/13/2015.
 */
public class InUpDelData extends AsyncTask<string,string,string> {
 
    ProgressDialog pg;
    Context context;
    JSONParser jsonParser;
    JSONObject jsonObject;
    String act;
 
    public void init(Context c,String ids, String indo, String sunda, String action){
        context = c;
        act = action;
        InUpDelData inUpDelData = this;
        inUpDelData.execute(indo,sunda,action,ids);
    }
 
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pg = new ProgressDialog(context);
        pg.setTitle("Menyimpan Data");
        pg.setMessage("Mohon Tunggu");
        pg.show();
    }
 
    @Override
    protected String doInBackground(String... params) {
        jsonParser = new JSONParser();
        jsonObject = null;
 
        String indo,sunda,aksi,sukses,id;
        sukses = "";
        indo = (String) params[0];
        sunda = (String) params[1];
        aksi = (String) params[2];
        id = (String) params[3];
 
        List<namevaluepair> param = new ArrayList<namevaluepair>();
        param.add(new BasicNameValuePair("bIndo",indo));
        param.add(new BasicNameValuePair("bSunda",sunda));
        param.add(new BasicNameValuePair("action",aksi));
        param.add(new BasicNameValuePair("id",id));
 
        try {
            jsonObject = jsonParser.getJsonObject("POST",url,param);
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        try {
            int stat = jsonObject.getInt("status");
            if(stat == 1){
                sukses = "sukses";
            }else{
                sukses = "gagal";
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
 
 
 
        return sukses;
    }
 
    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        if(s=="sukses"){
            if(act=="delete"){
                Toast.makeText(context,"Kata berhasil dihapus!", Toast.LENGTH_LONG).show();
            }else {
                Toast.makeText(context, "Kata berhasil disimpan!", Toast.LENGTH_LONG).show();
            }
        }else{
            if(act=="delete"){
                Toast.makeText(context,"Kata gagal dihapus!", Toast.LENGTH_LONG).show();
            }else {
                Toast.makeText(context, "Kata gagal disimpan!", Toast.LENGTH_LONG).show();
            }
        }
        pg.dismiss();
    }
}
 
</namevaluepair></namevaluepair></string,string,string>
Dan terakhir, kita harus memberi permission kepada aplikasi untuk berkomunikasi dengan server tempat dimana database mysql berada, atur AndroidManifest.xml seperti berikut:

?
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"?-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.infinityware.org.kamusku">
 
    <uses-permission android:name="android.permission.INTERNET">
 
    <application android:allowbackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme">
        <activity android:name=".MainActivity" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN">
 
                <category android:name="android.intent.category.LAUNCHER">
            </category></action></intent-filter>
        </activity>
        <activity android:name=".TambahActivity" android:label="@string/app_name">
        </activity>
    </application>
 
</uses-permission></manifest>

Setelah selesai dengan semua hal yang berhubungan dengan Android Studio, langkah selanjutnya kita perlu membuat beberapa file PHP untuk melakukan query dan juga berkomunikasi dengan database, file-file tersebut adalah sebagai berikut:
connection.php
?
1
2
3
4
5
6
7
8
<<!--?php
 $username = "root";
 $password = "";
 $host = "localhost";
 $dbname = "kamus";
 mysql_connect($host, $username, $password) or die ("connection failed");
 mysql_select_db($dbname) or die ("no database");
<?-->
tambah.php
?
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
<<!--?php
 require_once "connection.php";
 $json = array();
 $aksi = $_POST['action'];
 $id = $_POST['id'];
 $indo = $_POST['bIndo'];
 $sunda = $_POST['bSunda'];
 //$var = "minum";
 if($aksi == "insert"){
  $sql = "insert into data values(null,'".$indo."','".$sunda."')";
  $q = mysql_query($sql);
  if($q==1){
   $json['status']=1;
    
  }else{
   $json['status']=0;
  }
  echo json_encode($json);
 }else if($aksi=="update"){
  $sqlselect = "update data set indonesia = '".$indo."', sunda = '".$sunda."' where id = '".$id."'";
  $hasil = mysql_query($sqlselect);
  if($hasil){
   $json['status']=1;
    
  }else{
   $json['status']=0;
  }
  echo json_encode($json);
 }else if($aksi == "delete"){
  $q = mysql_query("delete from data where id = '".$id."'");
  if($q == true){
   $json['status']=1;
  }else{
   $json['status']=0;
  }
  echo json_encode($json);
 }
  
  
<?-->
Kamus.php
?
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
<<!--?php
 require_once "connection.php";
 $json = array();
 $var = $_POST['bIndo'];
 //$var = "minum";
 if($var == 'kosong'){
  $sqlselect = "SELECT * FROM `data` order by indonesia asc";
  $hasil = mysql_query($sqlselect);
  while($row = mysql_fetch_assoc($hasil)){
   $menu[] = $row;
  }
  if(is_array($menu)){
   $json['kamus']=$menu;
   echo json_encode($json);
  }
 }else{
  $sqlselect = "select sunda from data where indonesia = '".$var."'";
  $hasil = mysql_query($sqlselect);
  while($row = mysql_fetch_assoc($hasil)){
   $menu[] = $row;
  }
  if(is_array($menu)){
   $json['kamus']=$menu;
   echo json_encode($json);
  }
 }
  
<?-->

Jika sudah terpenuhi semua, maka tanpa menunggu aba-aba dari saya silahkan langsung jalankan aplikasinya. Oh ya, saya sendiri menjalankan proses debuging aplikasi ini langsung di real device, yang juga sudah terhubung langsung ke localhost, bagi yang masih bingung cara melakukan debugging dengan real device bisa menuju tautan ini, dan untuk menghubungkan real devic ke localhost/xampp yang ada di computer bisa menuju tautan ini. Oke…untuk sekarang saya anggap teman-temen sudah paham caranya ya, nah supaya aplikasinya bisa mengakses database di localhost, maka sesuaikan ip address pada variable “url” yang terdapat pada file MainActivity.java dan TambahActivity.java dengan ip address komputer teman-teman.  
Untuk teman-teman yang menjalankan aplikasi ini di emulator, silahkan ubah ip address pada variable “url” menjadi : “10.0.2.2”, ini adalah alamat untuk mengakses database yang ada di localhost dengan menggunakan emulator android.
Semoga berhasil! dan semoga tutorial ini bisa bermanfaat bagi teman-teman semuanya, dan jika masih ada yang bingung silahkan untuk berkomentar dan mengunduh file project nya. Terimakasih…

Download Project Kamus Android

Related Posts:

0 comments:

Post a Comment