This tutorial is to insert a new record from Android apps, to be stored at onine database.
Full code for the backend available at bit.ly/gitjson
The Android Studio project full code also available at GITHUB.
The previous tutorials also available at
+ Login facilities http://bit.ly/loginkerul
+ Insert a new record http://bit.ly/insertkerul
+ Listing & Search http://bit.ly/jsonsearch
+ Complete Android tutorials is available at http://fstm.kuis.edu.my/blog/android/
BACKEND
createuser.php – The backend code to accept the record/data. This PHP script will fetch data from Android form, and send to the database thru SQL.
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 |
<?php include "formcreateuser.php"; // code @GITHUB // bit.ly/gitjson // insert.php include "connect.php"; //$id=$_POST['id']; if (isset($_POST['uname']) && $_POST['uname']!=null && $_POST['pwd']!=null){ $uname=$_POST['uname']; $pwd=$_POST['pwd']; $userlevel=$_POST['userlevel']; $fullname=$_POST['fullname']; $email=$_POST['email']; $rs = mysqli_query($db, "INSERT INTO a_training_user (uname, pwd, userlevel, fullname, email) VALUES ('$uname', md5('$pwd'), '$userlevel','$fullname','$email')"); //echo (mysql_error()); // check for empty result if ($rs==true) { //insert successfull echo "success"; }//end match found else{//no match found //send status fail echo "error"; } }//end null else{ echo "error"; } ?> |
FRONT-END (MOBILE APP)
In Android Studio, add a new activity screen to display the insert new record form. As in the picture below, this screen Activity will provide input form for the user to fill in username, password, userlevel, fullname & email.
The XML for the UI layout.
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 |
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".CreateUser"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="40dp"> <ImageView android:id="@+id/imageView2" android:layout_width="match_parent" android:layout_height="wrap_content" app:srcCompat="@drawable/create_user" /> <EditText android:id="@+id/txtusername" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="Username*" android:inputType="text" /> <EditText android:id="@+id/txtpassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="Password*" android:inputType="textPassword" /> <EditText android:id="@+id/txtpassword2" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="Repeat password*" android:inputType="textPassword" /> <Switch android:id="@+id/txtadmin" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Admin?" /> <EditText android:id="@+id/txtfullname" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="Fullname*" android:inputType="textPersonName" /> <EditText android:id="@+id/txtemail" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="Email*" android:inputType="textEmailAddress" /> <Button android:id="@+id/bntcreateuser" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Create User" /> </LinearLayout> </android.support.constraint.ConstraintLayout> |
CreateUser.java – The complete code
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 239 240 241 242 243 244 |
package com.khirulnizam.json; import android.app.ProgressDialog; import android.content.DialogInterface; import android.os.AsyncTask; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.Switch; import android.widget.Toast; import org.json.JSONObject; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.Iterator; import javax.net.ssl.HttpsURLConnection; public class CreateUser extends AppCompatActivity implements View.OnClickListener{ String uname, pwd,pwd2, userlevel="regular", fullname, email; EditText txtuname, txtpwd,txtpwd2,txtfullname, txtemail; Button btncreateuser; Switch txtadmin; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_create_user); //UI declarations txtuname = (EditText)findViewById(R.id.txtusername); txtpwd= (EditText)findViewById(R.id.txtpassword); txtpwd2= (EditText)findViewById(R.id.txtpassword2); txtadmin=(Switch)findViewById(R.id.txtadmin); //userlevel txtadmin.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { userlevel = "admin"; } else { userlevel = "regular"; } } }); txtfullname= (EditText)findViewById(R.id.txtfullname); txtemail=(EditText)findViewById(R.id.txtemail); btncreateuser=(Button)findViewById(R.id.bntcreateuser); btncreateuser.setOnClickListener(this); }//end onCreate //variables to hold newuser data public void onClick(View v){ if (v.getId()==R.id.bntcreateuser) { uname = txtuname.getText().toString(); //check password repeat same pwd = txtpwd.getText().toString(); pwd2=txtpwd2.getText().toString(); if (pwd.equals(pwd2)){ pwd=pwd2; }//check password repeat same value else{ pwd=""; } //userlevel = txtadmin.getText().toString(); fullname = txtfullname.getText().toString(); email = txtemail.getText().toString(); //check all fields provided with data if(!uname.equals("") && !pwd.equals("") && !email.equals("") && !fullname.equals("")){ //call the AsyncTask if username,password,email provided data new SaveNewRecord().execute(); } }//end btnsave }//onClick //****************************** Save record process ASYNCTASK, starts here public class SaveNewRecord extends AsyncTask<String, Void, String> { //the progressdialog ProgressDialog progress = new ProgressDialog(CreateUser.this); protected void onPreExecute(){ //set message of the dialog progress.setMessage("Saving record to online database..."); //show dialog progress.show(); super.onPreExecute(); } protected String doInBackground(String... arg0) { try { // here is your URL path, change the IP number to // point to your own server URL url = new URL("http://khirulnizam.com/training/createuser.php"); JSONObject postDataParams = new JSONObject(); //add name pair values to the connection postDataParams.put("uname", uname); postDataParams.put("pwd", pwd); postDataParams.put("userlevel", userlevel); postDataParams.put("fullname", fullname); postDataParams.put("email", email); Log.e("params",postDataParams.toString()); Log.e("URL",url.toString()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(15000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("POST");//method=post conn.setDoInput(true); conn.setDoOutput(true); conn.connect();//execute the connection 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(); Log.e("responseCode", "responseCode "+responseCode); if (responseCode == HttpsURLConnection.HTTP_OK) { //code 200 connection OK //code 500 server not responding //code 404 file not found //this part is to capture the server response BufferedReader in=new BufferedReader(new InputStreamReader( conn.getInputStream())); //Log.e("response",conn.getInputStream().toString()); StringBuffer sb = new StringBuffer(""); String line=""; do{ sb.append(line); Log.e("MSG sb",sb.toString()); }while ((line = in.readLine()) != null) ; in.close(); Log.e("response",conn.getInputStream().toString()); Log.e("textmessage",sb.toString()); return sb.toString();//server response message } else { return new String("false : "+responseCode); } } catch(Exception e){ //error on connection return new String("Exception: " + e.getMessage()); } } @Override protected void onPostExecute(String result) { //Toast.makeText(getApplicationContext(), result, //Toast.LENGTH_LONG).show(); //return result; //call method to handle after verification if(progress != null && progress.isShowing()){ progress.dismiss(); } saveVerification(result);//call saveVerification to display dialog } }//end public String getPostDataString(JSONObject params) throws Exception { StringBuilder result = new StringBuilder(); boolean first = true; Iterator<String> itr = params.keys(); while(itr.hasNext()){ String key= itr.next(); Object value = params.get(key); if (first) first = false; else result.append("&"); result.append(URLEncoder.encode(key, "UTF-8")); result.append("="); result.append(URLEncoder.encode(value.toString(), "UTF-8")); } //Log.i("result",result.toString()); return result.toString(); }//end sendPostData public void saveVerification(String svrmsg){ String savemsg=""; //if new record successfully saved Toast.makeText(this, "svrmsg:"+svrmsg, Toast.LENGTH_LONG).show(); if (svrmsg.equals("success")){ savemsg="New record succesfully saved."; } else {//save attempt failed savemsg="Fail to save new record!"; } //**********common dialog box AlertDialog.Builder builder1 = new AlertDialog.Builder(this); builder1.setTitle("Saving Record"); builder1.setMessage(savemsg); builder1.setCancelable(false); builder1.setPositiveButton("ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }).create().show(); } //****************************** Save record ASYNCTASK, ends here } |
HttpHandler.java class – this is a helper class to handle data communication to the online server.
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 |
package com.khirulnizam.json; //HttpHandler.java import android.util.Log; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; public class HttpHandler { private static final String TAG = HttpHandler.class.getSimpleName(); public HttpHandler() { } public String makeServiceCall(String reqUrl) { String response = null; try { URL url = new URL(reqUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET");//method type // read the response InputStream in = new BufferedInputStream(conn.getInputStream()); response = convertStreamToString(in); } catch (MalformedURLException e) { Log.e(TAG, "MalformedURLException: " + e.getMessage()); } catch (ProtocolException e) { Log.e(TAG, "ProtocolException: " + e.getMessage()); } catch (IOException e) { Log.e(TAG, "IOException: " + e.getMessage()); } catch (Exception e) { Log.e(TAG, "Exception: " + e.getMessage()); } return response; } private String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line; try { while ((line = reader.readLine()) != null) { sb.append(line).append('\n'); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } } |
Trainer:
KHIRULNIZAM ABD RAHMAN, Department of Computer Science, FSTM KUIS.
He is a certified HRDF Trainer – specializing in client-side and back-end web based system development since 2000. His main programming language ingterests are Java, Android, PHP, Laravel JSON, MySQL, and currently Flutter.
Among short-courses he conducted are;
His personal blog is at KERUL.net . You could email him at khirulnizam@gmail.com , or Whatsapp: http://wasap.my/60129034614