Android - Pulling Data from MySQL server using PHP - java

Here my code:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year","1980"));
InputStream is = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("dropbox link to php code");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
System.out.println(is);
}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();
System.out.println("1 " + result);
}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);
Log.i("log_tag","id: "+json_data.getInt("id")+
", name: "+json_data.getString("name")+
", sex: "+json_data.getInt("sex")+
", birthyear: "+json_data.getInt("birthyear")
);
}
}
catch (JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
The link in the HTTPPost is a download link to the PHP code on Dropbox. That code looks like this:
<?php
mysql_connect("host","username","password");
mysql_select_db("1487057_test");
$q=mysql_query("SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close();
?>
The problem is that the PHP code does not seem to be "executed" by the HTTPClient. When I do a print of the input stream, I just get back the first two lines of the PHP code. The JSON log does not seem to print at all. Anyone see what's wrong?

If you have the json data from ftp server it will work fine, since u r
using dropbox for php file, u need to make sure that it works, would
suggest you to test service on browser first if it works fine then u
can move ahead with code.possibly setup the ftp instead of Dropbox as
file server.

modify your PHP to something like:
<?php
$sql = "SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'";
mysql_query("set names utf8");
$result = mysql_query($sql);
while ($e = mysql_fetch_assoc($result)) {
$output[]=$e;
}
print(json_encode($output));
mysql_close($dbhost);
?>

Related

Java (Android) HTTP Post to PHP Page

This is for an Android application ,where my mobile developer is trying to post json data to my PHP page .
Below is the function that is being used :
public static String postData(String url, String postData) {
// Create a new HttpClient and Post Header
InputStream is = null;
StringBuilder sb = null;
String result = "";
// StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
// StrictMode.setThreadPolicy(policy);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
httppost.setEntity(new StringEntity(postData));
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
// Execute HTTP Post Request
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());
//throw new CustomException("Could not establish network connection");
}
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");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
//throw new CustomException("Error parsing the response");
}
return result;
}
Where url is the link to my php webpage . On my php page , i am just trying to print out the posted data by doing :
print_r($_POST);
But it shows an empty array . I even tried using the REST addon for firefox and doing the same but it simply shows a blank array .
Would be great if someone could point out if i am missing anything .
Thanks.
you need to get the json content like below :
if(isset($_POST))
{
$json = file_get_contents('php://input');
$jsonObj = json_decode($json);
echo $jsonObj;
}

Connecting android to mySQL using php and JSON

