Error in connecting with Php app in Android - php

Here is my code to send the data from android app to php app which is running in my localhost. It is showing "Connection to http:// localhost refused" . Please help me
public void postData() throws JSONException
{
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/xampp/FeelSafeSecurity/connectiondemo.php");
JSONObject json = new JSONObject();
try {
// prepare JSON data:
json.put("name", "santhosh");
json.put("age", "24");
JSONArray postjson=new JSONArray();
postjson.put(json);
// Post the data:
httppost.setHeader("json", json.toString());
httppost.getParams().setParameter("jsonpost",postjson);
// Execute HTTP Post Request
System.out.print(json);
HttpResponse response = httpclient.execute(httppost);
// for JSON:
if(response != null)
{
InputStream is = response.getEntity().getContent();
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();
}
}
text = sb.toString();
}
tv.setText(text);
}
catch (ClientProtocolException e)
{
System.out.println(e.getMessage());
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
And here is my php code to receive the data. I'am new to PHP.
<?php
$json = $_SERVER['HTTP_JSON'];
echo "JSON: \n";
echo "--------------\n";
var_dump($json);
echo "\n\n";
$data = json_decode($json);
echo "Array: \n";
echo "--------------\n";
var_dump($data);
echo "\n\n";
echo "Result: \n";
echo "--------------\n";
echo "\n\nName : ".$data->name."\n\n Age : ".$data->age;
?>

Don't use localhost use your IP address. Localhost is only for the LOCAL server

localhost means the local machine on which the app executes. In your case either amdroid device or the emulator virtual machine. Neither of which is running your php server.
So, if you run this on device you must use the IP of the machine where php code is running.
If you are trying this on emulator and you host machine runs the php code then you might try 10.0.2.2 as described in emulator network addressing.

Related

how to send data from php to android not using json

i using httpPost method to send data from android to php.
Now i am want to send data from php to android ?
i need the simple and flexible method like: httpPost, but there from php to android
not from android to php
how it ?
Your PHP can just print whatever you want. It can be as simple as
<?php
print("This is my return value");
JSON is a common format, but it can be anything. Below is an complete java example of reading the PHP script's value.
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = null;
httppost = new HttpPost("www.myURL.com");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection" + e.toString());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
sb.deleteCharAt(sb.length() - 1);
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}

How to get a variable from php to android?

I have been searching everywhere this question and the only answer i've seen is JSON! I feel there is also other ways to do this.
My problem is i can post data from android to php script to insert data to my server. But what i want to do is get some data from my php to android. (without using JSON).
Please, i'm still in the basics. Make this as simple as possible!
Here's my php script:
<?php
$con=mysqli_connect("HOST", "USER", "PASSWORD", "DB_NAME");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$tablenamep = $_POST["tablenamep"];
$stringp = $_POST["stringp"];
$val = mysqli_query($con, "DESCRIBE `$tablenamep`");
if($val == TRUE) {
echo "Table exists";
$stringp = "This ID already exists. Try again!";
} else {
echo "Table does not exist";
mysqli_query($con, "CREATE TABLE ".$tablenamep." ( name VARCHAR(30), number INT, email VARCHAR(30))");
$stringp = "Your ID is available";
}
mysqli_close($con);
?>
This is how i used my java class to post data to php script.
public void CONNECT_SERVER(){
String msg = etID.getText().toString();
if (msg.length()>0){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://myfile.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("tablenamep", msg));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
} else {
Toast.makeText(getBaseContext(),"All field are required",Toast.LENGTH_SHORT).show(); }
}
The php script and android app is working FINE, no errors! Now i can add the data from my android app to the php script. NO PROBLEMS TILL NOW!
BUT WHAT I WANT, is to get the $stringp variable from the php script above to my android app after executing the script. In other words i want my app to know whether the ID exists or not.
I have already checked many forums regarding this question. SOLVE THIS PROBLEM WITHOUT JSON.
You must use json or other parsing method to retrieve data from server
try this
contact.php
<?php
mysql_connect ("localhost","root","");
mysql_select_db("meetapp");
$output=array();
$q=mysql_query("SELECT `app_id` FROM `registration`");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print (json_encode($output));
mysql_close();
?>
in your java code
try {
HttpClient httpclient2 = new DefaultHttpClient();
HttpPost httppost2 = new HttpPost("http://10.0.2.2:80/contact.php");
HttpResponse response2 = httpclient2.execute(httppost2);
HttpEntity entity2 = response2.getEntity();
is2 = entity2.getContent();
Log.e("log_tag", "connection success ");
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection "+e.toString());
}
try
{
BufferedReader reader2 = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb2 = new StringBuilder();
String line = null;
while ((line = reader2.readLine()) != null)
{
sb2.append(line + "\n");
}
is.close();
result3=sb2.toString();
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
}
try
{
JSONArray jArray2 = new JSONArray(result3);
String s11;
Log.w("Lengh",""+jArray2.length());
for(int i=0;i<jArray2.length();i++){
JSONObject json_data2 = jArray2.getJSONObject(i);
s11=json_data2.getString("app_id");
}
}
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
}

