Tuesday, July 3, 2012

Connect MySQL Database from android

Retrieve Database from mysql and Diplaying in Dynamic Table using android




To download Full program click here




I  Installed WAMP server on my local machine for excuting PHP programs.

I have programmed  in windows 7.

If You need WAMP server, click here to download.

Before run this program ,start wampserver

programs --> wampserver --> start wampserver

see right side below of taskbar WAMPSERVER -server offline icon present.









This is the wampserver icon


 Left click icon --> start all services














main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="116dp"
        android:layout_height="wrap_content"
        android:text="Insert" />

    <Button
        android:id="@+id/button2"
        android:layout_width="114dp"
        android:layout_height="wrap_content"
        android:text="Retrieve" />

    <Button
        android:id="@+id/button3"
        android:layout_width="114dp"
        android:layout_height="wrap_content"
        android:text="Update" />

    <Button
        android:id="@+id/button4"
        android:layout_width="116dp"
        android:layout_height="wrap_content"
        android:text="Delete" />

</LinearLayout>







































insert.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/e1"
        android:numeric="integer"
     
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <requestFocus />
    </EditText>


    <EditText
        android:id="@+id/e2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="text" />

    <EditText
        android:id="@+id/e3"
        android:numeric="integer"
       
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
   

    <Button
        android:id="@+id/button1"
        android:layout_width="276dp"
        android:layout_height="wrap_content"
        android:text="Button" />

</LinearLayout>



































update.xml



 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >



    <EditText
        android:id="@+id/e1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:numeric="integer" >

        <requestFocus />
    </EditText>


    <Button
        android:id="@+id/button2"
        android:layout_width="78dp"
        android:layout_height="wrap_content"
        android:text="Button" />


    <EditText
        android:id="@+id/e2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="text" />

    <EditText
        android:id="@+id/e3"
        android:numeric="integer"
      
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
  

    <Button
        android:id="@+id/button1"
        android:layout_width="276dp"
        android:layout_height="wrap_content"
        android:text="Button" />

</LinearLayout>



































select.xml


 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
   
    <EditText
        android:id="@+id/e1"
        android:numeric="integer"

        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <requestFocus />
    </EditText>
   
   
    <Button
        android:id="@+id/button1"
        android:layout_width="276dp"
        android:layout_height="wrap_content"
        android:text="Button" />

   
    <EditText
        android:id="@+id/e2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <EditText
        android:id="@+id/e3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
   

</LinearLayout>





































delete.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/e1"
        android:numeric="integer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <requestFocus />
    </EditText>


  
    <Button
        android:id="@+id/button1"
        android:layout_width="276dp"
        android:layout_height="wrap_content"
        android:text="Button" />

</LinearLayout> 







































 DatabaseActivity.java




package selva.db; // Change your package name


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class DatabaseActivity extends Activity {
    /** Called when the activity is first created. */
      @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
           
            Button button = (Button) findViewById(R.id.button1);
           
           
            Button button1 = (Button) findViewById(R.id.button2);
           
           
            Button button2 = (Button) findViewById(R.id.button3);

           
            Button button3 = (Button) findViewById(R.id.button4);

           

            button.setOnClickListener(new View.OnClickListener()
            {
            public void onClick(View view) {
               
               
                 Intent i = new Intent(getBaseContext(),insert.class);
                startActivity(i);
           }
           });
           
           
           
           
            button1.setOnClickListener(new View.OnClickListener()
            {
            public void onClick(View view) {
               
               
                 Intent i = new Intent(getBaseContext(),select.class);
                startActivity(i);
           }
           });
           
           
           
           
            button2.setOnClickListener(new View.OnClickListener()
            {
            public void onClick(View view) {
               
               
                 Intent i = new Intent(getBaseContext(),update.class);
                startActivity(i);
           }
           });
           
           
            button3.setOnClickListener(new View.OnClickListener()
            {
            public void onClick(View view) {
               
               
                 Intent i = new Intent(getBaseContext(),delete.class);
                startActivity(i);
           }
           });
           

           
        }
}




insert.java