I'm trying to create an android application that connects to mySQL database through php and JSON.
THis is my php file on the server:
<?php
$host="my_host";
$username="my_name";
$password="my_password";
$db_name="my_db_name";
$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "SELECT UserID, DisplayName
FROM User
WHERE (UserName LIKE '%it%') OR (DisplayName LIKE '%it%')";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['UserRes'][]=$row;
}
}
mysql_close($con);
echo json_encode($json);
?>
And this is my JSON java class code:
public class JSONClass extends AsyncTask<String,Void,String>{
public HashMap<String, String> tbl = new HashMap<String, String>();
private Context context;
public JSONClass(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... arg0) {
try{
String link = "some url";
URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
}
I'm new with this and just want to get the basics and work from there. The php file should return one row as an answer, but as far as I can figure it out, the function falls in the try - catch part. I know that the result should come as HashMap. Can someone please tell me what I'm doing wrong or give me a tip to get the result? Thank you in advance!
This is how you fetch data from url, where url below is the web address of your PHP script:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.addHeader("Content-Type", "application/x-www-form-urlencoded");
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "utf-8");
JSONArray ja = new JSONArray(result);
for(int i = 0 ; i < ja.length() ; i++){
String name = ja.getJSONObject(i).getString("name"); //write name of column
}

Cannot receive post parameters in php from android?

I am sending data from android to php script using json object as follows:
jobj.put("uname", userName);
jobj.put("password", passWord);
JSONObject re = JSONParser.doPost(url, jobj);
Then the doPost() method is as follows:
public static JSONObject doPost(String url, JSONObject c) throws ClientProtocolException, IOException
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
HttpEntity entity;
StringEntity s = new StringEntity(c.toString());
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
entity = s;
request.setEntity(entity);
HttpResponse response;
try{
Log.v("Request",""+request);
response = httpclient.execute(request);
//Log.v("response",""+response);
HttpEntity httpEntity = response.getEntity();
is = httpEntity.getContent();
}
catch(Exception e){
Log.v("Error in response",""+e.getMessage());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
//Log.v("Reader",""+reader.readLine());
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
//Log.v("response",sb.toString());
is.close();
json = sb.toString();
Log.v("response",json);
} catch (Exception e) {
Log.v("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (Exception e) {
Log.v("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
I have a php script which validates the input as follows:
$response = array();
$con=mysqli_connect("localhost","user","password","manage");
if((isset($_POST['uname']) && isset($_POST['password']))){
$empid = $_POST['uname'];
$pass = $_POST['password']);
$query = "SELECT empid,password FROM master WHERE mm_emp_id='".mysql_real_escape_string($empid)."' and mm_password='".mysql_real_escape_string($pass)."'";
$result = mysqli_query($con, $query);
if($result->num_rows != 0){
$response["success"] = 1;
$response["message"] = "";
print_r(json_encode($response));
}
else{
$response["success"] = 0;
$response["message"] = "The username/password does not match";
print_r(json_encode($response));
}
}
The problem is the isset() does not catch the uname key and I get undefined index for 'uname' and 'password' key. As you can see the json object is converted to string and added as String entity to the request. I cannot figure out what have I been doing wrong that the $_post is not receiving the values.
Please do suggest on what I have been doing so that i can receive the parameters in my php script.
you are posting data as application/json from android so you can access data in php with:
$post_data = json_decode(file_get_contents('php://input'));

JSONArray is empty

I read data from a database (only the last row, I do it in my php file) what I want to do is to use the data of each field separately but the problem is that the JSONArray is empty I tried a lot of ways to do it looking for it in different posts but it´s always empty.
This is my code
public class MainActivity extends Activity {
/** Called when the activity is first created. */
JSONArray jArray = null;
String result = null;
InputStream is = null;
StringBuilder sb=null;
String ct_id;
String ct_name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost= new HttpPost("http://xxx.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);
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());
}
//paring data
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
ct_id=json_data.getString("fecha");
ct_name=json_data.getString("dia");
}
}
catch(JSONException e1){
Toast.makeText(getBaseContext(), "JSON is empty" ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
}
}
It always catchs JSONException e1.
Thank you everibody in advance
Check returned string in result. Probably there are not only json structure(errors, warning, etc..). JSON spellchecker: http://jsonlint.com/
after checking the json response; better to try using GSON, much more convenient;
JsonParser jsonParser = new JsonParser();
JsonArray jArray;
if ( jsonParser.parse(result).isJsonArray() ) {
jArray = jsonParser.parse(result).getAsJsonArray();
}
else { jArray = new JsonArray(); }
The problem was in PHP file, JSON couldn´t understand the data and that is why it was empty, I changed it and now works properly.

Android, connecting to MySQL using PHP

I am trying to connect to MySQL DB using php script. But I don't get any output only exception code. I can't figure it out where is the problem. I used a tutorial code.
private EditText outputStream;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String result = null;
InputStream input = null;
StringBuilder sbuilder = null;
outputStream = (EditText)findViewById(R.id.output);
ArrayList <NameValuePair> nameValuePairs = new ArrayList <NameValuePair>();
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://ik.su.lt/~jbarzelis/Bandymas/index.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
input = entity.getContent();
}
catch(Exception e){
Log.e("log_tag","Error in internet connection"+e.toString());
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(input,"iso-8859-1"),8);
sbuilder = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
sbuilder.append(line + "\n");
System.out.println(line);
}
input.close();
result = sbuilder.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
int fd_id;
String fd_name;
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data = null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
fd_id = json_data.getInt("FOOD_ID");
fd_name = json_data.getString("FOOD_NAME");
outputStream.append(fd_id +" " + fd_name + "\n");
}
}
catch(JSONException e1){
Toast.makeText(getBaseContext(), "No food found", Toast.LENGTH_LONG).show();
}
catch(ParseException e1){
e1.printStackTrace();
}
}
PHP script:
<?php
mysql_connect("localhost","**********","******");
mysql_select_db("test");
$sql = mysql_query("select FOOD_NAME as 'Maistas' from FOOD where FOOD_NAME like 'A%'");
while($row = mysql_fetch_assoc($sql)) $output[]=$row;
print(json_encode($output));
mysql_close;
?>
Any ideas how to fix it?
First, dont use Exception.toString(), use Exception.printStackTrace():
catch (Exception e) {
e.printStackTrace();
}
Second, in your PHP code, your not checking for any errors. If any errors occur, I suggest you issue a different HTTP status code (like 400), then, in your Android code:
if (response.getStatusLine().getStatusCode() != 200) {
Log.d("MyApp", "Server encountered an error.);
}
This way you will know if something happened on the server.
Hope this helps

Categories

Resources