Splitting nested array sent from android to php - java

I am sending JSON Objects which contain converted ArrayLists. For the most part everything works fine except on the PHP page.
If I use:
if($_POST)
{
echo "Something was sent";
$obj = array();
$JSON_Entry = $_POST["Entry"];
$body = json_decode($JSON_Entry, true);
foreach ($body as $key => $value)
{
echo $value;
}
I get the response in android emulator logs;
Something was sent[SalesMade [id=0, product_description=Beer, qty=2, unit=3, total=6.0]]
But when I try to separate the array using:
foreach($value as $column => $row)
{
echo $row;
}
I get an Invalid argument supplied for foreach() error. Is it because I converted the ArrayList to a JSON object before posting?

First you have to json_decode() $value, then you can foreach() through it.

Related

Stuck in error JSON Parse error: Unable to parse JSON string

I am stuck in very common error JSON parse error cannot figure out web service is faulty or fetch code I get a response from this web service when I test it in my postman it return two objects but when I want to login from this web service it always gives parse error
React Native Function to loginUser where may be error is present
UserLoginFunction = () =>{
const { UserContact } = this.state ;
const { UserPassword } = this.state ;
if(this.state.UserContact == ""){
ToastAndroid.show('Pleas Enter Contact Number Correctly ',ToastAndroid.SHORT)
}
else if (this.state.UserPassword == ""){
ToastAndroid.show('Please Enter Password Correctly',ToastAndroid.SHORT)
}
else{
fetch(urls.localhosturl + urls.login, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
user_contact: UserContact,
user_password: UserPassword,
//user_name: UserName,
})
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson)
// If server response message same as Data Matched
if(responseJson === 'Data Matched')
{
//Save User Details to Local Storage
AsyncStorage.setItem("userContact", JSON.stringify(UserContact));
//Then open Profile activity and send user email to profile activity.
this.props.navigation.navigate('Home',{user_contact:UserContact,});
}
else{
ToastAndroid.show(responseJson,ToastAndroid.SHORT);
//Alert.alert(string,responseJson);
}
}).catch((error) => {
console.error(error);
});
}
}
PHP webservice
<!-- begin snippet: js hide: false console: true babel: false -->
<?php
// Importing DBConfig.php file.
include 'config.php';
// Creating connection.
$con = mysqli_connect($host_name, $host_user, $host_password, $database_name);
// Getting the received JSON into $json variable.
$json = file_get_contents('php://input');
// decoding the received JSON and store into $obj variable.
$obj = json_decode($json, true);
$user_contact = $obj['user_contact'];
$user_password = $obj['user_password'];
// $user_contact = $_REQUEST['user_contact'];
// $user_password = $_REQUEST['user_password'];
//$user_name = $obj['user_name'];
$Sql_Query = "select * from user_information where user_contact = '$user_contact' and user_password = '$user_password' ";
$check = mysqli_fetch_array(mysqli_query($con, $Sql_Query));
if (isset($check)) {
$SuccessLoginMsg = 'Data Matched';
// Converting the message into JSON format.
$SuccessLoginJson = json_encode($SuccessLoginMsg);
// Echo the message.
echo $SuccessLoginJson;
} else {
// If the record inserted successfully then show the message.
$InvalidMSG = 'Invalid Username or Password Please Try Again';
// Converting the message into JSON format.
$InvalidMSGJSon = json_encode($InvalidMSG);
// Echo the message.
echo $InvalidMSGJSon;
}
$result = $con->query($Sql_Query);
$array = $result->fetch_assoc();
$json = json_encode($array, true);
echo $json;
mysqli_close($con);
It looks like the standard output of your PHP service is used as the source of the JSON.
In that case, the fact that you are spitting out the following line is causing you trouble:
echo $SuccessLoginJson;
You may want to either suppress this message, write it to a log file, or perhaps write it to standard error instead. In any case, you've turned your web service into something that gives your client two results instead of one, and the client doesn't understand how to handle it.

Hash string in Java and validate it in PHP

