Skip to main content

Insert Record JSON Android in localhost environment

Synopsis

  • This tutorial is the continuation of Login JSON Android using Login Activity
  • STEP 1: Preparing the online database facilities in localhost.
  • STEP 2: Preparing the PHP script to insert a new record.
  • STEP 3: Coding of The Android client

insert-record-screen-in-actionprogress-dialog-saving-android-jsoninsert-record-screen-confirmation

 

STEP 1: Preparing the online database facilities in localhost.

Our Localhost environment is on Xampp as usual.

Importing the database to the online database. Download the full code below and you will find the SQL-dump file. Import the file and it will create a database named training.

training-database-sql

STEP 2: PHP script

Preparing the PHP script to insert a new record. We have lots of files, insertrecord.php are the one in use for this tutorial.

<?php
// include connect class
require_once __DIR__ . '/connect.php';

// connecting to db
$db = new DB_CONNECT();

//capture all values from client
$id=$_POST['id'];
$trainingname=$_POST['trainingname'];
$website=$_POST['website'];
$contact=$_POST['contact'];
$trainingdesc=$_POST['trainingdesc'];

//sql query
$q = mysql_query("INSERT INTO a_training VALUES ('$id','$trainingname', '$website','$contact','$trainingdesc')");

//echo (mysql_error());

if ($q==true) {
    // match found
	//send success to client if save went thru
		echo "success";

	}//end match found

	else{//no match found
		//send status fail
		echo "fail";

}

?>

 

STEP 3: Coding of The Android client

As in the screenshot, the layout is in the layout xml file. This activity is created from the Basic Activity. Kindly download the project folder for the complete code.

insert-record-screen

 

HttpHandler.java is the helper class to manage the online connection. Copy and paste to the package folder.

HttpHandler-java-file

The InsertRecord.java is the file to handle the GUI and the AsyncTask (multi-threading) code. We are just providing the segment code where the multi-threading of storing the new record in the online database, kindly download the project folder for the complete code.

You may call this class from onClick button by

    public void onClick(View v){
        if (v.getId()==R.id.fab) {
            id = txtid.getText().toString();
            trainingname = txttrainingname.getText().toString();
            contact = txtcontact.getText().toString();
            website = txtwebsite.getText().toString();
            trainingdesc = txttrainingdesc.getText().toString();

            //call the AsyncTask
            new SaveNewRecord().execute();
        }//end btnsave
    }//onClick

 

The complete SaveNewRecord asynctask

//****************************** Save record process ASYNCTASK, starts here
    public class SaveNewRecord extends AsyncTask<String, Void, String> {
        //the progressdialog
        ProgressDialog progress = new ProgressDialog(InsertRecord.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://192.168.43.252/training/insertrecord.php");

                JSONObject postDataParams = new JSONObject();
                //add name pair values to the connection
                postDataParams.put("id", id);
                postDataParams.put("trainingname", trainingname);
                postDataParams.put("contact", contact);
                postDataParams.put("website", website);
                postDataParams.put("trainingdesc", trainingdesc);

                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

 

 

Download-blueDOWNLOAD THE COMPLETE SOURCE CODE HERE
https://drive.google.com/file/d/0B34ZxOOoeSDdakYwbHMxclZIdjQ/view?usp=sharing

Need face-to-face lesson?, we also provide Android Studio training, 0129034614
http://bit.ly/androidjsk
android-kokuis-banner2

Disclaimer: Intermediate to advanced level. This tutorial works on Android Studio 2.3. Should you have any difficulties, leave your comment in the comment section.
SHARE to your friends...

Comments

Popular posts from this blog

Several English proverbs and the Malay pair

Or you could download here for the Malay proverbs app – https://play.google.com/store/apps/details?id=net.kerul.peribahasa English proverbs and the Malay pair Corpus Reference: Amir Muslim, 2009. Peribahasa dan ungkapan Inggeris-Melayu. DBP, Kuala Lumpur http://books.google.com.my/books/about/Peribahasa_dan_ungkapan_Inggeris_Melayu.html?id=bgwwQwAACAAJ CTRL+F to search Proverbs in English Definition in English Similar Malay Proverbs Definition in Malay 1 Where there is a country, there are people. A country must have people. Ada air adalah ikan. Ada negeri adalah rakyatnya. 2 Dry bread at home is better than roast meat home's the best hujan emas di negeri orang,hujan batu di negeri sendiri Betapa baik pun tempat orang, baik lagi tempat sendiri. 3 There's no accounting for tastes We can't assume that every people have a same feel Kepala sama hitam hati lain-lain. Dalam kehidupan ini, setiap insan berbeza cara, kesukaan, perangai, tabia

Login JSON Android using Login Activity

I’ve been trying to release this tutorial quite a while. At last after a long hard effort. Since HttpClient is not supported any more in Android SDK 23, I have to resort to org.json.JSONObject and java.net.HttpURLConnection library to do online database with JSON. The objective of this tutorial is to log-in from a mobile client with the username and password stored in an online database facility. STEP 1: Create a new Android project, this time choose the LoginActivity .

Contact Us at blog.kerul.net

Powered by EMF HTML Contact Form

Bootstrap Template for PHP database system - MyCompanyHR

HTML without framework is dull. Doing hard-coded CSS and JS are quite difficult with no promising result on cross platform compatibility. So I decided to explore BootStrap as they said it is the most popular web framework. What is BootStrap? - Bootstrap is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first web sites. (  http://www.w3schools.com/bootstrap/   ) Available here -  http://getbootstrap.com/ Why you need Flat-UI? Seems like a beautiful theme to make my site look professional. Anyway you could get variety of BootStrap theme out there, feel free to select here  http://bootstraphero.com/the-big-badass-list-of-twitter-bootstrap-resources/ Flat-UI is from DesignModo -   http://designmodo.com/flat/ Web Programming MyCompanyHR – PHP & MySQL mini project (with Boostrap HTML framework) Template 1: Template for the Lab Exercise. This is a project sample of a staff record management system. It has the PHP structured co

Pick a file using Intent.ACTION_GET_CONTENT

This tutorial is tested on Honeycomb 3.0 environment. In order to be used it in the lower level of Android API, I believe you could just change the target in the Android project. Screenshots Pick an image file using Intent.ACTION_GET_CONTENT The intention of this project is to choose an image file available in the device storage, and simply display it in an ImageView. The benefit of using Intent.ACTION_GET_CONTENT is you don’t have to develop open dialog box which is not available in the Android library. ACTION_GET_CONTENT with MIME type */* and category CATEGORY_OPENABLE -- Display all pickers for data that can be opened with ContentResolver.openInputStream() , allowing the user to pick one of them and then some data inside of it and returning the resulting URI to the caller. This can be used, for example, image chooser (as shown in this article).