package selva.db;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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 org.json.JSONException;
import org.json.JSONObject;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class insert extends Activity
{
   
   
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

   
   
     public void onCreate(Bundle savedInstanceState)
   
     {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.insert);
            Button button = (Button) findViewById(R.id.button1);
            button.setOnClickListener(new View.OnClickListener()
            {
                   public void onClick(View view)
                     {
         
                           String result = null;
                           InputStream is = null;
                           EditText editText = (EditText)findViewById(R.id.e1);
                           String v1 = editText.getText().toString();
                           EditText editText1 = (EditText)findViewById(R.id.e2);
                           String v2 = editText1.getText().toString();
                           EditText editText2 = (EditText)findViewById(R.id.e3);
                           String v3 = editText2.getText().toString();
         ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

                           nameValuePairs.add(new BasicNameValuePair("f1",v1));
                           nameValuePairs.add(new BasicNameValuePair("f2",v2));
                           nameValuePairs.add(new BasicNameValuePair("f3",v3));

                           StrictMode.setThreadPolicy(policy);


                //http post
                try{
                        HttpClient httpclient = new DefaultHttpClient();
                        HttpPost httppost = new HttpPost("http://10.0.2.2/insert.php");
                        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                        HttpResponse response = httpclient.execute(httppost);
                        HttpEntity entity = response.getEntity();
                        is = entity.getContent();

                        Log.e("log_tag", "connection success ");
      Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
                   }
               
               
                catch(Exception e)
                {
                        Log.e("log_tag", "Error in http connection "+e.toString());
  Toast.makeText(getApplicationContext(), "Connection fail",                                        Toast.LENGTH_SHORT).show();

                }
                //convert response to string
                try{
                        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                        StringBuilder sb = new StringBuilder();
                        String line = null;
                        while ((line = reader.readLine()) != null)
                        {
                                sb.append(line + "\n");
                                   Intent i = new Intent(getBaseContext(),DatabaseActivity.class);
                                startActivity(i);
                        }
                        is.close();

                        result=sb.toString();
                }
                catch(Exception e)
                {
                       Log.e("log_tag", "Error converting result "+e.toString());
                   }

      
                try{
                   
                                JSONObject json_data = new JSONObject(result);

                                CharSequence w= (CharSequence) json_data.get("re");
                             
                                Toast.makeText(getApplicationContext(), w, Toast.LENGTH_SHORT).show();

                     
                     }
                catch(JSONException e)
                   {
                        Log.e("log_tag", "Error parsing data "+e.toString());
                        Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
                    }

               

           }
           });
           
           

     }
   

}







update.java


package selva.db;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.NumberFormat;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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 org.json.JSONException;
import org.json.JSONObject;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class update extends Activity
{
   
   
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
     public void onCreate(Bundle savedInstanceState)
     {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.update);
          
            StrictMode.setThreadPolicy(policy);
          
            Button buttonupadte = (Button) findViewById(R.id.button1);
          
            Button button1 = (Button) findViewById(R.id.button2);
            button1.setOnClickListener(new View.OnClickListener()
            {
            public void onClick(View view)
          
            {
                 String result = null;
                InputStream is = null;
                EditText editText = (EditText)findViewById(R.id.e1);
                String v1 = editText.getText().toString();
                     EditText editText1 = (EditText)findViewById(R.id.e2);
                EditText editText2 = (EditText)findViewById(R.id.e3);
          ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

                nameValuePairs.add(new BasicNameValuePair("f1",v1));

                      try
                     {
                        HttpClient httpclient = new DefaultHttpClient();
                        HttpPost httppost = new HttpPost("http://10.0.2.2/select.php");
                        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                        HttpResponse response = httpclient.execute(httppost);
                        HttpEntity entity = response.getEntity();
                        is = entity.getContent();

                        Log.e("log_tag", "connection success ");
                      }
                        
                        
                      catch(Exception e)
                      {
                        Log.e("log_tag", "Error in http connection "+e.toString());
                        Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();

                      }
                //convert response to string
                try{
                        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                        StringBuilder sb = new StringBuilder();
                        String line = null;
                        while ((line = reader.readLine()) != null)
                        {
                                sb.append(line + "\n");
                           
                        }
                        is.close();

                        result=sb.toString();
                    }
                catch(Exception e)
                    {
                       Log.e("log_tag", "Error converting result "+e.toString());
                    Toast.makeText(getApplicationContext(), " Input reading fail", Toast.LENGTH_SHORT).show();

                    }

                //parse json data
                try{
                  
                             JSONObject object = new JSONObject(result);
                        String ch=object.getString("re");
                        if(ch.equals("success"))
                        {
                         
                           JSONObject no = object.getJSONObject("0");
                           String w= no.getString("f2");
                          long e=no.getLong("f3");
                      
                          editText1.setText(w);
                          String myString = NumberFormat.getInstance().format(e);
                          editText2.setText(myString);

                          }
                        else
                          {
                         
                            Toast.makeText(getApplicationContext(), "Record is not available.. Enter valid number", Toast.LENGTH_SHORT).show();

                            }
                  
              
                }
                catch(JSONException e)
                {
                        Log.e("log_tag", "Error parsing data "+e.toString());
                        Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
                }

                   }
               });
          

          
            buttonupadte.setOnClickListener(new View.OnClickListener()
            {
            public void onClick(View view)
              {
              
                String result = null;
                InputStream is = null;
                EditText editText = (EditText)findViewById(R.id.e1);

                String v1 = editText.getText().toString();

                EditText editText1 = (EditText)findViewById(R.id.e2);

                String v2 = editText1.getText().toString();
                EditText editText2 = (EditText)findViewById(R.id.e3);

                String v3 = editText2.getText().toString();

                ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

                nameValuePairs.add(new BasicNameValuePair("f1",v1));
                nameValuePairs.add(new BasicNameValuePair("f2",v2));
                nameValuePairs.add(new BasicNameValuePair("f3",v3));

                //http post
                try{
                        HttpClient httpclient = new DefaultHttpClient();
                        HttpPost httppost = new HttpPost("http://10.0.2.2/update.php");
                        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                        HttpResponse response = httpclient.execute(httppost);
                        HttpEntity entity = response.getEntity();
                        is = entity.getContent();

                        Log.e("log_tag", "connection success ");
                        Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
                }
                catch(Exception e)
                {
                        Log.e("log_tag", "Error in http connection "+e.toString());
                        Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();

                }
                //convert response to string
                try
                {
                        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                        StringBuilder sb = new StringBuilder();
                        String line = null;
                        while ((line = reader.readLine()) != null)
                        {
                                sb.append(line + "\n");
                                //Toast.makeText(getApplicationContext(), "Record Inserted", Toast.LENGTH_SHORT).show();
                                Intent i = new Intent(getBaseContext(),DatabaseActivity.class);
                                startActivity(i);
                        }
                        is.close();

                        result=sb.toString();
                }
                catch(Exception e)
                {
                       Log.e("log_tag", "Error converting result "+e.toString());
                   // Toast.makeText(getApplicationContext(), " record passing fail", Toast.LENGTH_SHORT).show();

                }

          
              
                //parse json data
                try{
                  
                    JSONObject json_data = new JSONObject(result);
                    CharSequence w= (CharSequence) json_data.get("re");
                    Toast.makeText(getApplicationContext(), w, Toast.LENGTH_SHORT).show();

                       }
                catch(JSONException e)
                {
                        Log.e("log_tag", "Error parsing data "+e.toString());
                        Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
                }

         
              
                
           }
           });
          
          
          
   
     }
   

}
 



