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'));
Related
I'm trying to insert data into the database from my app. I can fetch data, but when I try to pass variables to my server, I get the "Required field(s) is missing" error.
I've done this before with a different app, but that was before I had SSL installed on my website. Is there any chance SSL could be stopping the variables.
I tried keeping the code as simple as possible for testing purposes but I just can't figure it out. I have re-done several tutorials just to make sure I'm not making errors, but clearly I'm going wrong somewhere. Any help much appreciated!
class CreateNewProduct extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewProductActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", "name"));
params.add(new BasicNameValuePair("price", "2"));
params.add(new BasicNameValuePair("imgurl", "imgurl"));
JSONObject json = jsonParser.makeHttpRequest("http://myserver.com",
"POST", params);
Log.d("Create Response", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
startActivity(i);
finish();
} else {
Log.d("TEST", "Failed to create product");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
PHP Code:
<?php
$response = array();
if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['imgurl'])) {
$name = "joey";
$price = "3";
$imgurl = "blowey";
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$result = mysqli_query("INSERT INTO products(name, price, imgurl) VALUES('$name', '$price', '$imgurl')");
if ($result) {
$response["success"] = 1;
$response["message"] = "Product 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"] = "Required field(s) is missing";
echo json_encode($response);
}
?>
JSON Parser:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// 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;
}
}
Try to replace:
post.setEntity(new UrlEncodedFormEntity(dataToSend));
with
post.setRequestBody(dataToSend);
I have login system, and i get NullPointerException after getting response or in process request generation. My login request is:
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(res == "sucess"){
pDialog.setMessage("Loading User Space");
pDialog.setTitle("Getting Data");
UserFunctions logout = new UserFunctions();
logout.logoutUser(getApplicationContext());
Intent upanel = new Intent(getApplicationContext(), Main.class);
upanel.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pDialog.dismiss();
startActivity(upanel);
finish();
}else{
pDialog.dismiss();
loginErrorMsg.setText("Incorrect username/password");
}
}
}
And login building is:
public JSONArray loginUser(String email, String password, String appkey) {
String conc = email + password + appkey;
JSONArray json = jsonParser.getJSONFromUrl(loginURL + "?login=" + email
+ "&password=" + password + "&sign=" + conc);
return json;
}
In the jsonParser i have this code:
public class JSONParser {
static InputStream is = null;
static JSONArray jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url) {
// Making HTTP request
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
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();
json = sb.toString();
// try parse the string to a JSON object
jObj = new JSONArray(json);
// return JSON String
return jObj;
}
}
By the way JSON response of the type:
{ "status": "success",
"message": "",
"session_id": "asdasddfcvxgdgfdfv",
"user":
[{ "company": "company",
"last_name": "last_nameĀ·",
"name": "name",
"middle_name": "middle_name",
"phone": "+1234567890",
"photo": "avatar.png" }] }
After this action i get error of "null values" like this:
Error converting result java.lang.NullPointerException: lock == null
Error parsing data org.json.JSONException: End of input at character 0 of
Try this way,hope this will help you to solve your problem.
public JSONObject getJSONFromUrl(String url) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpclient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
StringBuilder buffer = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpEntity.getContent(), HTTP.UTF_8));
String line = null;
try {
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
} finally {
reader.close();
}
jObj = new JSONObject(reader.toString());
return jObj;
} catch (MalformedURLException localMalformedURLException) {
return null;
} catch (IOException localIOException) {
return null;
}catch (Exception e){
return null;
}
}
Your response is a JsonObject and you are parsing it to JSONArray
For more info. http://json.org/
I've been trying to use a JSONParser to access a remote database using php. However i have an error that i do not know how to solve. Could someone have a look over the code please. I've heard about the 3 characters at the start of a jsonString but i'm not sure how to fix it.
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(final String url) {
// Making HTTP request
try {
// Construct the client and the HTTP request.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// Execute the POST request and store the response locally.
HttpResponse httpResponse = httpClient.execute(httpPost);
// Extract data from the response.
HttpEntity httpEntity = httpResponse.getEntity();
// Open an inputStream with the data content.
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Create a BufferedReader to parse through the inputStream.
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
// Declare a string builder to help with the parsing.
StringBuilder sb = new StringBuilder();
// Declare a string to store the JSON object data in string form.
String line = null;
// Build the string until null.
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
// Close the input stream.
is.close();
// Convert the string builder data to an actual string.
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// Try to 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 the JSON Object.
return jObj;
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// 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;
}
}
LogCat error:
E/JSON Parser(27286): Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
Just though i'd add the php code that i'm using for the register function:
<?php
require("config.inc.php");
// If posted data is not empty
if(!empty($_POST))
{
// If the username or password submition is empty
if(empty($_POST['username']) || empty($_POST['password']))
{
// Create a JSON response
$response["success"] = 0;
$response["message"] = "Please enter a username and a password.";
die(json_encode($response));
}
// Check to see if there is already a user with the username
$query = " SELECT 1 FROM registration where username = :user";
// update the empty :user variable
$query_params = array(':user' => $_POST['username']);
// run query against database
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex)
{
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));
}
//return username data if already in use
$row = $stmt->fetch();
if($row)
{
$response["success"] = 0;
$response["message"] = "I'm sorry, this username is already in use";
die(json_encode($response));
}
// Query to create a user
$query = "Insert INTO registration (username, password) VALUES (:user, :password)";
// Update variables with actual data
$query_params = array(':user' => $_POST['username'], ':pass' => $_POST['password']);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
$response["success"] = 0;
$response["message"] = "Database Errror2. Please Try Again!";
die(json_encode($response));
}
// By this point, user has been added
$response["success"] = 1;
$response["message"] = "User Successfully Added!";
echo json_encode($response);
}
else
{
?>
<h1>Register</h1>
<form action="register.php method="post+>
Username:<br />
<input type = "text" name="username" value ="" />
<br /><br />
Password:<br />
<input type="password" name="password" value="" />
<br /><br />
<input type="submit" value="Register New User" />
</form>
<?php
}
?>
I'm currently working on android project related with database connectivity. As a part of App, there is an activity that form to insert data into database and retrieve the response whether it is inserted or not. Activity inserts data into database properly But, It fires an JSON parsing exception an couldn't get the response.
Here is my logcat scrreen:
03-31 09:49:38.196: D/JSON String:(884): Connection Error
03-31 09:49:38.236: D/Parsing Error!(884): Can't parse the stringorg.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
03-31 09:49:38.236: D/Exception!(884): java.lang.NullPointerException
03-31 09:49:38.526: W/InputMethodManagerService(373): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy#b410d300 attribute=null, token = android.os.BinderProxy#b40b3160
Here is my PHP Database connection script:config.inc.php
I think it is faulty!!
<?php
$username = "homeyadmin";
$password = "8YvUPxCsVHEca2Ru";
$host = "localhost";
$dbname = "homey_db";
//Communicate via UTF8
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try {
//Is this required??
// $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
mysql_connect('localhost','$username','$password') or die("Connection Error");
mysql_select_db($dbname) or die("no db found");
} catch(PDOException $ex) {
die("Failed to connect to Database!" +$ex.toString());
}
/*header('Content-Type: text/html; charset=utf-8');
session_start();*/
?>
And finally JSONParser class:
public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {
try {
if (method == "POST") {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
Log.d("Input Stream:", is.toString());
} else if (method == "GET") {
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf8");
url += "?" +paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (Exception ex) {
ex.toString();
}
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();
json = sb.toString();
Log.d("JSON String:", json);
} catch (Exception e) {
Log.d("Buffer Error!", "Can't convert result" +e.toString());
}
//Time to parse the string into JSONObject
try {
jobj = new JSONObject(json);
} catch (JSONException ex) {
Log.d("Parsing Error!", "Can't parse the string" +ex.toString());
}
return jobj;
}
}
Here is my php code
<?php
require("config.inc.php");
if(!empty($_POST)){
if (empty($_POST['FNAME']) || empty($_POST['LNAME']) || empty($_POST['EMAIL']) || empty($_POST['PASS'])
|| empty($_POST['HNAME']) || empty($_POST['HPNO']) || empty($_POST['HADD2'])
|| empty($_POST['HLANDMARK']) || empty($_POST['HNAME'])
|| empty($_POST['HCOUNTRY']) || empty($_POST['HSTATE'])
|| empty($_POST['HCITY']) || empty($_POST['HPHONE'])) {
//Creating JSON response
$response["success"] = 0;
$response["message"] = "All the fields are required!";
die(json_encode($response));
}
//List OF variables
$fname = $_POST['FNAME'];
$lname = $_POST['LNAME'];
$email = $_POST['EMAIL'];
$pass = $_POST['PASS'];
$hname = $_POST["HNAME"];
$hpno = $_POST["HPNO"];
$hadd2 = $_POST["HADD2"];
$hland = $_POST["HLANDMARK"];
$hcon = $_POST["HCOUNTRY"];
$hstate = $_POST["HSTATE"];
$hcity = $_POST["HCITY"];
$hphone = $_POST["HPHONE"];
//If page not died
$result = mysql_query("SELECT 1 FROM owner_info WHERE owner_email = '$email'");
$num = mysql_num_rows($result);
echo $num;
$i = 0;
if($num = $i) {
//JSON Response
$response["success"] = 0;
$response["message"] = "Email ID is already in use!";
die(json_encode($response));
}
//If None of these condition followed
$query = "INSERT INTO
owner_info (owner_fname, owner_lname, owner_email, owner_pass)
VALUES('$fname', '$lname', '$email', '$pass')
";
if(mysql_query($query)){
echo "done";
}else{
echo mysql_error();
}
$result1 = mysql_query("SELECT owner_id
FROM owner_info
WHERE owner_email = '$email'
");
if ($result1) {
while ($row = mysql_fetch_assoc($result1)) {
echo $temp_owner_id = $row['owner_id'];
}
mysql_query("INSERT INTO
hostel_info (h_owner_id, h_name, h_plot_no, h_address2, h_landmark, h_country, h_state, h_city, h_contact_no)
VALUES ('$temp_owner_id', '$hname', '$hpno', '$hadd2', '$hland', '$hcon', '$hstate', '$hcity', '$hphone')
");
$response["success"] = 1;
$response["message"] = "Data inserted successfully.";
die(json_encode($response));
} else {
$response["success"] = 0;
$response["message"] = "Database Error!!";
die(json_encode($response));
}
}
Please Help guys!!
You are getting invalid JSON, that's why it is not parsed.
Just add this code to see what you get from server:
try {
jobj = new JSONObject(json);
} catch (JSONException ex) {
Log.d("Parsing Error!", "Can't parse the string" +ex.toString());
Log.d("STRING_FROM_SERVER", json);
}
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