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.

 

63 Comments

  1. RoberVs August 2, 2011 at 8:58 pm

    How do you create the php file? Is it a simple notepad with .php extension? or Eclipse with PDT installed?

     
    • James August 2, 2011 at 9:00 pm

      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.

       
  2. Terry August 3, 2011 at 7:28 pm

    Thanks for the Example. I had search the Internet over for the EditText to Post to PHP. I will bookmark your site!!!

     
  3. Dim August 8, 2011 at 2:55 pm

    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?

     
    • James August 8, 2011 at 7:46 pm

      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.

       
  4. sanjay August 10, 2011 at 4:52 pm

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

     
    • James August 10, 2011 at 9:22 pm

      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.

       
  5. bharghav August 20, 2011 at 12:31 am

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

     
    • James August 20, 2011 at 11:56 am

      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.

       
      • bharghav August 30, 2011 at 7:45 am

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

         
        • James August 30, 2011 at 2:55 pm

          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.

           
  6. bharghav August 30, 2011 at 11:31 pm

    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.

     
    • James September 3, 2011 at 11:11 am

      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.

       
  7. Gautham September 5, 2011 at 3:34 pm

    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.

     
    • James September 5, 2011 at 9:25 pm

      No check the LogCat for the problem. It is most probably the problem in your side- Some reference error or null pointer exception.

       
  8. Gautham September 7, 2011 at 10:37 am

    Thing is ,i heard this “Not Responding” problem is common. So im not sure what to do.

     
  9. vasciquex September 9, 2011 at 12:00 pm

    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

     
    • James September 10, 2011 at 11:02 am

      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.

       
  10. vasciquex September 9, 2011 at 12:00 pm

    Sorry – failed to mention that it was from the first tutorial (http://coderzheaven.com/2011/04/android-phpmysql-connection/)

     
  11. RYS September 9, 2011 at 3:22 pm

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

     
    • James September 10, 2011 at 10:59 am

      OK RYS check your inbox soon

       
  12. vasciquex September 9, 2011 at 3:55 pm

    OR could anyone of you guys that have the app working, send me the WORKING application just delete the passwords?

     
  13. RYS September 12, 2011 at 12:15 pm

    Hi James, I still didn’t receive your attachment yet…i just received your message only. Can you please send for me again? Thanks~

     
  14. Reval September 22, 2011 at 9:46 pm

    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

     
  15. Skynight October 24, 2011 at 8:37 am

    After send to php side, nothing happens…any ideas ?

     
    • James October 24, 2011 at 8:55 pm

      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.

       
    • James October 31, 2011 at 11:15 pm

      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.

       
  16. Asraf October 31, 2011 at 5:53 pm

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

     
  17. Naveen October 31, 2011 at 7:05 pm

    Hi

    After clicking button, nothing happens,

    In my log it shows Exception:null

    I’m running php server.

    Any idea?

     
    • James October 31, 2011 at 11:14 pm

      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.

       
      • naveen November 1, 2011 at 11:37 am

        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?

         
        • James November 1, 2011 at 10:11 pm

          Naveen :- Check this link

           
        • James November 1, 2011 at 10:15 pm

          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.

           
      • naveen November 1, 2011 at 11:49 am

        Hi james

        How to get rid of
        Exception : android.os.NetworkOnMainThreadException null

        Exception is thrown while executing
        response=httpclient.execute(httppost);

        Pls help me

         
  18. Angelo November 24, 2011 at 5:02 pm

    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”

     
  19. krishnaveni December 27, 2011 at 1:51 pm

    Hi james,
    I have followed your this post..But when ever i click the button nothing is happening …what error is happened …

     
  20. radhika January 13, 2012 at 11:11 pm

    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 }

     
    • James January 15, 2012 at 10:25 pm

      check the logcat not the console.

       
  21. radhika January 13, 2012 at 11:13 pm

    basically i m creating a login page which verifies it with my mysql database. but even this much is not working.. pls help..

     
    • James January 15, 2012 at 10:24 pm

      @radhinka:- what help do you need?

       
  22. sanjeev February 14, 2012 at 1:54 pm

    Hi!!
    This tutorial is very useful for beginners like me

     
  23. Kennedy February 17, 2012 at 7:23 pm

    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.

     
  24. krishna kumar February 27, 2012 at 9:31 pm

    hi how to received(android) array list from php help me pls

     
    • James February 27, 2012 at 10:33 pm

      Make it as a string with some delimiter in between and split it in the android side.

       
  25. Pingback: Android phpMysql connection | Coderz Heaven

  26. janam March 14, 2012 at 2:16 pm

    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.

     
    • James March 14, 2012 at 7:55 pm

      Check whether you have added the permission in the manifest file.

       
  27. janam March 15, 2012 at 11:49 am

    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.

     
  28. janam March 15, 2012 at 1:53 pm

    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);
    }

     
  29. Pingback: How to create Simple Login form using php in android? - Connect php with android.

  30. Heloise April 25, 2012 at 10:11 am

    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

     
    • James April 25, 2012 at 2:36 pm

      Hey Heliose, People like you are always welcome. This is what the site’s name means.

       
  31. B September 16, 2012 at 4:31 pm

    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 🙂

     
  32. Pingback: How to get table values from a MySQL database and show it in Android as Tables.?

  33. Sridhar November 5, 2012 at 6:21 am

    my server is not accessing..the dialog blink and it disappers….

     
  34. peter November 19, 2012 at 7:03 pm

    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!

     
  35. Harsh October 24, 2013 at 6:13 pm

    hey, thanks for your code….
    In httpPost URL have written 10.0.0.2 in stand of 10.0.2.2
    Cheers!!

     
  36. syam November 1, 2013 at 11:56 am

    Hello I getting Undefined index :Edittext_value

     
  37. syam November 1, 2013 at 12:02 pm

    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)

     
  38. Vaibhavraj January 28, 2014 at 7:31 pm

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

     
  39. Ali March 7, 2014 at 5:39 pm

    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

     
    • James March 22, 2014 at 4:49 pm

      Get it from the ResolveInfo.

       
  40. Sonam March 9, 2014 at 9:06 pm

    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 !

     

Leave a Reply

Your email address will not be published. Required fields are marked *

 

 

 

Theme by HermesThemes

Copyright © 2018 CoderzHeaven. All Rights Reserved

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.