Today we are going to talk about another commonly used android process called upload data to a database. In this tutorial, i'm going to add some data to a php database using http "post method".This system can be used in registering related tasks in your android application.
You need a Hostinger account or you can also use your local wamp or xampp server. I am using hostinger for the demonstration purpose because it is absolutely free. You can also go to hostinger and signup for a free hosting account.
Signup for hostinger
- Order a free hosting account (mine is dinethips.esy.es) with a free subdomain
- Open your hosting account
- From the left menu click on databases
- Create a database
After creating you will see your database below
Copy the details it would be used for connecting our php script to database
Now create a table named person
In my table I am having three columns. One is id (auto increment, primary key) and the other ones are name and address.
We will insert name or address with our android app
Creating PHP Script to Insert Values into Database
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?php define('HOST','mysql.hostinger.in'); define('USER','u813815354_user'); define('PASS','bhaq2010'); define('DB','u813815354_db'); $con = mysqli_connect(HOST,USER,PASS,DB); $name = $_POST['name']; $address = $_POST['address']; $sql = "insert into Persons (name,address) values ('$name','$address')"; if(mysqli_query($con,$sql)){ echo 'success'; } else{ echo 'failure'; } mysqli_close($con); ?> |
Now insert these values to the database
Save it as insert-db.php and upload to the public folder of your hosting account.
Now find the actuall url for this php script.
In my case the url is http://dinethips.esy.es/insert-db.php
Creating Android Application – Android PHP Tutorial
Create a New Android App (I am using android studio)
Designing Interface
Create two TextView (for name and address label) and two EditText (for name and address input)
Create a button so your layout will look like
You can use the following xml code for creating the above 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 | <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:orientation="vertical" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Name" android:id="@+id/textView" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/editTextName" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Address" android:id="@+id/textView2" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/editTextAddress" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Insert" android:onClick="insert" android:id="@+id/button" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textViewResult" /> </LinearLayout> |
Come to MainActivity.java and define objects for EditText
The complete final code for your MainActivity.java is
package net.simplifiedcoding.insertintomysql; import android.os.AsyncTask; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; 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.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; public class MainActivity extends ActionBarActivity { private EditText editTextName; private EditText editTextAdd; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editTextName = (EditText) findViewById(R.id.editTextName); editTextAdd = (EditText) findViewById(R.id.editTextAddress); } public void insert(View view){ String name = editTextName.getText().toString(); String add = editTextAdd.getText().toString(); insertToDatabase(name,add); } private void insertToDatabase(String name, String add){ class SendPostReqAsyncTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { String paramUsername = params[0]; String paramAddress = params[1]; String name = editTextName.getText().toString(); String add = editTextAdd.getText().toString(); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("name", name)); nameValuePairs.add(new BasicNameValuePair("address", add)); try { HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost( "http://simplifiedcoding.16mb.com/insert-db.php"); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); } catch (ClientProtocolException e) { } catch (IOException e) { } return "success"; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show(); TextView textViewResult = (TextView) findViewById(R.id.textViewResult); textViewResult.setText("Inserted"); } } SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask(); sendPostReqAsyncTask.execute(name, add); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
Now finally open the Manifest.xml and add Internet Permission to your application
<uses-permission android:name="android.permission.INTERNET"/>
Hope you got a clear idea about the process. Leave a comment below if there are anything to know.
source | simplified coding
0 Comments