I have a problem connecting database with Android app. I am trying to implement this tutorial. Everything seems to be fine but I neither get any success not an error.
There is a button listener which on clicking does a post to a PHP file and gets the result. Here is the code for it:-
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", un.getText().toString()));
postParameters.add(new BasicNameValuePair("password", pw.getText().toString()));
//String valid = "1";
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://10.0.2.2/check.php", postParameters);
String res=response.toString();
Log.d("res:", res);
// res = res.trim();
res= res.replaceAll("\\s+","");
//error.setText(res);
if(res.equals("1"))
error.setText("Correct Username or Password");
else
error.setText("Sorry!! Incorrect Username or Password");
} catch (Exception e) {
un.setText(e.toString());
}
}
});
Here is the http post method:-
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
Log.d("postMethodReturn", result);
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The PHP code is as below:-
<?php
$un=$_POST['username'];
$pw=$_POST['password'];
//connect to the db
$user = "xyz";
$pswd = "xyz";
$db = "mydb";
$host = "localhost";
$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db);
//run the query to search for the username and password the match
$query = "SELECT * FROM mytable WHERE user = '$un' AND pass = '$pw'";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
//this is where the actual verification happens
if(mysql_num_rows($result) --> 0)
echo 1; // for correct login response
else
echo 0; // for incorrect login response
?>
Is there any bug in the program? I tried logging the intermediate values of res (http response) in activity code and result in the execute post method, but nothing is being logged. Tried changing "localhost" to "127.0.0.1" and also into a publicly available webhost, with all the database environment, but no success. All these on emulator and with public host, tried with real device too. Server seems to be running when checked from browser. Database exists with the values. All services running (apache, mysql).
The main problem is that there is no error! Any suggestions what is going wrong?
Couldn't find anyone with the same problem.
the problem was --> in the PHP code. changed it to == or > and everything works fine!
Related
I need to read data from an external database with hundreds of items. What I did so far is that I wrote the php query which returns all the items, so for i have done
php:
$db_host = "host";
$db_uid = "username";
$db_pass = "password";
$db_name = "person";
$db_con = mysql_connect($db_host,$db_uid,$db_pass) or die('could not connect');
mysql_select_db($db_name);
$sql = "SELECT * FROM employee ";
$result = mysql_query($sql);
while($row=mysql_fetch_assoc($result))
$output[]=$row;
print(json_encode($output));
mysql_close();
android:
String url = "http://localhost/index.php";
#Override
public void onCreate(Bundle savedInstanceState) {
/*
* StrictMode is most commonly used to catch accidental disk or network
* access on the application's main thread
*/
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork()
.penaltyLog().build());
super.onCreate(savedInstanceState);
setContentView(R.layout.hospital);
byear = (EditText) findViewById(R.id.editText1);
submit = (Button) findViewById(R.id.submitbutton);
tv = (TextView) findViewById(R.id.showresult);
// define the action when user clicks on submit button
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// declare parameters that are passed to PHP script i.e. the
// name "birthyear" and its value submitted by user
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
data = byear.getText().toString();
// define the parameter
postParameters.add(new BasicNameValuePair("data", data));
String response = null;
// call executeHttpPost method passing necessary parameters
try {
response = CustomHttpClient.executeHttpPost(
url,
postParameters);
// store the result returned by PHP script that runs
// MySQL query
String result = response.toString();
// parse json data
try {
returnString = "";
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag", "id: " + json_data.getInt("id")
+ ", name: " + json_data.getString("name")
);
// Get an output to the screen
returnString += "\n" + "Name ="
+ json_data.getString("name") + "\n"
+ "Contact number = "
+ json_data.getInt("contact") + "\n"
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
try {
tv.setText(returnString);
} catch (Exception e) {
Log.e("log_tag", "Error in Display!" + e.toString());
;
}
} catch (Exception e) {
Log.e("log_tag",
"Error in http connection!!" + e.toString());
}
}
});
}
}
My question is how can I pass the data from edit text android to php query so the query will only return the proper items only
To send data to php use postParameters :
postParameters.add(new BasicNameValuePairs("id",data));
In your php script add
if(isset($_POST['id']){
var id = $_POST['id'];
// do db operation here
}
with id = your data id and data = your data.
$var_data=$_REQUEST['data'];
print($var_data);
use above 2 lines in your php code at line number 1 so it will print android data associated with key "data"
postParameters.add(new BasicNameValuePair("data", data));
First you have to write respective php script Then you can use this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://Your Url");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("uid",username));
nameValuePairs.add(new BasicNameValuePair("filename",filename));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Make sure that the field name in your table in server side is "uid" and "filename" respectively.
For more information see this.
Hi,
i use this class to make a request to server, which consist of the json data object.
Class is:-
public class HttpClient {
private static String URL = "localhost/json/json_handle.php";
public String postJsonData(String data) {
try {
StringBuffer buffer = new StringBuffer();
// Apache HTTP Reqeust
System.out.println("Sending data..");
System.out.println("Data: [" + data + "]");
org.apache.http.client.HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
List<NameValuePair> nvList = new ArrayList<NameValuePair>();
BasicNameValuePair bnvp = new BasicNameValuePair("json", data.toString());
// We can add more
nvList.add(bnvp);
post.setEntity(new UrlEncodedFormEntity(nvList));
HttpResponse resp = client.execute(post);
// We read the response
InputStream is = resp.getEntity().getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line + "\n");
}
is.close();
buffer.append(str.toString());
// Done!
return buffer.toString();
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}
}
Then i use a php class on server side to get the json object from the request. But, at server side i am getting nothing. Even when i use $_REQUEST method, then code after this method doesn't work.
Here is my php file:-
<?php
$file = fopen("MyFile.txt" ,"w");
$int = $_REQUEST;
fwrite($file,"aaa");
//$input =$_REQUEST['json'];
fwrite($file,"HELLO 111");
//$data = json_decode($input,true);
/*print_r($input);
// get values
$firstname = $input->firstName;
$surename = $input->lastName;
$age = intval($input->age);
// check values
if (isset($firstname) && !empty($firstname) &&
isset($surename) && !empty($surename) &&
isset($age) && is_numeric($age))
{
// do something
echo "Hello ".htmlspecialchars($firstname)." ".htmlspecialchars($surename)."!<br>";
echo "You are $age years old! Wow.";
}
else
{
echo "Some values are missing or incorrect";
}*/
//fwrite($file, $data);
fclose($file);
?>
Any suggestions regarding this problem???
Thanks friends for your help.
I got the solution and now the program is working perfectly on localhost as well as online.
For localhost, we just have to give the URL as:-
1.1.1.1/json/json_handle.php
where 1.1.1.1 is your ip address.
Again, thanks alot friends.
I have written PHP code to fetch data from Database. It get the login values. (username & password). I connect it through mysql server/localhost. when I run this PHP code it always show the "0". It means it doesn't get the data from Database. Why is that?
Here my PHP code:
<?php
$hostname_localhost ="localhost";
$database_localhost ="gpsvts_geotrack";
$username_localhost ="root";
$password_localhost ="";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_localhost, $localhost);
$username = $_POST['uname'];
$password = $_POST['passwd'];
$query_search = "select 'uname' & 'passwd' from user_master where uname = '.$username.' AND passwd = '.$password.'";
$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";
}
?>
I put this in my wamp server www folder.when i run this php file wamp server localhost it always say "no such user found".
i used this php file for fetching data from db to connect android login form. it contain two fields. which are username & password.
here I give my android login code.
b = (Button)findViewById(R.id.Button01);
et = (EditText)findViewById(R.id.username);
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(AndroidPHPConnectionDemo.this, "",
"Validating user...", true);
new Thread(new Runnable() {
public void run() {
login();
}
}).start();
}
});
}
void login(){
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://10.0.2.2//new/nuwan1.php"); // make sure the url is correct.
//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("username",et.getText().toString().trim())); // $Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(new BasicNameValuePair("password",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(AndroidPHPConnectionDemo.this,"Login Success", Toast.LENGTH_SHORT).show();
}
});
startActivity(new Intent(AndroidPHPConnectionDemo.this, UserPage.class));
}else{
showAlert();
}
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
public void showAlert(){
AndroidPHPConnectionDemo.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(AndroidPHPConnectionDemo.this);
builder.setTitle("Login 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();
}
});
}
Always I got the alart no such user found & php response is No such user found
why is that?
pls help me.
I used following php code
<?php
$un=$_POST['uname'];
$pw=$_POST['passwd'];
//connect to the db
$host="localhost"; // Host name
$user="root"; // Mysql username
$pswd=""; // Mysql password
$db="gpsvts_geotrack"; // Database name
$tbl_name="user_master"; // Table name
$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db, $conn);
//run the query to search for the username and password the match
$query = "SELECT * FROM $tbl_name WHERE uname = '$un' AND passwd= '$pw'";
//$query = "SELECT uid FROM $tbl_name WHERE uname = '$un' AND passwd = '$pw'";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
//this is where the actual verification happens
if(mysql_num_rows($result) > 0)
echo mysql_result($result,0); // for correct login response
else
echo 0; // for incorrect login response
?>
Then return uid as response. but not validating user. Is there PHP code wrong or android code wrong. I want to match the values user enter & database get. Is that happen in here.
if not give me correct thing.
In your program you are passing from your side is:
nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim())); // $Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(new BasicNameValuePair("password",pass.getText().toString().trim()));
And you are trying to fetch from PHP side is:
$un=$_POST['uname'];
$pw=$_POST['passwd'];
So Change The Name in nameValuePairs are passed with this:
nameValuePairs.add(new BasicNameValuePair("uname",et.getText().toString().trim())); // $Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(new BasicNameValuePair("passwd",pass.getText().toString().trim()));
If I'm not mistaken it should be like this because your post variables are spelled different than what you're putting in the name value pairs.
nameValuePairs.add(new BasicNameValuePair("uname",et.getText().toString().trim())); // $Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(new BasicNameValuePair("passwd",pass.getText().toString().trim()));
I could really need some help to my project.
I have an android app, that scans for wireless networks. I want to upload this data to a mysql database.
Android have database class:
public class Database {
public static void putServerData(String building, String floor, String room, String address, String signal){
String db_url = "http://**(IP ADDRESS)**/setdata.php";
#SuppressWarnings("unused")
InputStream is = null;
ArrayList<NameValuePair> request = new ArrayList<NameValuePair>();
request.add(new BasicNameValuePair("building",building));
request.add(new BasicNameValuePair("floor",floor));
request.add(new BasicNameValuePair("room",room));
request.add(new BasicNameValuePair("address",address));
request.add(new BasicNameValuePair("signal",signal));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(db_url);
httppost.setEntity(new UrlEncodedFormEntity(request));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
}
}
This is called by:
try {
Database.putServerData(building,floor, room, array1.get(1).toString(), array2.get(2).toString());
} catch (Exception e) {
Log.e("test", "test");
}
The server is a Win7 machine, with apache php and mysql
The setdata.php file:
<?php
$con = mysql_connect("localhost","root","pass");
if(!$con)
{
echo 'Not connected';
echo ' - ';
}else
{
echo 'Connection Established';
echo ' - ';
}
$db = mysql_select_db("android");
if(!$db)
{
echo 'No database selected';
}else
{
echo 'Database selected';
}
$building = $_POST['building'];
$floor = $_POST['floor'];
$room = $_POST['room'];
$ap_mac1 = $_POST['ap_mac1'];
$ap_strength1 = $_POST['ap_strength1'];
$ap_mac2 = $_POST['ap_mac2'];
$ap_strength2 = $_POST['ap_strength2'];
$ap_mac3 = $_POST['ap_mac3'];
$ap_strength3 = $_POST['ap_strength3'];
$ap_mac4 = $_POST['ap_mac4'];
$ap_strength4 = $_POST['ap_strength4'];
$ap_mac5 = $_POST['ap_mac5'];
$ap_strength5 = $_POST['ap_strength5'];
echo ($_POST['building']);
mysql_query("INSERT INTO wifiscan VALUES($nextid, '$building','$floor','$room','$ap_mac1','$ap_strength1','$ap_mac2','$ap_strength2', '$ap_mac3', '$ap_strength3', '$ap_mac4', '$ap_strength4', '$ap_mac5', '$ap_strength5')");
mysql_close(); ?>
This is not working. Im not sure i select the database in the correct way, could that be the problem?
Maybe this isnt so clear and ill will explain it further if you want.
Use some Log and maybe sprintfs to figure out what is exactly going on.
I#d start with the PHP. Try to open the URL from your browser and put some outputs in the PHP to see if everything works fine here. Post your results and you will probably get further help.
I have an application which gets some data from a remote database.
I use PHP with the following code to connect to the data base.
mysql_connect($host,$username,$password) or die( "no connection");
#mysql_select_db($database) or die( "Unable to select database");
$query = $_REQUEST['query'];
$q=mysql_query($query);
while($e=mysql_fetch_assoc($q)) {
$output[]=$e;
}
print(json_encode($output));
mysql_close();
I then connect via following java code
public void connect(ArrayList<NameValuePair> nameValuePairs) {
result = "";
InputStream is = null;
String url = "http://'ipadress'/PhpProject1/EmptyPHP.php";
//Get the content
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("Connect", "Error in http connection " + e.toString());
}
//Convert content toString
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, HTTP.UTF_8), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
//result = replaceString(sb.toString());
} catch (Exception e) {
Log.e("Connect", "Error converting result " + e.toString());
}
}
When i have done that I make a query through
public void query(String query){
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("query", query));
connect(nameValuePairs);
}
While this works great with the emulator there is a problem when using it on the phone.
Anyone has a clue why this is?
Thank you in advance
Make sure to connect your real device to the your private network to actually be able to access that server.
Easiest option would be a WiFi network in the same subnet as the server. Otherwise your phone won't be able to access the network as it is not public.