select.java



 package selva.db;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.NumberFormat;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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 org.json.JSONException;
import org.json.JSONObject;


import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class select extends Activity
{
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

   
     public void onCreate(Bundle savedInstanceState)
     {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.select);
           
            Button button = (Button) findViewById(R.id.button1);
            StrictMode.setThreadPolicy(policy);
           
            button.setOnClickListener(new View.OnClickListener()
            {
            public void onClick(View view)
              {
                 String result = null;
                InputStream is = null;
                EditText editText = (EditText)findViewById(R.id.e1);
                String v1 = editText.getText().toString();
                     EditText editText1 = (EditText)findViewById(R.id.e2);

                EditText editText2 = (EditText)findViewById(R.id.e3);

          ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

                nameValuePairs.add(new BasicNameValuePair("f1",v1));
                    try
                    {
                        HttpClient httpclient = new DefaultHttpClient();
                        HttpPost httppost = new HttpPost("http://10.0.2.2/select.php");
                        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                        HttpResponse response = httpclient.execute(httppost);
                        HttpEntity entity = response.getEntity();
                        is = entity.getContent();

                        Log.e("log_tag", "connection success ");
                    

                    }
                catch(Exception e)
                    {
                        Log.e("log_tag", "Error in http connection "+e.toString());
                        Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();

                    }
                //convert response to string
                    try{
                        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                        StringBuilder sb = new StringBuilder();
                        String line = null;
                        while ((line = reader.readLine()) != null)
                        {
                                sb.append(line + "\n");
                                

                        }
                        is.close();

                        result=sb.toString();
                    }
                    catch(Exception e)
                    {
                       Log.e("log_tag", "Error converting result "+e.toString());


                    Toast.makeText(getApplicationContext(), " Input reading fail", Toast.LENGTH_SHORT).show();

                    }

                //parse json data
                try{
                   
          
                        JSONObject object = new JSONObject(result);
                        String ch=object.getString("re");
                        if(ch.equals("success"))
                        {
                          
                           JSONObject no = object.getJSONObject("0");
                           
                         //long q=object.getLong("f1");
                        String w= no.getString("f2");
                        long e=no.getLong("f3");
                       
                        editText1.setText(w);
                       String myString = NumberFormat.getInstance().format(e);

                       
                        editText2.setText(myString);

                          }

                       
                        else
                        {
                          
                            Toast.makeText(getApplicationContext(), "Record is not available.. Enter valid number", Toast.LENGTH_SHORT).show();

                        }
                   
               
                }
                catch(JSONException e)
                {
                        Log.e("log_tag", "Error parsing data "+e.toString());
                        Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
                }


           }
           });
           
           
   
     }
   

}




 delete.java