I want to create a Java Application, which creates an user account.
After this, the user should be able to login on my website.
I need a Java method to generate a hash, which is supported by PHP.
In PHP I always used this function to generate a hash:
public function hashPassword($password){
$options = [
'cost' => 11,
];
$password."<br>";
$hash = password_hash($password, PASSWORD_BCRYPT, $options)."<br>";
return $hash;
}
How can I do this in Java, when ...
I use this in PHP, to validate the password
public function checkPassword($password, $hash){
if (password_verify($passwordFromPost, $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
}
PS: to generate the $hash, I use the first function.
If anything isn't correct, please correct my code, because I'm new in Java

passing php object into array/list like in java

maybe its duplicate but i cant find it.
something = new ArrayList<>();
something.add(new Object("Hello"));
something.add(new object("World"));
something.add(new Object("!"));
for(blablabla){
System.out.print(something.get(i).getTextFromConstructor());
}
this will print "Hello World!"
in php i dont know solution to pass whole objects into array to call their methods from loop or just by something[0]->method();
As i know this in php cannnot be done, but maybe i am wrong :-)
Thank You
$arr = array();
$arr[] = new MyUSerDefinedObject("Hello");
//...
echo $arr[0]->methd();
//or
foreach ($arr as $val) {
echo $val->methd();
}
Use this example to set the bridge b/w php and java so that you can pass values to them
<?php
$date = new Java("java.util.Date", 70, 9, 4);
var_dump($date->toString());
$map = new Java("java.util.HashMap");
$map->put("title", "Java Bridge!");
$map->put("when", $date);
echo $map->get("when")->toString()."\n";
echo $map->get("title")."\n";
$array = array(1,2,3,4,5);
$map->put("stuff", $array);
var_dump($map->get("stuff"))."\n";
$system = new JavaClass("java.lang.System");
echo "OS: ".$system->getProperty("os.name")."\n";
$math = new JavaClass("java.lang.Math");
echo "PI: ".$math->PI."\n";
?>

How to retrieve associated products for configurable product with Magento SOAP API2?

I'm trying to get all the associated products for a configurable product using the Magento SOAP API v2. The catalogProductLink call looks close, but doesn't handle configurable types. I don't see any other calls that contain the associated product and configurable type information for a product. How have others solved this issue?
I'm using Magento version 1.6 and the SOAP API V2 with Java.
I looked deeper into this solution and realized that you may need to override the API model (Mage_Catalog_Model_Product_Api) to achieve the results you're looking for.
In the items function (around line 90), you can do something like this:
foreach ($collection as $product) {
$childProductIds = Mage::getModel('catalog/product_type_configurable')->getChildrenIds($product->getId());
$result[] = array(
'product_id' => $product->getId(),
'sku' => $product->getSku(),
'name' => $product->getName(),
'set' => $product->getAttributeSetId(),
'type' => $product->getTypeId(),
'category_ids' => $product->getCategoryIds(),
'website_ids' => $product->getWebsiteIds(),
'children' => $childProductIds[0],
);
}
create the folder app/code/local/Mage/Catalog/Model/Product/Link
copy the app/code/core/Mage/Catalog/Model/Product/Link/Api.php into this folder and edit it. (I’ve only done the change for the V1 but I’m pretty sure it’s as easy in V2)
replace the content of the the items() function with the following
if($type == "associated"){
$product = $this->_initProduct($productId);
try
{
$result = Mage::getModel('catalog/product_type_configurable')->getUsedProducts(null,$product);
}
catch (Exception $e)
{
$this->_fault('data_invalid', Mage::helper('catalog')->__('The product is not configurable.'));
}
}
else
{
$typeId = $this->_getTypeId($type);
$product = $this->_initProduct($productId, $identifierType);
$link = $product->getLinkInstance()
->setLinkTypeId($typeId);
$collection = $this->_initCollection($link, $product);
$result = array();
foreach ($collection as $linkedProduct) {
$row = array(
'product_id' => $linkedProduct->getId(),
'type' => $linkedProduct->getTypeId(),
'set' => $linkedProduct->getAttributeSetId(),
'sku' => $linkedProduct->getSku()
);
foreach ($link->getAttributes() as $attribute) {
$row[$attribute['code']] = $linkedProduct->getData($attribute['code']);
}
$result[] = $row;
}
}
return $result;
then you can call the API like this now:
$client->call($sessionId, 'product_link.list', array('associated', $id_of_your_configurable_product));
Basically my code is checking the type provided and if it’s “associated” it returns the child products.
I’m pretty sure there’s better way of doing it but I thought that the Product Link API was the most relevant place to do it.
Enjoy!
(please note: this code is not mine, i just adapted it and thought it would be a nice idea to help you guys out)

Null display when parsing json from php to android

here is my php code
$titikPetaInti = array();
while($row = mysql_fetch_assoc($hasil2))
{
$titikPetaInti[] = $row['koordinat'];
}
$data = "{titikPeta:".json_encode($titikPetaInti)."}";
echo $data;
?>
then here is my android code
xResultTitikPeta is result request to php
jObject = new JSONObject(xResultTitikPeta);
JSONArray myArray1 = (JSONArray) jObject.getJSONArray("titikPeta");
String[]titikPeta = new String[myArray1.length()];
for(int a = 0; a < myArray1.length(); a++)
{
titikPeta[a] = myArray1.getJSONObject(a).toString();
}
teks1 = (TextView) findViewById(R.id.textView1);
teks1.setText(Arrays.toString(titikPeta));
it displaying null at emulator like no value
--EDIT--
i think there something mistake in parsing code, cus when i display the xResultTitikPeta in android, it give me string result
here is result of xResultTitikPeta
{titikPeta:["-8.705378,115.225189","-8.56056700000000,115.42395100000","-8.57659700000000,115.40065300000","-8.55596300000000,115.41085700000","-8.51855200000000,115.491908000000","-8.54743200000000,115.41036800000","-8.56551100000000,115.45173900000","-8.44321000000000,115.616019000000"]}
this is malformed JSON! no double quotes on key.
$data = "{titikPeta:".json_encode($titikPetaInti)."}";
instead do:
$data = '{"titikPeta":'.json_encode($titikPetaInti).'}';
EDITED:
Ok, remove that hand made approach:
$data = json_encode(array("titikPeta"=>$titikPetaInti));
OK, I've found your bug! As well as fixing the $data = json_encode(array("titikPeta" => $titikPetaInti)); issue, the problem is here:
titikPeta[a] = myArray1.getJSONObject(a).toString();
The elements of myArray1 are actually of type string and cause an exception to be thrown, so you need instead:
titikPeta[a] = myArray1.getString(a);
This produces the output of:
[-8.705378,115.225189, -8.56056700000000,115.42395100000, -8.57659700000000,115.40065300000, -8.55596300000000,115.41085700000, -8.51855200000000,115.491908000000, -8.54743200000000,115.41036800000, -8.56551100000000,115.45173900000, -8.44321000000000,115.616019000000]
As each element in your array is of the form "-8.705378,115.225189", the JSON parser assumes they are strings. If you change the elements to "-8.705378","115.225189" you can also use:
titikPeta[a] = Double.toString(myArray1.getDouble(a));
However, the first version will work too.
Note: my personal preference is that I would declare each array element as:
{"x":-8.705378,"y":115.225189}
try
$data = "{\"titikPeta\":".json_encode($titikPetaInti)."}";

Categories