android app wrote to get place name of id 2 php gives null

I was trying out this code but it gives null. where it should be giving me the place name. what seems to be the problem in my code? i want to get place details by giving the place ID. But i debugged too, it was always returning null
Code
String result = "";
InputStream is = null;
// the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("place_id", "2"));
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://example.com/getAllPeopleBornAfter.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
TextView z = (TextView)findViewById(R.id.textView1);
z.setText(json_data.getString("place_id"));
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
});
PHP
<?php
include "db_config.php";
$q=mysql_query("SELECT 'name' FROM places WHERE place_id='".$_REQUEST['place_id']."'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close();
?>
Too less information to help. Are you sure your PHP script returns anything? What logging of http response shows? Maybe it is all fine with your code and null is what you should get as problem lurks elsewhere?
BTW: your PHP code is very bad. You are open to exploitation with SQL Injection and in general you should always check if query (or fopen or anything) succeeded before you try to consume expected data it should return, as there is NO guarantee all went fine. Habit of error checking is crucial to solid software development. I also recomment to not use "?>" if it is just pure PHP script file, not mixed with HTML or anything (mixing is bad too).
THIS IS THE ANSWER
ref.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String result = "";
InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("place_id", "3"));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://hopscriber.com/test.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// parse json data
String version = null;
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
version = json_data.getString("name");
Toast.makeText(getBaseContext(), version,
Toast.LENGTH_LONG).show();
TextView x = (TextView) findViewById(R.id.textView1);
x.setText(version);
}
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), version, Toast.LENGTH_LONG)
.show();
} catch (ParseException e1) {
e1.printStackTrace();
}
}
});
php
<?php
include "db_config.php";
$query = mysql_query("SELECT * FROM places WHERE place_id='".mysql_real_escape_string($_POST[place_id])."'");
while($e=mysql_fetch_assoc($query))
$output[]=$e;
print(json_encode($output));
mysql_close();
?>
thanx all for the help

Sending Data From Android To Server with JSON data

I am trying sending data from Android application to web server. My android application is working successfully.However php code have problems.
<?php
$json = $_SERVER['HTTP_JSON'];
echo "JSON: \n";
var_dump($json);
echo "\n\n";
$data = json_decode($json,true);
echo "Array: \n";
var_dump($data);
echo "\n\n";
$name = $data['name'];
$pos = $data['position'];
echo "Result: \n";
echo "Name : ".$name."\n Position : ".$pos;
?>
Errors:
Notice: Undefined index: HTTP_JSON in C:\wamp\www\jsonTest.php on line 2
( line 2 : $json = $_SERVER['HTTP_JSON']; )
I couldn't find these problems reason. Can you help me ?
( note: I am using wamp server )
Here is the relevant Android source:
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("10.0.2.2:90/jsonTest.php";);
JSONObject json = new JSONObject();
try {
json.put("name", "flower");
json.put("position", "student");
JSONArray postjson=new JSONArray();
postjson.put(json);
httppost.setHeader("json",json.toString());
httppost.getParams().setParameter("jsonpost",postjson);
System.out.print(json);
HttpResponse response = httpclient.execute(httppost);
if(response != null)
{
InputStream is = response.getEntity().getContent();
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();
}
}
text = sb.toString();
}
tv.setText(text);
}catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
This code works successfully on android side(no error). But php side has problems..
Thanks.
This isn't where your JSON is:
$json = $_SERVER['HTTP_JSON'];
You possibly meant:
$json = $_POST['HTTP_JSON'];
Where HTTP_JSON is the POST variable name you gave to your JSON in your Android app.
The rest of the errors stem from the fact that json_decode is failing because you're not successfully reading the JSON data from the request. You can check the response of json_decode to check if it was successful as follows:
$data = json_decode($json,true);
if( $data === NULL)
{
exit( 'Could not decode JSON');
}
Finally, passing true as the second parameter to json_encode means it will return an associative array, so you'd access elements like so:
$name = $data['name'];
$pos = $data['position'];
Make sure you read the docs for json_encode so you understand what it's doing.
Edit: Your problem is that you're accessing the $_POST parameter by the wrong name. You should be using:
$json = $_POST['jsonpost'];
Since the following line names the parameter "jsonpost":
httppost.getParams().setParameter("jsonpost",postjson);
Since I don't know how the java client sends the request
I would try :
print_r($_SERVER);
print_r($_GET);
print_r($_POST);
To figure out how it does.
try these lines:
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");

Android mysql php problem

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.

Categories