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>
<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
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));
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
Thank you friends.....
hi. . in that select query how we redrive date format . . pls tell me. . an new to android.
ReplyDeleteThank you.
CharSequence w= (CharSequence) json_data.get("re");
ReplyDelete//re means??
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
ReplyDeletei have the same issue did you fixed it?
DeleteIs there any one who answers the questions posted??
ReplyDeleteHas anybody got the answers for the questions posted??
Even I have got the same doubt....
ReplyDeleteCharSequence w= (CharSequence) json_data.get("re");
//re means??
Hi deepak !
Deletere 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 !
Thankyou dear bro, very helpful!
ReplyDeletegreetings from Azerbaijan/Baku
You are welcome my brother !
Deletehi 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
ReplyDeleteDid u pass these values from insert.java?
DeletenameValuePairs.add(new BasicNameValuePair("f1",v1));
nameValuePairs.add(new BasicNameValuePair("f2",v2));
nameValuePairs.add(new BasicNameValuePair("f3",v3));
yes bro
Deletebut 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
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.
DeleteThis comment has been removed by the author.
ReplyDeletei 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
ReplyDeleteyou 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.
Deletegetting jason fail while updation kindly help me..
ReplyDeleteString result1 = null;
ReplyDeleteInputStream 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
Please Help me
ReplyDeleteHow to insert multiple row in mysql using Andoird?
send JSON array to php. Then you can process the json for inserting.
Deleteyou have any example than send me please
Deleterajneesh.gosai@yahoo.com
Thank u so much for such a great tutorial. Sir pls share any example where we can update mutiple rows at a time.
DeleteThank you so much sir, am very grateful to you'.......... :)
ReplyDeleteje peut inserer
ReplyDeletejarrive pas a insérer aucun donnée lorsque je clique sur insert ilya des erreur
ReplyDelete04-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)
I have a problem
ReplyDeleteorg.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:
This comment has been removed by the author.
DeleteThis comment has been removed by the author.
ReplyDeletehave you application of this code for Email apps (like : Gmail) ??
ReplyDeletei am connected with local phpymadmin...
ReplyDeletebut 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
You have to change IP adress "10.0.2.2" by YOUR IP ADDRESS
DeleteHow 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.
ReplyDeletei'm getting this error too..please help me if you got the solution
Deletesame here i'm also getting this same error
Deleteif i want to get a list data from table t1. what will i do?
ReplyDeleteTks
Sorry .. anyone can help me ? when i click on insert button nothing happen .. it mean i cant do insert process.. why ?
ReplyDeletei 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
ReplyDeleteWhen i execute This Code, Please Help me Bro.
thanx for sharing
ReplyDeleteit's helpful.....
03-26 23:38:11.470 22857-22857/com.example.shreeram.sixthsense E/AndroidRuntime﹕ FATAL EXCEPTION: main
ReplyDeletejava.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)
Can u please
Deletehelp me
code didn't worke ,what i shall do???sir
ReplyDeleteWhen 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
ReplyDelete"
and shows msg "JsonArray fail"
Can you please help me???
Thankyou
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.
ReplyDeletehow can i upload profile image with this.. i got an error while upload to mysql server..
ReplyDeleteThank you so much for this helpful post.
ReplyDeleteselva sir
ReplyDelete530 selvakumar
45 yaaru thambi ??
Hi Mr.deepan,
Delete45 -> it's just number.
nameValuePairs.add(new BasicNameValuePair("f1", v1));
ReplyDeleteThe method add(NameValuePair) in the type ArrayList is not applicable for the arguments (BasicNameValuePair)
How to solve this error
hi
ReplyDeletei have not understand the structure of application where i put PHP file please give idea
This comment has been removed by the author.
ReplyDeleteHi 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.
ReplyDelete"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
Hi Rajitha,
DeleteIt's looking like parse exception. Display the result before parsing it.
Sorry sir I can't Understand That Display the result before parsing it.
ReplyDeleteDid you get result in postman? First check the result in postman Once you get result in postman, come back to android and parse it.
DeleteYeah 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.
DeleteHow do I send data to MySQL using android phone without using webhost?
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteI follow exartly what is here and the code has this
ReplyDelete"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.
Nice blog...Very useful information is providing by ur blog. Great beginning php tutorials Very clear and helpful for beginners.
ReplyDeleteMy blog
I simply want to say I’m very new to blogs and actually loved you’re blog site. Almost certainly I’m going to bookmark your blog post . You absolutely come with great well written articles. Thanks a lot for sharing your blog.
ReplyDeleteAndroid Training in chennai |Android Training in Velachery
Thanks a lot! You made a new blog entry to answer my question; I really appreciate your time and effort.
ReplyDeleteBest Android Training in chennai|Android Training in chennai with placement | Android Training in velachery
07-19 03:11:47.231 9648-9648/com.example.acer.androidwithmysql E/log_tag: Error in http connection org.apache.http.conn.HttpHostConnectException: Connection to http://localhost refused
ReplyDelete07-19 03:11:47.234 9648-9648/com.example.acer.androidwithmysql E/log_tag: Error converting result java.lang.NullPointerException
07-19 03:11:47.234 9648-9648/com.example.acer.androidwithmysql D/AndroidRuntime: Shutting down VM
07-19 03:11:47.234 9648-9648/com.example.acer.androidwithmysql E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.acer.androidwithmysql, PID: 9648
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
at org.json.JSONTokener.nextValue(JSONTokener.java:94)
at org.json.JSONObject.(JSONObject.java:156)
at org.json.JSONObject.(JSONObject.java:173)
at com.example.acer.androidwithmysql.insert$1.onClick(insert.java:113)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
.
.
.
.
plzzz............
Confronting "Can't Connect to MySQL server? Contact to MySQL Server 5.0 Support
ReplyDeleteOrdinarily clients are not ready to associate with MySQL server in light of some after reasons: if there is arrange disappointment, no MySQL is running on the specified host, firewall blocking or because of some different reasons. Ensure; on the off chance that you know how to tackle this issue at that point proceed and rapidly fathom it generally pick most ideal approach to dispose of this issue i.e. MySQL Remote Support or MySQL Remote Service. We at Cognegic have various years of involvement in MySQL and viably comprehend your questions and give you most ideal arrangement.
For More Info: https://cognegicsystems.com/
Contact Number: 1-800-450-8670
Email Address- info@cognegicsystems.com
Company’s Address- 507 Copper Square Drive Bethel Connecticut (USA) 06801
ReplyDeleteIt’s actually a cool and helpful piece of info.
I’m happy that you just shared this helpful info
with us. Please keep us informed like this.
Thank you for sharing
hirschmann electronics
Star-x-c98
Latest software Ali 3510 c 102.102.02.026
Ecolink E17000
all-protocol
Max Future SX-6000
star track 150hd
Thanks for sharing such a nice Blog.I like it
ReplyDeleteWhy Play Games Online?
hardrest
ReplyDeleteMyBlogger Club
ReplyDeleteGuest Posting Site
Best Guest Blogging Site
Guest Blogger
Guest Blogging Site
Microcen IT Professional team have expertise in enterprise infrastructure security, design & deployment. We have best team in the industry to lead your security projects and infrastructure design & deployment.
ReplyDeleteMicrocen IT Professional team have expertise in enterprise infrastructure security, design & deployment. We have best team in the industry to lead your security projects and infrastructure design & deployment. https://www.microcen.com/architecture-design-and-implementation-services
ReplyDelete"We Are Fully IT Managed Services can provide the peace of mind you need.
ReplyDeleteDo you have a question about our process? Just feel like talking things out? Please give us a call or fill out the inquiry form." https://www.microcen.com/corporate-support
Very Informative, good stuff. A good article is one that a person is aware of, to get something to learn from that article and your article is also one of them.We hope that you will share a similar article in the future and make us aware thank you.
ReplyDeleteRead more articles here:
The Masters Real Estate
Smart City Lahore
Lahore Smart City Location
Capital Smart City map
Faisalabad Smart City
Park View City Islamabad
Park View City Lahore
Nova City Islamabad