I am trying to connect an android application to a mysql database. The database “tardy_system” is running inside phpmyadmin provided by wamp server. we have a php file “login.php” located in C:/Wamp/www/Latepass functioning as our API backend. Its primary goal is to connect to the database and run queries to serve as parsed JSON data. Our java code within the android environment IS SUPPOSED TO connect to the index.php code. We are unable to connect the java code to the php api backend. The java code specifies to look in http://192.168.0.102:3306/Latepass/login.php for the file. This lan address is the current internal address for the wamp server and database. It is dynamic at the moment but we will eventually change it to a static ip. After we save and export the android apk and run it, UPON “Student Login” button click the java code initiates, however
Connection always fails.
The php code works and is reachable from any computer on the lan. We ran a test query (Everything starting with FOR DEBUGGINGONLY) and were able to read it from anywhere on the LAN across 2 browsers (Chrome and Firefox).
So the WAMP server is working – since we can connect to the php file across the network.
The PHP file is working – since it does execute a test query within the browsers.
Problem:
I think something is preventing the connection between the java code and the php code. We have tried disabling all firewalls (Hardware in the router and software in windows.) The JSON connection uses port 3306. There doesnt appear to be anything filtering that port.
My php code – Latepass/login.php
<?php
//turn off error reporting
error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING);
//connect to mySQL
$connect = mysql_connect("localhost", "root", "") or die(mysql_error("connection error 2"));
//Select the database
mysql_select_db("tardy_system")or die("database selection error");
//Retrieve the login details via POST
$username = $_POST['username'];
$password = $_POST['password'];
//Query the table android login
$query = mysql_query("SELECT * FROM students WHERE username='$username' AND password='$password'");
//check if there any results returned
$num = mysql_num_rows($query);
//If a record was found matching the details entered in the query
if($num == 1){
//Create a while loop that places the returned data into an array
while($list=mysql_fetch_assoc($query)){
//Store the returned data into a variable
$output = $list;
//encode the returned data in JSON format
echo json_encode($output);
}
//close the connection
mysql_close();
}
?>
StudentloginActivity
package com.android.upgrayeddapps.latepass;
import java.io.BufferedReader;
import java.io.IOException;
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.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class StudentLoginActivity extends Activity implements OnClickListener{
EditText etUsername;
EditText etPassword;
Button btnLogin;
//Create string variables that will have the input assigned to them
String strUsername;
String strPassword;
//Create a HTTPClient as the form container
HttpClient httpclient;
//Use HTTP POST method
HttpPost httppost;
//Create an array list for the input data to be sent
ArrayList<NameValuePair> nameValuePairs;
//Create a HTTP Response and HTTP Entity
HttpResponse response;
HttpEntity entity;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.studentlogin);
initialise();
}
private void initialise()
{
etUsername = (EditText) findViewById(R.id.txtbxStudentUsername);
etPassword = (EditText) findViewById(R.id.txtbxStudentLunchID);
btnLogin = (Button) findViewById(R.id.btnLoginStudent);
//Set onClickListener
btnLogin.setOnClickListener(this);
}
public void onClick(View v) {
//Create new default HTTPClient
httpclient = new DefaultHttpClient();
//Crate new HTTP POST with URL to php file as parameter
httppost = new HttpPost("http://192.168.0.102:3306/Latepass/login.php");
//Assign input text to strings
strUsername = etUsername.getText().toString();
strPassword = etPassword.getText().toString();
try{
//Create an Array List
nameValuePairs = new ArrayList<NameValuePair>();
//place them in an array list
nameValuePairs.add(new BasicNameValuePair("username", strUsername));
nameValuePairs.add(new BasicNameValuePair("password", strPassword));
//Add array list to http post
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//assign executed for container to response
response = httpclient.execute(httppost);
//check status code, need to check status code 200
if(response.getStatusLine().getStatusCode()== 200){
//assign response.getEntity()l
//check if entity is not null
if(entity !=null){
//create new input stream with received data assigned
InputStream instream = entity.getContent();
//Create a JSON Object. Assign converted data as parameter
JSONObject jsonResponse = new JSONObject(convertStreamToString(instream));
//Assign JSON responses to local strings
String retUser = jsonResponse.getString("username");//mySQL table field
String retPass = jsonResponse.getString("password");//mySQL table field
//Validate login
if(strUsername.equals(retUser)&& strPassword.equals(retPass)){
//Create a new shared preference by getting the preference
SharedPreferences sp = getSharedPreferences("logindetails",0);
//Edit the shared Preferences
SharedPreferences.Editor spedit = sp.edit();
//Put the login details as strings
spedit.putString("username", strUsername);
spedit.putString("password", strPassword);
//Close the editor
spedit.commit();
//Display a Toast saying login was a success
Toast.makeText(getBaseContext(), "Success!",Toast.LENGTH_SHORT).show();
} else{
//Display a Toast saying it failed
Toast.makeText(getBaseContext(), "Invalid Login Details", Toast.LENGTH_SHORT).show();
}
}
}
} catch(Exception e){
e.printStackTrace();
//Display Toast when there is a connection error
Toast.makeText(getBaseContext(), "Connection Error Android",Toast.LENGTH_SHORT).show();
Log.e("YourTag", e.getMessage(), e);
}
}//End try/Catch
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}//End ConvertStreamToString()
public void onGotoLatePassActiviy(View View)
{
Intent intent = new Intent(View.getContext(), LatePassActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
StudentLoginActivity.this.finish();
}
}
Question: Am i missing something in the configuration of wamp that does not allow my java code to reach the php code?
Currently i am getting a few apache errors which lead me to try to config it.
Today: Ran wireshark during the login process. Applied a tcp source and destination = 3306 filter. Got this transmission
A WAMP server listens on two ports: port 80 and port 3306. Port 80 is for the web server, port 3306 is for the database server.
You cannot connect to your web server (and PHP) over port 3306. You will hit the database server, which will promptly drop the connection once it realises the client is speaking a different protocol.
Example on my local machine:
The solution is to change the URL to http://192.168.0.102/Latepass/login.php
If this doesn’t work, ensure the web server is listening: in a command prompt type
netstat -a -n -p tcp. you should see something like this:If you don’t see that first line ending in :80, either apache isn’t listening or you’ve changed the port. See Apache’s logs for more details.