ANDROID TUTORIAL CREATING CRUD WITH JASON AND MYSQL DATABASE
Welcome to. My previous post aboutThe most effective wayto speed up the latest IDMdownload, the nextarticle this time is a tutorialCreating Android CRUD AppswithJSONandMySQL. This app is made withEclipse SoftwareversionLunaand for the DataBase server useXamppplease those who don't have the software can browse on google.
Today is a presentation assignmentNetwork Programming Course, the reason is already tired of creating programsCRUD (Create, Update, Delete, Read)simple discourseClothing sales. However, because my group didn't present it in front of the class because there were certain arguments, rather than my useless project, I thought of just sharing it on the blog, maybe some people who have experienced the same task or are just looking forreference. (true story)
Android questions:
1. MakeAndroid Web Services Applicationcapable of processingCRUD( Add, Edit, Delete, Delete ) onMySQL Databasesby wearingJSON parsingorXML(I use JSON)
Provision :
1.DatabasesI useXAMPP 2.Web ServicealsoXAMPP 3.Android Clienti wearMy Android phoneto carry out the application
Material :
1. SoftwareLuna version Ecipseto create an Application 2. Web Server and DataBase useXAMPP 3.Android Phoneas Client
Tutorials:
1. CreateMySQL Databaseby the namefashionand tabledb_clothingwith the contents of the fieldid, brand, type, sizeandpricedata typevarcharexcept id data typei integer and primary
2. Create a PHP file that is used to replace the fileMySQL Databaseaccording to the client's request, please enter the folderC:xampphtdocsfashionand create a fileserver.phpin the file containsadd, edit, delete scripts, view data as usual
Mysql Connection Error :
" . mysql_error()); mysql_select_db($database) or die("
Database Connection Error:
" .
mysql_error()); @$operation = $_GET'operation'; switch ($operation) case "view": $query_show_clothes = mysql_query("SELECT * FROM db_clothes")
or die(mysql_error()); $data_array = array(); while ($data = mysql_fetch_assoc($query_show_clothes)) $data_array = $data; echo json_encode($data_array); breaks; case "insert": /* Source code for Insert data */ @$brand = $_GET'brand'; @$type = $_GET'type'; @$size = $_GET'size'; @$price = $_GET'price'; $query_insert_data = mysql_query("INSERT INTO db_clothing
type='$type' , size='$size',price='$price' WHERE id='$id'"); if ($query_update_clothing) echo "Data Update Successful"; else echo mysql_error(); break; case "delete": /* Source code for Delete Biodata */ @$id = $_GET'id'; $query_delete_clothing = mysql_query("DELETE FROM db_clothing WHERE
id='$id'"); if ($query_delete_pakaian) echo "Delete Data Berhasil"; else echo mysql_error(); break; default: break; ?>
3. Open SoftwareEclipsecreate a new project with the namefashion, then in chaptersrcmake 3 classes isMainActivity.java , Connections.Java , Clothing.javaand in theres - layoutthere is a performance file with the formatxml
4. Previously openAndroidManifest.xml(the file is below itself)
then add android:name="android.permission.INTERNET"/>
In the layout I created the TableLayout was onVerticalScrollViewin the ScrollView, this works so that data that has a width of more than the screen size automaticallyscrollso that all data can be seen.
6. The following is thecontents of the script in
the Connection.java packagecom.examplore.deathnote; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; public class Connection public String call(String url) int BUFFER_SIZE = 2000; InputStream in = null; try in = OpenHttpConnection(url); catch(IOException e) e.printStackTrace(); returns ""; InputStreamReader isr = new InputStreamReader(in); int charRead; String str = ""; char inputBuffer = new charBUFFER_SIZE; try while ((charRead = isr.read(inputBuffer)) >0) String readString = String.copyValueOf(inputBuffer, 0, charRead); str += readString; inputBuffer = new charBUFFER_SIZE; in.close(); catch(IOException e) // Handle Exception e.printStackTrace(); returns ""; return str; private InputStream OpenHttpConnection(String url) throws IOException InputStream in = null; int response = -1; URL url1 = new URL(url); URLConnection conn = url1.openConnection(); if (!(conn instanceof HttpURLConnection)) throw new IOException("Not An Http Connection"); try HttpURLConnection httpconn = (HttpURLConnection) conn; httpconn.setAllowUserInteraction(false); httpconn.setInstanceFollowRedirects(true); httpconn.setRequestMethod("GET"); httpconn.connect(); response = httpconn.getResponseCode(); if (response == HttpURLConnection.HTTP_OK) in = httpconn.getInputStream(); catch(Exception e) throw new IOException("Error connecting2"); return in;
7. The following is the contents of the script onclothes.javafor the IP adjust tonetwork IPwhich is obtained for example if the computer IP192.168.43.94then also fill it in the IP project192.168.43.94
8. The following is the contents of the script onMainActivity.java package
the Connection.java packagecom.examplore.deathnote; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.examplore.deathnote.MainActivity; import com.examplore.deathnote.Clothes; import com.examplore.deathnote.R; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.graphics.Color; import android.os.Bundle; import android.os.StrictMode; import android.support.v4.view.ViewPager.LayoutParams; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity implements OnClickListener Outfit = new Outfit(); TableLayout tableClothes; Button buttonAddClothing; ArrayList ArrayListbuttonDelete = new ArrayList(); JSONArray arrayClothes; @Override protected void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (android.os.Build.VERSION.SDK_INT >9) StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder() .permitAll().build(); StrictMode.setThreadPolicy(policy); //variable introduction tableClothes = (TableLayout) findViewById(R.id.tableClothes); buttonAddClothing = (Button) findViewById(R.id.buttonAddClothing); buttonAddClothing.setOnClickListener(this); TableRowTable row = new TableRow(this); rowTable.setBackgroundColor(Color.CYAN); TextView viewHeaderId = new TextView(this); TextView viewHeaderBrand = new TextView(this); TextView viewHeaderType = new TextView(this); TextView viewHeaderSize = new TextView(this); TextView viewHeaderPrice = new TextView(this); TextView viewHeaderAction = new TextView(this); viewHeaderId.setText("ID"); viewHeaderBrand.setText("Brand"); viewHeaderType.setText("Type"); viewHeaderSize.setText("Size"); viewHeaderPrice.setText("Price"); viewHeaderAction.setText("Action"); viewHeaderId.setPadding(5, 1, 5, 1); viewHeaderBrand.setPadding(5, 1, 5, 1); viewHeaderType.setPadding(5, 1, 5, 1); viewHeaderSize.setPadding(5, 1, 5, 1); viewHeaderPrice.setPadding(5, 1, 5, 1); viewHeaderAction.setPadding(5, 1, 5, 1); rowTable.addView(viewHeaderId); rowTable.addView(viewHeaderBrand); rowTable.addView(viewHeaderType); rowTable.addView(viewHeaderSize); rowTable.addView(viewHeaderPrice); rowTable.addView(viewHeaderAction); tableClothes.addView(Table rows, new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); try arrayClothes = new JSONArray(fashion.displayClothes()); for(int i = 0; i< arrayPakaian.length(); i++) JSONObject jsonChildNode = arrayClothes.getJSONObject(i); String brand = jsonChildNode.optString("brand"); String type = jsonChildNode.optString("type"); String size = jsonChildNode.optString("size"); String price = jsonChildNode.optString("price"); String id = jsonChildNode.optString("id"); System.out.println("Brand :" + brand); System.out.println("Type :" + type); System.out.println("Size :" + size); System.out.println("Price:" + price); System.out.println("ID :" + id); rowTable = new TableRow(this); if (i % 2 == 0) rowTable.setBackgroundColor(Color.LTGRAY); TextView viewId = new TextView(this); viewId.setText(id); viewId.setPadding(5, 1, 5, 1); rowTable.addView(viewId); TextView viewBrand = new TextView(this); viewBrand.setText(brand); viewBrand.setPadding(5, 1, 5, 1); rowTable.addView(viewBrand); TextView viewType = new TextView(this); viewType.setText(type); viewType.setPadding(5, 1, 5, 1); rowTable.addView(viewType); TextView viewSize = new TextView(this); viewSize.setText(size); viewSize.setPadding(5, 1, 5, 1); rowTable.addView(viewSize); TextView viewPrice = new TextView(this); viewPrice.setText(price); viewPrice.setPadding(5, 1, 5, 1); rowTable.addView(viewPrice); buttonEdit.add(i, new Button(this)); buttonEdit.get(i).setId(Integer.parseInt(id)); buttonEdit.get(i).setTag("Edit"); buttonEdit.get(i).setText("Edit"); buttonEdit.get(i).setOnClickListener(this); rowTable.addView(buttonEdit.get(i)); buttonDelete.add(i, new Button(this)); buttonDelete.get(i).setId(Integer.parseInt(id)); buttonDelete.get(i).setTag("Delete"); buttonDelete.get(i).setText("Delete"); buttonDelete.get(i).setOnClickListener(this); rowTable.addView(buttonDelete.get(i)); tableClothes.addView(Table rows, new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); catch(JSONException e) e.printStackTrace(); public void onClick(View view) if (view.getId() == R.id.buttonAddClothing) // Toast.makeText(MainActivity.this, "Add Data Button", // Toast.LENGTH_SHORT).show(); addClothing(); else /* * Checking the data array, to match the index * each button */ for(int i = 0; i< buttonEdit.size(); i++) /* if clicked is the edit button */ if (view.getId() == buttonEdit.get(i).getId() && view.getTag().toString().trim().equals("Edit")) // Toast.makeText(MainActivity.this, "Edit : " + // buttonEdit.get(i).getId(), Toast.LENGTH_SHORT).show(); int id = buttonEdit.get(i).getId(); getDataByID(id); /* if you click the delete button */ else if (view.getId() == buttonDelete.get(i).getId() && view.getTag().toString().trim().equals("Delete")) // Toast.makeText(MainActivity.this, "Delete : " + // buttonDelete.get(i).getId(), Toast.LENGTH_SHORT).show(); int id = buttonDelete.get(i).getId(); deleteClothes(id); public void deleteClothes(int id) clothes.deleteClothing(id); /* restart activity */ finish(); startActivity(getIntent()); public void getDataByID(int id) String brandEdit = null, typeEdit = null, sizeEdit = null, priceEdit = null; JSONArray arrayPersonal; try arrayPersonal = new JSONArray(clothes.getClothesById(id)); for(int i = 0; i< arrayPersonal.length(); i++) JSONObject jsonChildNode = arrayPersonal.getJSONObject(i); brandEdit = jsonChildNode.optString("brand"); typeEdit = jsonChildNode.optString("type"); sizeEdit = jsonChildNode.optString("size"); priceEdit = jsonChildNode.optString("price"); catch(JSONException e) e.printStackTrace(); LinearLayout layoutInput = new LinearLayout(this); layoutInput.setOrientation(LinearLayout.VERTICAL); // create hidden id in alertbuilder conclusion TextView viewId = new TextView(this); viewId.setText(String.valueOf(id)); viewId.setTextColor(Color.TRANSPARENT); layoutInput.addView(viewId); end EditText editBrand = new EditText(this); editBrand.setText(brandEdit); layoutInput.addView(editBrand); end EditText editType = new EditText(this); editType.setText(TypeEdit); layoutInput.addView(editType); conclude EditText editSize = new EditText(this); editSize.setText(sizeEdit); layoutInput.addView(editSize); final EditText editPrice = new EditText(this); editPrice.setText(PriceEdit); layoutInput.addView(editPrice); AlertDialog.Builder builderEditClothes = new AlertDialog.Builder(this); builderEditClothing.setIcon(R.drawable.batagrams); builderEditClothing.setTitle("Update Outfit"); builderEditClothes.setView(layoutInput); builderEditClothes.setPositiveButton("Update", new DialogInterface.OnClickListener() @Override public void onClick(DialogInterface chat, int which) String brand = editBrand.getText().toString(); String type = editType.getText().toString(); String size = editSize.getText().toString(); String price = editPrice.getText().toString(); System.out.println("Brand : " + brand + " Type : " + type+ " Size : " + size + " Price : " + price); Report string = outfit.updateClothing(viewId.getText().toString(), editBrand.getText().toString(), editType.getText().toString(),editSize.getText().toString(), editPrice.getText().toString()); Toast.makeText(MainActivity.this, report, Toast.LENGTH_SHORT).show(); /* restart activity */ finish(); startActivity(getIntent()); ); builderEditClothes.setNegativeButton("Cancel", new DialogInterface.OnClickListener() @Override public void onClick(DialogInterface chat, int which) dialog.cancel(); ); builderEditClothes.show(); public void addClothing() /* layout will be displayed in AlertDialog */ LinearLayout layoutInput = new LinearLayout(this); layoutInput.setOrientation(LinearLayout.VERTICAL); end EditText editBrand = new EditText(this); editBrand.setHint("Brand"); layoutInput.addView(editBrand); final EditText editType = new EditText(this); editType.setHint("Type"); layoutInput.addView(editType); finished EditText editSize = new EditText(this); editSize.setHint("Size"); layoutInput.addView(editSize); finished EditText editPrice = new EditText(this); editPrice.setHint("Price"); layoutInput.addView(editPrice); AlertDialog.Builder builderInsertClothes = new AlertDialog.Builder(this); builderInsertClothes.setIcon(R.drawable.batagrams); builderInsertClothes.setTitle("Insert Clothes"); builderInsertClothes.setView(layoutInput); builderInsertClothes.setPositiveButton("Insert", new DialogInterface.OnClickListener() @Override public void onClick(DialogInterface dialog, int which) String brand = editBrand.getText().toString(); String type = editType.getText().toString(); String size = editSize.getText().toString(); String price = editPrice.getText().toString(); System.out.println("Brand : " + brand + " Type : " + type+ " Size : " + size + " Price : " + price); Report string = clothing.inserClothing(brand, type, size, price); Toast.makeText(MainActivity.this, report, Toast.LENGTH_SHORT).show(); /* restart activity */ finish(); startActivity(getIntent()); ); builderInsertClothes.setNegativeButton("Cancel", new DialogInterface.OnClickListener() @Override public void onClick(DialogInterface dialog, int which) dialog.cancel(); ); builderInsertClothes.show();
Data received fromBiodata.javastill in the form ofStringbut has structureJSON Encode. By entering the string into the JSONArray, the data will automatically be stored in the array. But keep in mind, that the data we receive from MySQL is data in the form of rows and columns
9. Done, please Copas later if typed, afraid of errors because it's too long hehe
Testing:
1. Turn onWifi / TheTeringIf there's no point, you have to have Wifi because later on, the laptop will be the place to store the database and Android as theClient must be connected with the same IP(eg laptop and android phone connected to campus wifi). For example laptop IP192.168.43.94put in projectclothes.java
2. Turn on Xampp Apache and MySQL just enough
3. Connectdata cableon an Android phone (provided that the driver has been installed) running a project to an Android phone, for exampleACER Z205
4. Then see the picture below
Download Project<< database sama koneksi buat sendiri mirip file diatas
That's the post aboutTutorial on creating Android CRUD Apps with JSONand MySQL to be useful, This is not a guide for newbies who are new to Android before learning about JSON Arrays, ordinary Android CRUD, XML etc. This is just my coursework that hasn't been presented yet. May be useful.