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.....






Anatomy of an Android Application



Before reading this,  learn how to create android application:

Click here

 

First, note the various files that make up an Android project in the Package Explorer in Eclipse.



The various folders and their files are as follows:


 ➤ src — Contains   the   .java source files for your project. In this example, there is

 one  file, HelloworldActivity.java.  The HelloworldActivity.java file is the source file for 

your activity. You will write the code for your application in this file.


➤ Android 2.3 library — This item contains one file, android.jar, which contains all the 

class libraries needed for an Android application.


➤ gen — Contains the R.java file, a compiler-generated file that references all the 

resources found in your project. You should not modify this file. 


➤ assets — This folder contains all the assets used by your application, such as 

HTML, text files, databases, etc.


➤ res — This folder contains all the resources used in your application. It also   

contains a few other subfolders: drawable-<resolution>, layout, and values.

➤ AndroidManifest.xml — This is the manifest file for your Android application. Here 

you specify the permissions needed by your application, as well as other features 

(such as intent-filters,receivers, etc.).

MAIN.XML


The main.xml file defines the user interface for your activity. Observe the following in red color:

<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”@string/hello” />

 
The @string in this case refers to the strings.xml file located in the res/values folder. 

Hence, @string/hello refers to the hello string defined in the strings.xml file, which is “Hello World, MainActivity!”:

 
<?xml version=”1.0” encoding=”utf-8”?>
<resources>
<string name=”hello”>Hello World, MainActivity!</string>
<string name=”app_name”>HelloWorld</string>
</resources>

 
It is recommended that you store all the string constants in your application in this 

strings.xml file and reference these strings using the @string identifier. That way, if 

you ever need to localize your application to another language, all you need to do is 

replace the strings stored in the strings.xml file with the targeted language and 

recompile your application.



Observe the content of the AndroidManifest.xml file:



<?xml version=”1.0” encoding=”utf-8”?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android”
package=”m.m”
android:versionCode=”1”
android:versionName=”1.0”>
<application android:icon=”@drawable/icon” android:label=”@string/app_name”>
<activity android:name=”.
HelloworldActivity
android:label=”@string/app_name”>
<intent-filter>
<action android:name=”android.intent.action.MAIN” />
<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion=”9” />
</manifest>

The AndroidManifest.xml file contains detailed information about the application:

➤    It defines the package name of the application as m.m.

➤   The version code of the application is 1. This value is used to identify the version number of your application. It can be used to programmatically determine whether an application needs to be upgraded.

➤   The version name of the application is 1.0. This string value is mainly used for display to the user. You should use the format: <major>.<minor>.<point> for this value.

➤    The application uses the image named icon.png located in the drawable folder.

➤  The name of this application is the string named app_name defined in the strings.xml file.

➤   There is one activity in the application represented by the
HelloworldActivity.java 
file. The label displayed for this activity is the same as the application name.

➤    Within the definition for this activity, there is an element named <intent-filter>:

➤   The action for the intent fi lter is named android.intent.action.MAIN to indicate that
this activity serves as the entry point for the application.

➤    The category for the intent-fi lter is named android.intent.category.LAUNCHER
to indicate that the application can be launched from the device’s Launcher icon.

➤  Finally, the android:minSdkVersion attribute of the <uses-sdk> element specifi es the minimum version of the OS on which the application will run.

As you add more fi les and folders to your project, Eclipse will automatically generate the content of R.java, which at the moment contains the following:

package m.m;
public final class R {
public static final class attr {
}
public static final class drawable {
public static final int icon=0x7f020000;
}
public static final class layout {
public static final int main=0x7f030000;
}
public static final class string {
public static final int app_name=0x7f040001;
public static final int hello=0x7f040000;
}
}

 
You are not supposed to modify the content of the R.java file; Eclipse automatically generates the content for you when you modify your project.

Finally, the code that connects the activity to the UI (main.xml) is the setContentView() method, which is in the MainActivity.java file:

 
package m.m;
 
import android.app.Activity;
 
import android.os.Bundle;
 
public class
HelloworldActivity
extends Activity 

{
/** Called when the activity is first created. */
 
@Override
 
public void onCreate(Bundle savedInstanceState) 
{
 
super.onCreate(savedInstanceState);
 
setContentView(R.layout.main);
 
}
 
}

 
Here, R.layout.main refers to the main.xml file located in the res/layout folder. As you 

add additional XML files to the res/layout folder, the filenames will automatically be 

generated in the R.java file. The onCreate() method is one of many methods that are 

fired when an activity is loaded.