Hi all..
Most of our visitors had problem with one of our previous post on Android-php connection. So here I am posting another simple example to connect with a php file. Here I am simply putting an echo in the php file which ehoes back the data from the android side.
Here are the things you need to remember.
1. Make sure your server is running(Xampp or Wampp).
2. Make sure you give right path of your php file inside your android program.
3. Make sure you have put the internet permission in the android manifest file.
4. And the last one the android side and php side posting variables should be the same.Here is the android main java file contents.
package pack.coderzheaven; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class AndroidPHPConnectionDemo extends Activity { Button b; EditText et; TextView tv; HttpPost httppost; StringBuffer buffer; HttpResponse response; HttpClient httpclient; List<NameValuePair> nameValuePairs; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b = (Button)findViewById(R.id.Button01); et= (EditText)findViewById(R.id.EditText01); tv= (TextView)findViewById(R.id.tv); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { final ProgressDialog p = new ProgressDialog(v.getContext()).show(v.getContext(),"Waiting for Server", "Accessing Server"); Thread thread = new Thread() { @Override public void run() { try{ httpclient=new DefaultHttpClient(); httppost= new HttpPost("http://10.0.0.2/my_folder_inside_htdocs/connection.php"); // make sure the url is correct. //add your data nameValuePairs = new ArrayList<NameValuePair>(1); // Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar, nameValuePairs.add(new BasicNameValuePair("Edittext_value",et.getText().toString().trim())); // $Edittext_value = $_POST['Edittext_value']; httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); //Execute HTTP Post Request response=httpclient.execute(httppost); ResponseHandler<String> responseHandler = new BasicResponseHandler(); final String response = httpclient.execute(httppost, responseHandler); System.out.println("Response : " + response); runOnUiThread(new Runnable() { public void run() { p.dismiss(); tv.setText("Response from PHP : " + response); } }); }catch(Exception e){ runOnUiThread(new Runnable() { public void run() { p.dismiss(); } }); System.out.println("Exception : " + e.getMessage()); } } }; thread.start(); } }); } }
Here is the main.xml the layout for the above file.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <EditText android:text="" android:id="@+id/EditText01" android:layout_width="fill_parent" android:layout_height="wrap_content" android:singleLine="true"> </EditText> <Button android:text="Send to php side" android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content"> </Button> <TextView android:id="@+id/tv" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="" /> </LinearLayout>
Here is the android manifest.xml file
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="pack.coderzheaven" android:versionCode="1" android:versionName="1.0"> <uses-permission android:name="android.permission.INTERNET"></uses-permission> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".AndroidPHPConnectionDemo" 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> </manifest>
Here is the PHP side. I am simply echoing back the value send from the android side.
connection.php
$val = $_POST['Edittext_value']; echo $val;
here I have a Edittext on my android side and after entering something in it and hitting the button to send, the textbox data will be send to the server and the server echoes back the same data.
My php file is saved in a folder named “my_folder_inside_htdocs” and named “connection.php”
I am working in localhost so it is given as “10.0.2.2” please replace your domain name here.
However you have a MySQl-connection in that php file and fetch some data from the database and echo back from the php side. You will get that data as string in the php side in this line
ResponseHandler<String> responseHandler = new BasicResponseHandler(); String response = httpclient.execute(httppost, responseHandler); System.out.println("Response : " + response); </blockquote>
You can manipulate this string as you want.
Any problem with this post please leave your comments.If this post was useful then click on the +1 button on top to share it across the web.
Please leave your valuable comments.
Here is another more detailed explanation.
How to create Simple Login form using php in android? – Connect php with android.
How do you create the php file? Is it a simple notepad with .php extension? or Eclipse with PDT installed?
You can simply create a php file with any editor. Only thing is it should have a .php extension and it needs a server to run. You can test this in your system in localhost also.
Thanks for the Example. I had search the Internet over for the EditText to Post to PHP. I will bookmark your site!!!
Hello James,
congratulations for your great effort! I have some problems implementing this code. At lines
b = (Button)findViewById(R.id.Button01);
et= (EditText)findViewById(R.id.EditText01); tv= (TextView)findViewById(R.id.tv);
i get that id can not be resolved or is not a field. What can i do?
Hello Dim, check that while you build the project an import like “import android.R “(something like that, not sure) might have automatically imported in the top section of your code. Please delete that and proceed.
Also make sure your layout xml is ok.
hey james,i even i have the same problem..
b = (Button)findViewById(R.id.Button01);
et= (EditText)findViewById(R.id.EditText01); tv= (TextView)findViewById(R.id.tv);
show error..i checked it,the there values are not present in the R.java file(which should happen bydefault after declaration),what may be the problem??
Hello sanjay:- This will sometimes happen in android when you copy a project. Try this-> Right click on your project and select properties, then try changing the SDK and click apply. Or clean your project and build again.
Check that something like import “android.R” has been imported in your project , then delete it and clean the project and then run the project. This will solver your problem.
hello james
using wamp server(working fine)
using correct ip address 192.168.1.106(localip)
given correct root folder(wamp/www/hello.php)
I have followed your previous post and this post too..But when ever i click the button nothing is happening and when i used your last post it shows invalid username and password.
I think there is a problem with the emulator connecting to php file and mysql.
please send me reply as iam currently stuck totally in my project.
Thank you and this post is really helpfull!!
Hello bhargav:- I am using Xampp and never used wampp. If you are using the localhost then try changing the ip to 10.0.2.2 (alias for localhost) . If the previous post was working and you are getting invalid username and password then try echoing back what you are sending from your android side as result. If you are getting invalid username or password, most probably the problem is with the php file. Try using the same variable name as android client(it is case sensitive).
My suggesting is instead of echoing “invalid username or password” echo back the username and password and see what values are going to the php side.
In your latest java file experiment by just putting a simple echo in your php side and try sending parameters one by one. Please leave your comments if you have any more doubts.
hey James
I was trying the code the new one but on my phone its displaying the whole html document.Also when I tried at home connected to same wifi and its not working.
I want to develop an app that could talk with other clients on local wifi via server.DO you think I need a database for this mechanism to work.
I also tried cnnecting two phones on same wifi without a server but it didnt work.
ANy way james,if you knw any information please let me know.
Thanx man.I realy appreciate for your great help!!
Where you are gettting the html code? Can you explain.
You need a database for you application if you want to store the details of clients and their conversation, it can be SQLite or it can be on the server. if it is an SQLite then you will loose data if the user uninstalls the application.
Hey james
Thank you for your immediate response man.It’s wonderful.
When I am just running the new code which is on this page on emulator.I am getting as php responce as below:
$val = $_POST[‘Edittext_value’];
echo $val;
BUt when I run the app on real device its saying
Response from PHP:<!doctype html PUBLIC"-/W#C/DTD XHTML 1.0 and sooo onnnnn….
Wht might be the exact problem.
IN my app I am trying to connect to php files from three or four devices and then open a socket communication between devices to implement chat.What do you think about this idea and as you know android how much time do you think this is going to take.
Hello Bhargav:- I think your file has no php tags. echo only the things you want, everything else is ok. Check whether your file has php tags. I think currently your file is HTML.
OR you might be putting the HTML code inside the php tags.
Hey james,
I uploaded my PHP file at some remote web host,
for example http://www.xyz.com/display.php , something like that.
And when ever i click on the button , i get an error saying “Activity TestDB is not responding”.
Is it cos of the remote web host or something else ?
Cos i’m working on linux and i got some permission issues so can’t install XAMPP.
Please Help,
Thank you.
No check the LogCat for the problem. It is most probably the problem in your side- Some reference error or null pointer exception.
Thing is ,i heard this “Not Responding” problem is common. So im not sure what to do.
Hi James,
somehow I’m making a mistake – or am failing to have some code done correctly – I have done all of the coding for the android app – but there is no response (no reaction) form either the emulator or my galaxy tab… Why could that be? It says that it installs it on the device, but when it should load – it’s simply not starting – when I look for it on the device, it’s not installed there aswell…. ??? Hmmm
if there is no response from the emulator or tab then how did you develop the app. I can’t understand your problem.
IF the app is not installing it may be due to your device’s memory problem. Try uninstalling some unwanted applications and install again.
Sorry – failed to mention that it was from the first tutorial (http://coderzheaven.com/2011/04/android-phpmysql-connection/)
James, Would you mind send me your full success login example include the php for me?? Your help will be appreciate. Hope your can help me out ><"
OK RYS check your inbox soon
OR could anyone of you guys that have the app working, send me the WORKING application just delete the passwords?
Hi James, I still didn’t receive your attachment yet…i just received your message only. Can you please send for me again? Thanks~
Hi james
I cant get this code to work as well 🙁 it gives me the error of
error: package R does not exist
in four seperate places for the
setContentView(R.layout.main);
It also underlines the second @Override and says that its not allowed went implementing interface method
After send to php side, nothing happens…any ideas ?
Did you check whether your php server is running. It is a perfect;y working code. Check your logcat for the exception caught and solve the problem.
Feel free to ask if you have any more doubts.
Hello Skynight :- Please check that your php server is running and make sure the URL is a existing file and the path is correct. If something comes from the php side even if it is a php error it will be shown in a textView below.
Hi
when i start running the application, i got the following msg in emulator,
“The application has stopped unexpectedly. please try again.”
I’m also attaching log information here,
10-31 12:18:52.384: ERROR/AndroidRuntime(394): FATAL EXCEPTION: main
10-31 12:18:52.384: ERROR/AndroidRuntime(394): java.lang.RuntimeException: Unable to start activity ComponentInfo{pack.coderzheaven/pack.coderzheaven.AndroidPHPConnectionDemo}: java.lang.NullPointerException
10-31 12:18:52.384: ERROR/AndroidRuntime(394): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1815)
10-31 12:18:52.384: ERROR/AndroidRuntime(394): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1831)
10-31 12:18:52.384: ERROR/AndroidRuntime(394): at android.app.ActivityThread.access$500(ActivityThread.java:122)
10-31 12:18:52.384: ERROR/AndroidRuntime(394): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1024)
10-31 12:18:52.384: ERROR/AndroidRuntime(394): at android.os.Handler.dispatchMessage(Handler.java:99)
10-31 12:18:52.384: ERROR/AndroidRuntime(394): at android.os.Looper.loop(Looper.java:132)
10-31 12:18:52.384: ERROR/AndroidRuntime(394): at android.app.ActivityThread.main(ActivityThread.java:4123)
10-31 12:18:52.384: ERROR/AndroidRuntime(394): at java.lang.reflect.Method.invokeNative(Native Method)
10-31 12:18:52.384: ERROR/AndroidRuntime(394): at java.lang.reflect.Method.invoke(Method.java:491)
10-31 12:18:52.384: ERROR/AndroidRuntime(394): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
10-31 12:18:52.384: ERROR/AndroidRuntime(394): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
10-31 12:18:52.384: ERROR/AndroidRuntime(394): at dalvik.system.NativeStart.main(Native Method)
10-31 12:18:52.384: ERROR/AndroidRuntime(394): Caused by: java.lang.NullPointerException
10-31 12:18:52.384: ERROR/AndroidRuntime(394): at pack.coderzheaven.AndroidPHPConnectionDemo.onCreate(AndroidPHPConnectionDemo.java:84)
10-31 12:18:52.384: ERROR/AndroidRuntime(394): at android.app.Activity.performCreate(Activity.java:4397)
10-31 12:18:52.384: ERROR/AndroidRuntime(394): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048)
10-31 12:18:52.384: ERROR/AndroidRuntime(394): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1779)
10-31 12:18:52.384: ERROR/AndroidRuntime(394): … 11 more
Pls help me sir..
Hi
After clicking button, nothing happens,
In my log it shows Exception:null
I’m running php server.
Any idea?
Hello Naveen :- Please check that your php server is running and make sure the URL is a existing file and the path is correct. If something comes from the php side even if it is a php error it will be shown in a textView below.
Hi James,
My PHP server is running perfectly and the URL is also correct.
I’m also getting ‘Exception:null’ in my log, even i have used the file in local host.
httppost= new HttpPost(“http://10.0.2.2 /connection.php”);
In connection.php, it has
Is anything wrong?
Naveen :- Check this link
try creating a folder and put connection.php inside that. If there is any error in connection.php it will be shown in the textview as per the code.
I think the request is not reaching the php side. There can be no other error in this code.
Hi james
How to get rid of
Exception : android.os.NetworkOnMainThreadException null
Exception is thrown while executing
response=httpclient.execute(httppost);
Pls help me
Hi James!
Thanks for the example, but I’m having a problem on how to remove the extra characters on the response string. something like this
“i>>?string”
Hi james,
I have followed your this post..But when ever i click the button nothing is happening …what error is happened …
wen i run d above project, n enter value in text box n click on button, my console has this msg which is d last msg n my application does nothing.
[2012-01-13 23:04:29 – tryf] ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.tryf.android/.TryfActivity }
check the logcat not the console.
basically i m creating a login page which verifies it with my mysql database. but even this much is not working.. pls help..
@radhinka:- what help do you need?
Hi!!
This tutorial is very useful for beginners like me
Thanks man nice tutorial.could u please help modify the program so that i can be able to save the value in the mysql database.
hi how to received(android) array list from php help me pls
Make it as a string with some delimiter in between and split it in the android side.
Pingback: Android phpMysql connection | Coderz Heaven
Thanks alot James. My project compiles successfully but nothing happens when I click on the button. Also no error is shown on the logCat.
Running the app in debug mode shows that response is null in this line:
” response=httpclient.execute(httppost);”
Any idea on what I might be missing. The php script works fine when I test on web browser.
Check whether you have added the permission in the manifest file.
I have added “INTERNET” permission to the manifest file and successfully followed your tutorial on uploading images which works fine. I just can’t get why database connectivity is failing.
I was finally able to solve my problem and would like to share the solution with other guys who might run into the same problem. I did a printStackTrace on the exception and read from the logcat what exactly causes it. I realized it was: ” at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)”
Then searched on how to solve this and noted that the best approach would have been to separate my network and UI threads. I did this and viola, all went well. However the restriction can also be solved (NOT a GOOD WAY) by adding the code below to the onCreate method of your main activity:
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Pingback: How to create Simple Login form using php in android? - Connect php with android.
Dear James
Thank you for this wonderful tutorial. I have been struggling with connections between php and android for more than 2 days now and after I worked through your tutorial I finally succeeded.
Thank you
Hey Heliose, People like you are always welcome. This is what the site’s name means.
Hey James,
I posted on one of your other tutorials. It is either awaiting moderation still, or for someone reason it wasn’t approved. I found the problem why people are seeing the button as unresponsive. My problem is I get the same error as a user above, “The application has stopped unexpectedly. please try again.” This happens right after I click the button and after the ProgressDialog.
As for the button, I suspect people are opening Eclipse and simply creating a new class then pasting the code. The problem with this is the XML layout file contains all the XML instructions for the button and edit texts, but the class file isn’t communicating with the XML doc. Those users should either put the code into the Main Activity, or create a new activity in Eclipse. This way an XML file is automatically generated and referenced.
Can someone please help me with my “The application has stopped unexpectedly. please try again.” problem 🙂
Pingback: How to get table values from a MySQL database and show it in Android as Tables.?
my server is not accessing..the dialog blink and it disappers….
Finally!
After days of googling and trying out different tutorials, this one worked in the very first try. You have made my day, good sir!
hey, thanks for your code….
In httpPost URL have written 10.0.0.2 in stand of 10.0.2.2
Cheers!!
Hello I getting Undefined index :Edittext_value
first of all thank you for you for providing this tutorial
I am getting this error first time i am doing this please resolve
11-01 17:30:16.918 W/SingleClientConnManager(14359): Invalid use of SingleClientConnManager: connection still allocated.
11-01 17:30:16.918 W/SingleClientConnManager(14359): Make sure to release the connection before allocating another one.
*11-01 17:30:16.973 W/System.err(14359): org.apache.http.client.HttpResponseException: Not Found
11-01 17:30:16.973 W/System.err(14359): at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:71)
11-01 17:30:16.973 W/System.err(14359): at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:59)
11-01 17:30:16.973 W/System.err(14359): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:657)
11-01 17:30:16.973 W/System.err(14359): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:627)
*11-01 17:30:16.978 W/System.err(14359): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:616)
11-01 17:30:16.978 W/System.err(14359): at com.example.androidphpproject.MainActivity$UploadListener$1.run(MainActivity.java:94)
Firstly Sir thank you so mch for this GREAT Tutorial. The tutorial u explained is vry nice.
Its really effective for begginers like me.
M totally new
to android, m just working on php.
Thank you so mch sir for efforts….
I cant connect my android app with localhost. I dont have the php code you are using. Can you plzz give me that code?? So I can try with that
Get it from the ResolveInfo.
Hello James Sir, I have followed your tutorial and developed this. I have an activity which validates a user by checking the credentials from the server.
Here is my code.
PaymentActivity.java
package com.example.androidphpmy;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class PaymentActivity extends Activity {
Button b;
EditText et,pass;
TextView tv;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List nameValuePairs;
ProgressDialog dialog = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment);
b = (Button)findViewById(R.id.Button01);
et = (EditText)findViewById(R.id.accountno);
pass= (EditText)findViewById(R.id.password);
tv = (TextView)findViewById(R.id.tv);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog = ProgressDialog.show(PaymentActivity.this, “”,
“Validating user…”, true);
new Thread(new Runnable() {
public void run() {
payment();
}
}).start();
}
});
}
void payment(){
try{
httpclient=new DefaultHttpClient();
httppost= new
HttpPost(“http://tanushreedutta.site40.net/payment_new/check.php”);
//add your data
nameValuePairs = new ArrayList(2);
// Always use the same variable name for posting i.e the android side variable name and
php side variable name should be similar,
nameValuePairs.add(new
BasicNameValuePair(“accno”,et.getText().toString().trim()));
// $Edittext_value = $_POST[‘Edittext_value’];
nameValuePairs.add(new
BasicNameValuePair(“bpassword”,pass.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
// edited by James from coderzheaven.. from here….
ResponseHandler responseHandler = new
BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
System.out.println(“Response : ” + response);
runOnUiThread(new Runnable() {
public void run() {
tv.setText(“Response from PHP : ” + response);
dialog.dismiss();
}
});
if(response.equalsIgnoreCase(“User Found”)){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(PaymentActivity.this,”Payment Successful”,Toast.LENGTH_SHORT).show();
}
});
startActivity(new Intent(PaymentActivity.this, MainActivity.class));
}
else{
showAlert();
}
}catch(Exception e){
dialog.dismiss();
System.out.println(“Exception : ” + e.getMessage());
}
}
public void showAlert(){
PaymentActivity.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(PaymentActivity.this);
builder.setTitle(“Payment Error.”);
builder.setMessage(“User not Found.”)
.setCancelable(false)
.setPositiveButton(“OK”, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
}
Now the problem is whenever I enter account no and password in response text, it gives me correct output but in any of the cases (valid or invalid user) it executes “else” statement i.e executes showAlert() method. Is there any problem with my code.Any suggestion or advice will be highly appreciated. Thank you all in advance !