Question

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<NameValuePair> 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<NameValuePair>(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<String> 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();               
        }
        });
  }
}

Response generating php file

<?php
$hostname_localhost ="url";
$database_localhost ="databasename";
$username_localhost ="myusername";
$password_localhost ="xxxx";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
 or
trigger_error(mysql_error(),E_USER_ERROR);

mysql_select_db($database_localhost, $localhost);

$accno = $_POST['accno'];
$bpassword = $_POST['bpassword'];
$query_search = "select * from details where accno = '".$accno."' AND bpassword =      
'".$bpassword. "'";
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
//echo $rows;
if($rows == 0) { 
echo "No Such User Found"; 
}
else  {
echo "User Found"; 
}

?>

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 !

Was it helpful?

Solution

There's nothing complex going on here; your response is clearly just not saying "User Found"; so you should check that thoroughly.

Just attach your debugger, set a breakpoint at that line, and see what the response actually says in this case. It should be quite obvious what's amiss when you can pause there and step through/view the state of the various variables.

Alternately, you need to post the function that generates the response so we can see what it would return given your input. There isn't enough information here for us to fully diagnose the issue currently.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top