package selva.db;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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 org.json.JSONException;
import org.json.JSONObject;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class delete extends Activity  {
   
   
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();


   
   
   
     public void onCreate(Bundle savedInstanceState)
   
     {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.delete);
          
            Button button = (Button) findViewById(R.id.button1);
          
          
            button.setOnClickListener(new View.OnClickListener()
            {
            public void onClick(View view)
            {
              
                 String result = null;
                InputStream is = null;

              

                EditText editText = (EditText)findViewById(R.id.e1);

                String v1 = editText.getText().toString();

                              
                ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

                nameValuePairs.add(new BasicNameValuePair("f1",v1));
              

                StrictMode.setThreadPolicy(policy);

                //http post
                try
                {
                        HttpClient httpclient = new DefaultHttpClient();
                        HttpPost httppost = new HttpPost("http://10.0.2.2/delete.php");
                        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                        HttpResponse response = httpclient.execute(httppost);
                        HttpEntity entity = response.getEntity();
                        is = entity.getContent();

                        Log.e("log_tag", "connection success ");
                        Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
                }
                catch(Exception e)
                {
                        Log.e("log_tag", "Error in http connection "+e.toString());
                        Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();

                }
                //convert response to string
                try
                {
                        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                        StringBuilder sb = new StringBuilder();
                        String line = null;
                        while ((line = reader.readLine()) != null) {
                                sb.append(line + "\n");
                         Intent i = new Intent(getBaseContext(),DatabaseActivity.class);
                                startActivity(i);
                  }
                        is.close();

                        result=sb.toString();
                }
                catch(Exception e)
                {
                       Log.e("log_tag", "Error converting result "+e.toString());
                

                }

          
              
                //parse json data
                try
                {
                  
                               JSONObject json_data = new JSONObject(result);

                              
                                CharSequence w= (CharSequence) json_data.get("re");
                            
                                Toast.makeText(getApplicationContext(), w, Toast.LENGTH_SHORT).show();

                  }
                catch(JSONException e)
                {
                        Log.e("log_tag", "Error parsing data "+e.toString());
                        Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
                }


           }
           });
          
   
     }
   }
 
 



  AndroidMenifest.xml


 ?xml version="1.0" encoding="utf-8"?>


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="selva.db"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="14" />
   
 <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
          <activity
               android:label="@string/app_name"
              android:name=".DatabaseActivity" >
              <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
              </intent-filter>
          </activity>
       
           
           
           
           
         <activity
              android:label="Insert Record"
              android:name=".insert" >
             <intent-filter >
                <action android:name="q.w.e.qwe" />
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
       
       <activity
            android:label="Get Record"
            android:name=".select" >
            <intent-filter >
                <action android:name="q.w.e.qwe" />
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
           
          
       <activity
            android:label="Delete Record"
            android:name=".delete" >
            <intent-filter >
                <action android:name="q.w.e.qwe" />
               <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
          
       <activity
            android:label="Update Record"
            android:name=".update" >
            <intent-filter >
                <action android:name="q.w.e.qwe" />
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

    </application>


</manifest>



 After installing the wamp server,  C drive --> wamp --> www --> save the following php program in given corresponding names.

database name: ex1

Table Name     :  t1

