code works on emulator but not physical device - php

I have code that I'm trying to submit to a database, and the code works fine on an emulator but as soon as I move to an actual device the same code will no longer work. I think it has to do with the time() function in my php (I don't know what else it could be) but am I missing something obvious? this code on a physcial android device always throws "Oops! An error occurred." but on my emulator on my computer it works just fine. I've checked to make sure that I uploaded fresh copies of the project.
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['assemblyLotNumber']) && isset($_POST['assemblyID']) && isset($_POST['assemblerID']) && isset($_POST['quantity'])) {
$assemblyLotNumber = $_POST['assemblyLotNumber'];
$assemblyID = $_POST['assemblyID'];
$assemblerID = $_POST['assemblerID'];
$quantity = $_POST['quantity'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
$time = time();
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO assemblylot (assemblyLotNumber, assemblyID, assemblerID, date, isPremade, quantity) VALUES('$assemblyLotNumber', '$assemblyID', '$assemblerID', $time, 1, '$quantity')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "premade assembly successfully created.";
$response["date"] = $time;
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
$response["date"] = $time;
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
this is where I call it in the code
public void submitAssemblyLot(Assembly a) {
List<NameValuePair> assemblyParam = new ArrayList<NameValuePair>();
assemblyParam.add(new BasicNameValuePair("assemblyLotNumber", Integer.toString(a.getAssemblyLotNumber())));
assemblyParam.add(new BasicNameValuePair("assemblyID", Integer.toString(a.getAssemblyID())));
assemblyParam.add(new BasicNameValuePair("assemblerID", Integer.toString(a.getAssemblerID())));
try {
JSONObject json = jsonParser.makeHttpRequest(
url_submit_assembly_lot, "POST", assemblyParam);
String message = json.getString("message");
String date1 = json.getString("time");
Log.d("submitAssemblyLot", message);
Log.d("submitAssemblyLot", date1);
} catch (JSONException e) {
e.printStackTrace();
}
}

Related

App Can't Reach PHP file or Error in PHP File Android Studio

My app tries to create a new row in a server.
The error I get is Null Point Exception at jObj = new JSONObject(json);
This is the php file that creates a new row:
<?php
$response = array();
if (isset($_POST['user']) && isset($_POST['pass']) & isset($_POST['mail'])&& isset($_POST['num']))
{
$user = $_POST['user'];
$pass = $_POST['pass'];
$mail = $_POST['mail'];
$num = $_POST['num'];
require_once __DIR__ . '/db_connect2.php';
$db = new DB_CONNECT();
$result = $db->query("INSERT INTO users(Name, Password, Email,ConfirmNum) VALUES('$user', '$pass', '$mail', '$num')");
if ($result) {
$response["success"] = 1;
$response["message"] = "user successfully created.";
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "missing fields";
echo json_encode($response);
}
?>
The parser that requests for the update is:
package com.example.denis.onthego;
import android.content.ContentValues;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class JSONParser {
static JSONObject jObj;
static String json;
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public static JSONObject makeHttpRequest(String url, String method, ContentValues params) {
// Making HTTP request
try {
final OkHttpClient client = new OkHttpClient();
Request request;
// check for request method
if (method.equals("POST")) {
// request method is POST
MediaType contentType = MediaType.parse("application/x-www-form-urlencoded; charset=UTF-8");
String content = "";
for (String key : params.keySet())
{
if ( !content.isEmpty())
content += "&";
content += key + "=" + params.get(key);
}
RequestBody body = RequestBody.create(contentType, content);
request = new Request.Builder().url(url).post(body).build();
}
else {
// request method is GET
request = new Request.Builder().url(url).build();
}
final Response response = client.newCall(request).execute();
json = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e ){
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
And the call for the parser is :
JSONObject json = jsonParser.makeHttpRequest(url_create_product,"POST", params);
While the "add_user" is for the php file that makes a new row(It is the correct url) and "params" are not empty and contain the right keys and content.
Is there something wrong with the parser or the php file?
This is a very serious school project and this is the only thing I am missing.
Here are the params:
params.put("user", "swane15");
params.put("pass", "asdeg124A");
params.put("mail", "asf#asd.com");
params.put("num", "111111");
Why doesn't the php file return anything? Is because the app can't reach it or is there an error with the php file itself?
MediaType JSON = MediaType.parse("Content-Type:application/json; charset=UTF-8");
RequestBody body = RequestBody.create(JSON, params.toString());
Change to:
MediaType contentType = MediaType.parse("application/x-www-form-urlencoded; charset=UTF-8");
String content = "";
for (String key : params.keySet())
{
if ( !content.isEmpty())
content += "&";
content += key + "=" + params.get(key);
}
RequestBody body = RequestBody.create(contentType, content);
To do it right you should URLEncoder.encode() the values.

Send json object to local php server using HttpURLConnection

I am trying to send json object in android to local php server(XAMPP).
Here is my php script which recieves that object.
<?php
$response = array();
if (isset(($_POST['PNR_NO'])&&($_POST['Status'])&&($_POST['update_time']))){
$PNR_NO = $_POST['PNR_NO'];
$Status = $_POST['Status'];
$update_time = $_POST['update_time'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO pnr_database(PNR_NO, Status,update_time) VALUES('$PNR_NO', '$Status', '$update_time')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
// echoing JSON response
echo json_encode($response);
}
else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
}
else {
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
echo json_encode($response);
}?>
And the java code that i am using is :
#Override
protected Void doInBackground(String... urls) {
OutputStream os;
HttpURLConnection conn = null;
try {
//constants
String pnr = "1234";
String stat = "WC12";
String updTime = "13:20";
Log.i("aaaaa", "Started");
URL url = new URL(urls[0]);
JSONObject jsonObject = new JSONObject();
jsonObject.put("PNR_NO",pnr );
jsonObject.put("Status", stat);
jsonObject.put("update_time", updTime);
String message = jsonObject.toString();
System.out.println(message);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /*milliseconds*/);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(message.getBytes().length);
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
//open
conn.connect();
//setup send
os = new BufferedOutputStream(conn.getOutputStream());
os.write(message.getBytes());
Log.i("aaaaa","ended");
//clean up
os.flush();
}
catch (IOException e) {
e.printStackTrace();
}
catch (JSONException ex) {
ex.printStackTrace();
}
finally {
//clean up
/*try {
os.close();
is.close();
}
catch (IOException e) {
e.printStackTrace();
}
*/
conn.disconnect();
}
return null;
}
Basically I want to send data to my php server where I have created a database which has a table named pnr_database and the sent data should get stored in that table.I don't want any response from server.
But my code is not working...
I tested my php script from a html form where i was sending data to server... In that case php script was working fine and data was getting stored in database But i am not able to make it work in android.
This might be a little late answer. But the JSON you receive in php is encoded so you need to decode it as such in your if clause:
$decoded = json_decode($_POST, true); //this will return an array
$PNR_NO = $decoded['PNR_NO'];
$Status = $decoded['Status'];
$update_time = $decoded['update_time'];
Here you can enter the columns to your table.

Required Field(s) missing result

I'll just keep this question short. What is wrong with my php code, it keeps outputting 0 or Required Field(s) is missing. Here's the code
<?php
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['id']) && isset($_POST['status_id'])) {
$id = $_POST['id'];
$status_id = $_POST['status_id'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql update row with matched pid
$result = mysql_query("UPDATE pims_liip_pallet_purchase_order SET status = '$status_id' WHERE id = $id");
// check if row inserted or not
if ($result) {
// successfully updated
$response["success"] = 1;
$response["message"] = "Product successfully updated.";
// echoing JSON response
echo json_encode($response);
} else {
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
Here is the post data in my app
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String status_id = statusID.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("status_id", status_id));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
UPDATE_COMMENTS_URL, "POST", params);
// full json response
Log.d("Post Update", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Updated!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Update Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Any answers will be very much honored :D Thanks!
Your error says it all. Since you get to the } else { ... } bit, it means isset($_POST['id']) && isset($_POST['status_id']) is false.
In other words, your form is either:
not using POST, but GET. In that case add method="post" to your <form> tag. (actually, POST is default behaviour, so if this is the case, you probably have to remove or change method="GET" from the form tag)
and/or your form does not contain input fields with name="id" and/or name="status_id"
The updated question adds Android code. Hence this update:
I doubt that jsonParser.makeHttpRequest actually posts a form encoded json string. It more then likely will just POST json data to the webserver. PHP's $_POST will not automatically be filled with this data, since it only handles form encoded data.
You probably need to read this data from stdIn.
Try:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$rawPostData = file_get_contents("php://input");
$postData = (array)json_decode($rawPostData);
}
And then use $postData where you otherwise would use $_POST
Just debug the $_POST['id'] and $_POST['status_id'].
Before this line.
if (isset($_POST['id']) && isset($_POST['status_id'])) {
you will find answer automatically. Hopefully one of two post variables is not set.
For debug use print_r($_POST);

Inserting into mysql from android app

I am new to android development. As part of a bigger project I want to insert data from an android device to a web-server. So I did some research and articles like The article from androidhive and this article from codeproject were really helpful in trying to develop a test-app which inserts in to a mysql db, which is residing at a remote web-server.
Here is my android code
ConnectivityManager connMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xxxxxxxx.in/installment.php");
try{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", editTextCustomer.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("amount", editTextAmount.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
Log.i("postData", response.getStatusLine().toString());
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
}
else {
Toast.makeText(PayBillActivity.this, "Internet Access, Denied!!", Toast.LENGTH_LONG).show();
}
Here is the php code
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['name']) && isset($_POST['amount'])) {
$name = $_POST['name'];
$amount = $_POST['amount'];
$con=mysqli_connect("localhost","db_user","passwd","db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO installment (name, amount) VALUES ('$_POST[name]','$_POST[amount]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
// check if row inserted or not
if ($sql) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Installment made successfully";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
echo $result;
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
//$amount = 1000;
//echo $amount;
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
when I run the app, I am getting this "NetworkOnMainThreadException" exception and as a result no rows are being added. But its working perfect with HTML POST.
Can anyone tell me where the problem is in my code?
Thanks in advance!:)
I think if you spent the time you did on posting this question into google you may have got some good answers... Just to complete this question
There are two options available with you, either you can add a line of code and allow network operation on main thread, but its very very bad for your app and also as a coding style.
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
The longer option is to redesign the code to have the network operations performed in a separate thread. This is both good for the app and you will learn how to work on a multi-threaded program.
I think you should not use that strict or take it manually out of main..
Just use a smart premade lib and it is making all for you !
Download : http://loopj.com/android-async-http/
Note: And this lib is even using gzip to compress requests :)

Android sending data to php function

I havnt been able to find a guide on how to submit data to a database from android through php.
say for instance i have the following site:
function insert($var1) {
// mysql inserting a new row
$result = mysql_query("INSERT INTO report (name) VALUES ('$var1')");
// check if row inserted or not
if ($result) {
// successfully inserted into database;
$msg = "Message received.";
} else {
$msg = "Not received.";
}
return ($msg);
}
if (isset($_POST['name'])) {
$name = $_POST['name']);
insert($name);
} else {
echo "No input.";
}
How would i call this from my Android project?
You can refer to this tutorial but you do need a web-server for it.
Request mechanism Android App ----> webserver ------> database (mysql)
Respond mechanism Android App <---- webserver <------ database (mysql)
Android App will use JSON or other to get the data and display it
PHP Code
<?php
$con=mysql_connect("host","username");
if(!$con)
{
die("Could Not Connect".mysql_error());
}
$db="CREATE DATABASE login";
mysql_query($db,$con);
mysql_select_db("login",$con);
$tab="CREATE TABLE info(FirstName varchar(20),LastName varchar(20))";
mysql_query($tab,$con);
$user_fname=$_POST['fn'];
$user_lname=$_POST['ln'];
$row= mysql_query("INSERT INTO info (FirstName,LastName) VALUES('$user_fname', '$user_lname')");
if ($row) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
echo $row;
}
mysql_close($con);
?>
Sending the Data (Android)
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://127.0.0.1:4001/file.php");
List<NameValuePair> pair=new ArrayList<NameValuePair>(2);
pair.add(new BasicNameValuePair("fn",fname));
pair.add(new BasicNameValuePair("ln",lname));
httppost.setEntity(new UrlEncodedFormEntity(pair));
HttpResponse response = httpclient.execute(httppost);

Categories