Breaking News

How to insert data into MySql Database from Android Application. Final Step (4 & 5)

This process can be used if you want to develop an App which is not Stand Alone  (access centralized database).
In this post we will understand how to move data from Android App to MySql Database. We are going to use an Android Studio with the help of XAMPP Server which will help to run Server Side Script like Php.
Again, we need a little bit knowledge on how to work with Php and MySql, but don't worry if you don't have that knowledge, this post will give you a light on it.
What to do is installation of Android Studio, XAMPP Server and Text Editor (Notepad++, Sublime Text, Bluefish, etc) on your Machine, after the Installation, follow the Main 5 steps, which will consists a lot of small steps on each.

  1. Create MySql Database
  2. Write Php code to interact with MySql Database.
  3. Develop Simple App to capture Data from the User.
  4. Connect Android App to MySQL Database.
  5. Insert Data to MySQL Database
Note: I'm using Windows OS, Notepad++ and XAMPP Server.

Step 3 & 4: Connect Android App to MySQL Database & Insert data to it.

After developing your Database and Interface Design from previous post, now its time to work on other side of Java where we will do those functionalities for sending our data to MySQL Database.
  • Open your Android Studio with the App that we have designed.
  • On the top left corner of  Android Studio (Apart from menu) there is app Package click it (maximize) then click java (maximize) then click com.sourceofconcept.soc (Company Domain and App name) and finally you'll see all files of java that is concerned with your App.
  • Now double click it to open the code ground.

Now its time to code.
First of all we have to capture the values (information) that will be entered through the App that we have design before pushing them to the database. When we have them we can do anything that we need. So type the following codes to get them from the front end to the back end.

On MainActivity.java paste the following codes.

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    Button btnSend;
    EditText Fname, Phone, Addr;
    String fullName, PhoneNo, Address;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Fname=(EditText)findViewById(R.id.txtName);
        Phone=(EditText)findViewById(R.id.txtPhone);
        Addr=(EditText)findViewById(R.id.txtAddress);
        btnSend=(Button)findViewById(R.id.btnSave);
        btnSend.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btnSave:
                fullName=Fname.getText().toString();
                PhoneNo=Phone.getText().toString();
                Address=Addr.getText().toString();
                SOC_DB soc_db = new SOC_DB(this);
                soc_db.execute(fullName, PhoneNo, Address);
                break;
        }
    }
}

The above code is used to capture the data that will be entered by user and send to another class which is called SOC_DB.java. This Class is responsible to receive the data and then to the php scrpt.

The general process is that, there is php scripts  called insert.php which is used to send the Data to the Database, but these data is coming from an Android App, so the connection between Android App and php script is performed by the SOC_DB.java, this is the Class which make the connection and take the data entered by user to php script.
So after typing the above codes, now create a new Java Class and Call it SOC_DB. Follow the following steps to create a Java Class.
  • On the Top Left Corner, Click on app then
  • Click on java then
  • Right click on the first file (mine is com.sourceofconcept.soc)
Then follow the instruction of the following picture.

 

When you finish to create a Class SOC_DB, now type the following codes in it.


import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import javax.net.ssl.HttpsURLConnection;
public class SOC_DB extends AsyncTask<String, Void, String> {
    Context context;
    SOC_DB (Context context){
        this.context = context;
    }
    @Override
    protected String doInBackground(String... params) {
        String path = "http://ip address/App/insert.php";
        String name, phone, addres;
        name = params[0];
        phone = params[1];
        addres = params[2];
        try {
            URL url = new URL(path);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream OS = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
            String data = URLEncoder.encode("name", "UTF-8") +"="+ URLEncoder.encode(name, "UTF-8") +"&"+
                    URLEncoder.encode("phone", "UTF-8") +"="+ URLEncoder.encode(phone, "UTF-8") +"&"+
                    URLEncoder.encode("address", "UTF-8") +"="+ URLEncoder.encode(addres, "UTF-8");
            bufferedWriter.write(data);
            bufferedWriter.flush();
            bufferedWriter.close();
            InputStream IS = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(IS, "iso-8859-1"));
            String result="";
            String line="";
            while ((line = bufferedReader.readLine()) != null){
                result+=line;
            }
            bufferedReader.close();
            IS.close();
            httpURLConnection.disconnect();
            return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    @Override
    protected void onPostExecute(String result) {
        Toast.makeText(context, result, Toast.LENGTH_LONG).show();
    }
}

Note: In this codes there is a word ip address. This means that you have to put the IP Address of your machine (Computer) if you are running this codes by using real device but if you are using a Virtual Device  (Emulator) you have to put 10.0.2.2 as your default IP Address.

After typing those codes now finalize by opening Manifest File Located on 
app →manifests→AndroidManifest.xml
And add an Internet Permission by typing the following code.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

Type it before an <application> tag. We add this permission because to run this application you have to switch on hotspot in your mobile device (If you are running in real device) and connect it with your Machine (Computer) by turning on Wi-fi. After these two device connected your are ready to run.
Don't forget to switch on Apache and MySQL Servers.

If you didn't get a concept or logic of it, just watch the following video.
For any query please put you comment and I will replay as soon as possible.

We are done...!!!

I hope now you have an understanding on what we have discussed in this final steps. Please feel free to ask any question if you didn't understand then I can reply as faster as I can.
Please comment and share with your friends. Don't miss the following article where we will continue to discuss different concepts and its Application in Android.

Thank you for reading and watching, be blessed....!!!

Video and demonstration of this discussion.

No comments