Fields Name    :  f1(bigint),f2(text),f3(bigint)





  insert.php


     <?php

         $con = mysql_connect("localhost","root","");
         if (!$con)
           {
             die('Could not connect: ' . mysql_error());
           }

           mysql_select_db("ex1", $con);


           $v1=$_REQUEST['f1'];
           $v2=$_REQUEST['f2'];
           $v3=$_REQUEST['f3'];


              if($v1==NULL || $v2==NULL || $v3==NULL)
             {


                $r["re"]="Fill the all fields!!!";
                 print(json_encode($r));
                die('Could not connect: ' . mysql_error());

             }


            else
          {
           $i=mysql_query("select * from t1 where f1=$v1",$con);
           $check='';
                  while($row = mysql_fetch_array($i))
                    {
 
                          $check=$row['f1'];

                     }

          
                   if($check==NULL)
                  {

                        $q="insert into t1 values('$v1','$v2','$v3')";
                        $s= mysql_query($q);
                        if(!$s)
                          {
                                $r["re"]="Inserting problem in batabase";
                 
                               print(json_encode($r));
                           }
                         else
                          {
                             $r["re"]="Record inserted successfully";
                              print(json_encode($r));
                           }
             }
            else
             {
               $r["re"]="Record is repeated";
                 print(json_encode($r));
     
              }
}
 mysql_close($con);
              
    ?>
 


 update.php

         
     <?php

         $con = mysql_connect("localhost","root","");
         if (!$con)
           {
             die('Could not connect: ' . mysql_error());
           }

           mysql_select_db("ex1", $con);


             $v1=$_REQUEST['f1'];
             $v2=$_REQUEST['f2'];
             $v3=$_REQUEST['f3'];
  
              if($v1==NULL || $v2==NULL || $v3==NULL)
              {
                 $r["re"]="Fill the all fields!!!";
                 print(json_encode($r));
                die('Could not connect: ' . mysql_error());
               }
             else
                   {

                       $i=mysql_query("select * from t1 where f1=$v1",$con);
                        $check='';
                      while($row = mysql_fetch_array($i))
                       {
 
                             $check=$row['f1'];

                        }

          
                        if($check!=NULL)
                       {

                           $q="update t1 set f2='$v2',f3='$v3' where f1='$v1'";
                           $s= mysql_query($q,$con);
                          if(!$s)
                           {
                                 $r["re"]="updating problem in batabase";
                 
                                 print(json_encode($r));
                              }
                            else
                            {
                               $r["re"]="Record updated successfully";
                    
                                   print(json_encode($r));
                              }
                          }
                        else
                          {
                           $r["re"]="Record is not available.. Enter valid number!!";
                              print(json_encode($r));
                          }

           }
 mysql_close($con);
              
    ?>
 


  select.php

        <?php

         $con = mysql_connect("localhost","root","");
         if (!$con)
           {
             die('Could not connect: ' . mysql_error());
           }

           mysql_select_db("ex1", $con);
           $v1=$_REQUEST['f1'];
          if($v1==NULL)
            {


                $r["re"]="Enter the number!!!";
                 print(json_encode($r));
                die('Could not connect: ' . mysql_error());
          }

          else

            {


                $i=mysql_query("select * from t1 where f1=$v1",$con);
               $check='';
               while($row = mysql_fetch_array($i))
                {
 
                  $r[]=$row;
                  $check=$row['f1'];
                 }
                  if($check==NULL)
                   {           
                      $r["re"]="Record is not available";
                      print(json_encode($r));
                
                     }
                   else
                     {
                         $r["re"]="success";
                            print(json_encode($r));
                             
                       }



}

 mysql_close($con);
              
    ?>


 delete.php

       <?php

         $con = mysql_connect("localhost","root","");
         if (!$con)
           {
             die('Could not connect: ' . mysql_error());
           }

               mysql_select_db("ex1", $con);


                  $v1=$_REQUEST['f1'];


                 if($v1==NULL)
                {


                          $r["re"]="Enter the number!!!";
                          print(json_encode($r));
                         die('Could not connect: ' . mysql_error());

                     }



                    else

                   {
                           $i=mysql_query("select * from t1 where f1=$v1",$con);
                           $check='';

                        while($row = mysql_fetch_array($i))
                         {
 
                             $check=$row['f1'];

                           }

          
                             if($check==NULL)
                             {

                                   $r["re"]="Record is not found.. Enter valid number";
                                   print(json_encode($r));
                              }            
                           else
                          {
                                    $q="delete from t1 where f1='$v1'";
                                     $s= mysql_query($q,$con);
                                     if(!$s)
                                    {
                                            $r["re"]="Record deletion problem in batabase";
                 
                                             print(json_encode($r));
                                     }
                                     else
                                          {
                                             $r["re"]="Record Deleted successfully";
                                              print(json_encode($r));
                                            }

                                 }


                    }

 mysql_close($con);
              
    ?> 





 you should run php by giving your own values. Then you should use php programs 

  in android. 






















 output:



























click insert button




























you will get record added successfully message after Clicking Button.

Then click back button -->  Retrieve button --> Enter number which is given while inserting -->Click button --> you will get record which is inserted in database.













































Then click back button -->  update button --> Enter number which is given while inserting -->Click button --> you will get record which is inserted in database.

Then alter name--> then click button

























Then click back button -->  Retrieve button --> Enter number which is given while inserting -->Click button --> you will get record which is upadted in database.





















Then click back button -->  Delete button --> Enter number which is given while inserting -->Click button --> you will get delete message which is inserted in database.





















To download Full program click here


Retrieve Database from mysql and Diplaying in Dynamic Table using android





Thank you friends.....






60 comments:

  1. hi. . in that select query how we redrive date format . . pls tell me. . an new to android.
    Thank you.

    ReplyDelete
  2. CharSequence w= (CharSequence) json_data.get("re");

    //re means??

    ReplyDelete
  3. Plz help me.. i have got an error... Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject

    ReplyDelete
  4. Is there any one who answers the questions posted??
    Has anybody got the answers for the questions posted??

    ReplyDelete
  5. Even I have got the same doubt....

    CharSequence w= (CharSequence) json_data.get("re");

    //re means??

    ReplyDelete
    Replies
    1. Hi deepak !
      re is result which can be get from php. For example take a look at select.php
      $r["re"]="Enter the number!!!";
      $r["re"]="Record is not available";
      $r["re"]="success";

      Just i pass the result via 're' variable !

      Delete
  6. Thankyou dear bro, very helpful!

    greetings from Azerbaijan/Baku

    ReplyDelete
  7. hi bro i have error in php files that insert.php file f1,f2,f3 is Undefined index bro what can i do now bro pls help me bro

    ReplyDelete
    Replies
    1. Did u pass these values from insert.java?
      nameValuePairs.add(new BasicNameValuePair("f1",v1));
      nameValuePairs.add(new BasicNameValuePair("f2",v2));
      nameValuePairs.add(new BasicNameValuePair("f3",v3));

      Delete
    2. yes bro
      but i run the insert .php showing this error

      please help bro


      Notice: Undefined index: f1 in C:\xampp\htdocs\phpfiles\insert.php on line 12

      Notice: Undefined index: f2 in C:\xampp\htdocs\phpfiles\insert.php on line 13

      Notice: Undefined index: f3 in C:\xampp\htdocs\phpfiles\insert.php on line 14
      {"re":"Fill the all fields!!!"}Could not connect:
      what can i do pro

      Delete
    3. You must pass static values while run insert.php alone. When you run this from android you must get values using POST or GET method.

      Delete
  8. This comment has been removed by the author.

    ReplyDelete
  9. i have got dis error.. will you help me?? Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject

    ReplyDelete
    Replies
    1. you can't get string as JSONObject. You can design the JSON code depends on the result which you can get from server. The result is mixing of strings,JSONObjects and JSONArray.

      Delete
  10. getting jason fail while updation kindly help me..

    ReplyDelete
  11. String result1 = null;
    InputStream is1 = null;

    editText1 = (EditText) findViewById(R.id.e2);
    String v11 = editText1.getText().toString();
    editText1.setText("");

    editText2 = (EditText) findViewById(R.id.e2);
    String v2 = editText2.getText().toString();
    editText2.setText("");

    editText3 = (EditText) findViewById(R.id.e3);
    String v3 = editText3.getText().toString();
    editText3.setText("");

    editText4 = (EditText) findViewById(R.id.e4);
    String v4 = editText4.getText().toString();
    editText4.setText("");

    editText5 = (EditText) findViewById(R.id.e5);
    String v5 = editText5.getText().toString();
    editText5.setText("");

    editText6 = (EditText) findViewById(R.id.e6);
    String v6 = editText6.getText().toString();
    editText6.setText("");

    editText7 = (EditText) findViewById(R.id.e7);
    String v7 = editText7.getText().toString();
    editText7.setText("");

    editText8 = (EditText) findViewById(R.id.e8);
    String v8 = editText8.getText().toString();
    editText8.setText("");

    ArrayList nameValuePairs1 = new ArrayList();

    nameValuePairs1.add(new BasicNameValuePair("SNo", v11));
    nameValuePairs1.add(new BasicNameValuePair("Subject", v2));
    nameValuePairs1.add(new BasicNameValuePair("Originating_From", v3));

    nameValuePairs1.add(new BasicNameValuePair("Department_Sent_To", v4));
    nameValuePairs1.add(new BasicNameValuePair("Status", v5));
    nameValuePairs1.add(new BasicNameValuePair("Type", v6));

    nameValuePairs1.add(new BasicNameValuePair("Received_Date", v7));
    nameValuePairs1.add(new BasicNameValuePair("Who_Is_Reading", v8));

    StrictMode.setThreadPolicy(policy);

    // http post
    try {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://10.0.2.2/update.php");
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs1));
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    is1 = entity.getContent();

    Log.e("log_tag", "connection success ");
    Toast.makeText(getApplicationContext(), "pass",
    Toast.LENGTH_SHORT).show();
    }

    catch (Exception e) {
    Log.e("log_tag", "Error in http connection " + e.toString());
    Toast.makeText(getApplicationContext(), "Connection fail",
    Toast.LENGTH_SHORT).show();

    }
    // convert response to string
    try {
    BufferedReader reader = new BufferedReader(
    new InputStreamReader(is1, "iso-8859-1"), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line + "\n");

    }
    Log.e("log_tag", "connection success1 ");
    is1.close();

    result1 = sb.toString();
    } catch (Exception e) {
    Log.e("log_tag", "Error converting result " + e.toString());
    }

    try {

    JSONObject json_data = new JSONObject(result1);
    //int code=(json_data.getInt("code"));

    CharSequence w = (CharSequence) json_data.get("re");
    Log.e("log_tag", "connection success2 ");
    Toast.makeText(getApplicationContext(), w, Toast.LENGTH_SHORT).show();

    /* if(code==1)
    {
    Toast.makeText(getBaseContext(), "Update Successfully",
    Toast.LENGTH_SHORT).show();
    }

    else
    {
    Toast.makeText(getBaseContext(), "Sorry, Try Again",
    Toast.LENGTH_LONG).show();
    }
    */
    } catch (JSONException e) {
    Log.e("log_tag", "Error parsing data " + e.toString());
    Toast.makeText(getApplicationContext(), "JsonArray fail",
    Toast.LENGTH_SHORT).show();
    }
    }

    }





    php




    ReplyDelete
  12. Please Help me
    How to insert multiple row in mysql using Andoird?

    ReplyDelete
    Replies
    1. send JSON array to php. Then you can process the json for inserting.

      Delete
    2. you have any example than send me please
      rajneesh.gosai@yahoo.com

      Delete
    3. Thank u so much for such a great tutorial. Sir pls share any example where we can update mutiple rows at a time.

      Delete
  13. Thank you so much sir, am very grateful to you'.......... :)

    ReplyDelete
  14. jarrive pas a insérer aucun donnée lorsque je clique sur insert ilya des erreur
    04-12 22:03:07.225: E/AndroidRuntime(883): at org.json.JSONObject.(JSONObject.java:154)
    04-12 22:03:07.225: E/AndroidRuntime(883): at org.json.JSONObject.(JSONObject.java:171)
    04-12 22:03:07.225: E/AndroidRuntime(883): at selva.db.select$1.onClick(select.java:101)
    04-12 22:03:07.225: E/AndroidRuntime(883): at android.view.View.performClick(View.java:3480)
    04-12 22:03:07.225: E/AndroidRuntime(883): at android.view.View$PerformClick.run(View.java:13983)
    04-12 22:03:07.225: E/AndroidRuntime(883): at android.os.Handler.handleCallback(Handler.java:605)
    04-12 22:03:07.225: E/AndroidRuntime(883): at android.os.Handler.dispatchMessage(Handler.java:92)
    04-12 22:03:07.225: E/AndroidRuntime(883): at android.os.Looper.loop(Looper.java:137)
    04-12 22:03:07.225: E/AndroidRuntime(883): at android.app.ActivityThread.main(ActivityThread.java:4340)
    04-12 22:03:07.225: E/AndroidRuntime(883): at java.lang.reflect.Method.invokeNative(Native Method)
    04-12 22:03:07.225: E/AndroidRuntime(883): at java.lang.reflect.Method.invoke(Method.java:511)
    04-12 22:03:07.225: E/AndroidRuntime(883): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
    04-12 22:03:07.225: E/AndroidRuntime(883): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
    04-12 22:03:07.225: E/AndroidRuntime(883): at dalvik.system.NativeStart.main(Native Method)

    ReplyDelete
  15. I have a problem
    org.json.JSONException: Value
    nameValuePairs = new ArrayList();
    nameValuePairs.add(new BasicNameValuePair("pseudo", "ikram"));
    try {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://10.0.2.2/test_pfa/getCordinate.php");
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    is = entity.getContent();
    } catch (Exception e) {
    Toast.makeText(Interface_3.this, "Your friend is not Connected", Toast.LENGTH_LONG).show();
    }
    // convertion of the query into string
    try {
    BufferedReader reader = new BufferedReader(
    new InputStreamReader(is, "iso-8859-1"), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line + "\n").toString().substring(0, sb.toString().length()-1);

    }
    is.close();
    result = sb.toString();
    } catch (Exception e) {
    Toast.makeText(Interface_3.this, "can not recuperate coordinate",
    Toast.LENGTH_LONG).show();
    }
    try {
    Toast.makeText(Interface_3.this,"Merci pour votre inscription " , Toast.LENGTH_LONG).show();
    //Log.i("tagconvertstr", "["+result+"]");
    JSONArray jArray = new JSONArray(result);
    for (int i = 0; i < jArray.length(); i++) {
    JSONObject json_data = jArray.getJSONObject(i);
    passd = json_data.getString("passwd");

    }
    }catch (Exception e){
    Toast.makeText(Interface_3.this, "erreur: "+e.toString(),
    Toast.LENGTH_LONG).show();
    }


    return passd;
    }
    IN php:

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
  16. This comment has been removed by the author.

    ReplyDelete
  17. have you application of this code for Email apps (like : Gmail) ??

    ReplyDelete
  18. i am connected with local phpymadmin...

    but when try to access my remote sql server....it not works.

    i changed host name, db_username, pass, and db.....

    table and field are same....

    i run on my pc it works....but when try in android it not...

    help me.

    thank you

    ReplyDelete
    Replies
    1. You have to change IP adress "10.0.2.2" by YOUR IP ADDRESS

      Delete
  19. How do i do the same using xampp? i got "JsonArray fail" when i tried this in my system. Please i would be grateful if you reply fast.

    ReplyDelete
    Replies
    1. i'm getting this error too..please help me if you got the solution

      Delete
  20. if i want to get a list data from table t1. what will i do?
    Tks

    ReplyDelete
  21. Sorry .. anyone can help me ? when i click on insert button nothing happen .. it mean i cant do insert process.. why ?

    ReplyDelete
  22. i have got dis error.. will you help me?? Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject

    When i execute This Code, Please Help me Bro.

    ReplyDelete
  23. thanx for sharing
    it's helpful.....

    ReplyDelete
  24. 03-26 23:38:11.470 22857-22857/com.example.shreeram.sixthsense E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.NullPointerException
    at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
    at org.json.JSONTokener.nextValue(JSONTokener.java:94)
    at org.json.JSONObject.(JSONObject.java:154)
    at org.json.JSONObject.(JSONObject.java:171)
    at com.example.shreeram.sixthsense.RegisterActivity$1.onClick(RegisterActivity.java:138)
    at android.view.View.performClick(View.java:4191)
    at android.view.View$PerformClick.run(View.java:17229)
    at android.os.Handler.handleCallback(Handler.java:615)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4960)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
    at dalvik.system.NativeStart.main(Native Method)

    ReplyDelete
  25. Nice blog...Very useful information is providing by ur blog. Great beginning php tutorials Very clear and helpful for beginners.

    ReplyDelete
  26. code didn't worke ,what i shall do???sir

    ReplyDelete
  27. When Im trying to retriving data from mysql it says " E/log_tag(582): Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
    "
    and shows msg "JsonArray fail"
    Can you please help me???
    Thankyou

    ReplyDelete
  28. how to create database and tables inorder to insert the value. U hve specified "http://10.0.2.2/insert.php" which ipaddress should i use whether LAN address or Wifi address.

    ReplyDelete
  29. how can i upload profile image with this.. i got an error while upload to mysql server..

    ReplyDelete
  30. Thank you so much for this helpful post.

    ReplyDelete
  31. selva sir

    530 selvakumar
    45 yaaru thambi ??

    ReplyDelete
    Replies
    1. Hi Mr.deepan,
      45 -> it's just number.

      Delete
  32. Nicely presented information in this post, I prefer to read this kind of stuff. The quality of content is fine and the conclusion is good. Thanks for the post. forgings manufacturing

    ReplyDelete
  33. nameValuePairs.add(new BasicNameValuePair("f1", v1));

    The method add(NameValuePair) in the type ArrayList is not applicable for the arguments (BasicNameValuePair)


    How to solve this error

    ReplyDelete
  34. hi
    i have not understand the structure of application where i put PHP file please give idea

    ReplyDelete
  35. This comment has been removed by the author.

    ReplyDelete
  36. Hi Sir I was use the above code.The database was connect Succesfully.I Try to Insert the Data From Android to Localhost means i got the below error Like.
    "E/log_tag: Error parsing data org.json.JSONException: Value <?xml of type java.lang.String cannot be converted to JSONObject"
    Please Give the Solution For this Error Sir
    Thanks and Regards
    Raji

    ReplyDelete
    Replies
    1. Hi Rajitha,
      It's looking like parse exception. Display the result before parsing it.

      Delete
  37. Sorry sir I can't Understand That Display the result before parsing it.

    ReplyDelete
    Replies
    1. Did you get result in postman? First check the result in postman Once you get result in postman, come back to android and parse it.

      Delete
    2. Yeah Sir I have the result of php with mysql Using XAMP part sucessfully Working.But in the Android Part When insert the data i got the above Error Message Sir.

      Delete
  38. How do I send data to MySQL using android phone without using webhost?

    ReplyDelete
  39. This comment has been removed by the author.

    ReplyDelete
  40. I follow exartly what is here and the code has this

    "Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject"

    Insert and delete work fine but select and update has this error.

    Please help needed.

    ReplyDelete