not receiving any values from php server - php

I want to retrieve all names from my database and send it to all the registered phones by gcm.
I get an error at my android side
Error
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.util.ArrayList.get(int)' on a null object reference
at reminder.com.org.remind.GCMPushReceiverService.onMessageReceived(GCMPushReceiverService.java:27)
this is the result of var_dump($message)
array(1) { ["message"]=> array(3) { [0]=> string(5) "name1" [1]=> string(5) "name2" [2]=> string(5) "name3" } }
Please help. Thanks.
PHP Server Code
<?php
include('db_connect.php');
DEFINE('GOOGLE_API_KEY','my_google_api_key');
$db = new DB_CONNECT();
$conn = $db->connect();
$gcmRegids = array();
$names = array();
$sql = "SELECT * FROM Test";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
array_push($gcmRegids, $row['reg_id']);
array_push($names, $row['name']);
}
if(isset($gcmRegids)) {
$e = "ads";
$message = array('message' => $names);
var_dump($message);
$pushStatus = sendPushNotification($gcmRegids,$message);
}
function sendPushNotification($reg_ids, $message) {
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $reg_ids,
'data' => $message,
);
$headers = array (
'Authorization: key='. GOOGLE_API_KEY,
'Content-type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($fields));
$result = curl_exec($ch);
if($result === false) {
die('Curl failed:'. curl_error($ch));
}
curl_close($ch);
//echo $result;
return $result;
}
?>
array(1) { ["message"]=> array(3) { [0]=> string(5) "name1" [1]=> string(5) "name2" [2]=> string(5) "name3" } }
Android code
public class GCMPushReceiverService extends GcmListenerService {
public final static String s = "msg";
ArrayList<String> arr = new ArrayList<String>();
#Override
public void onMessageReceived(String from, Bundle data) {
if(data != null) {
arr = data.getStringArrayList("message");
Log.d("Names:",arr.get(0));
}
}
.....
}

You can't get simply an Php Array into Android/java array .. you have to convert it.. try to change your php script as..
$message = array('message' => json_encode($names));
it will convert your php array($names) into json.
than get the JSON in android as..
String message = data.getString("message");
Log.e(TAG, "Message: " + message);
now convert it into JsonArray as..
JsonArray array = new JsonArray(message);
now loop on it and get the content of Php array names.

I think here you are doing wrong.
change your code as below and try again
if (isset($gcmRegids) && count($gcmRegids) > 0) {
$e = "ads";
$message = array('message' => $names);
var_dump($message);
foreach ($gcmRegids as $gcmid) {
$pushStatus = sendPushNotification($gcmid, $message);
}
}

Related

Ordering by JSON

We are importing our JSON from an API. The JSON is pulling through fine but unordered
We want to order the JSON file by the name field, We have used uasort but it does not seem to take effect?
$url="https://dev-api.ourwebsite.com";
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// DUMPING THE JSON
$json=json_decode($result, true);
uasort($json, 'name');
foreach($json as $value) {
$course_name=$value["name"];
}
usort() (or uasort() if you need to keep the keys of the array) is what you need:
<?php
// mocking some data
$json = [
["name" => "paul"],
["name" => "jeff"],
["name" => "anna"]
];
uasort($json,
// this callable needs to return 1 or -1, depending on how you want it to sort
function($a, $b) {
if($a['name']>$b['name']) {
return 1;
} else {
return -1;
}
});
var_dump($json);
foreach($json as $value) {
$course_name=$value["name"];
echo $course_name."<br>";
}
// output:
array(3) {
[2]=>
array(1) {
["name"]=>
string(4) "anna"
}
[1]=>
array(1) {
["name"]=>
string(4) "jeff"
}
[0]=>
array(1) {
["name"]=>
string(4) "paul"
}
}
anna
jeff
paul

Newsletter2Go REST API - How to add new recipient to list?

Is it possible to add a new recipient via the REST API of Newsletter2Go?
I tried it like this (snippet):
public function subscribeAction()
{
$this->init();
$email = $this->getRequest()->getParam('email');
$gender = $this->getRequest()->getParam('gender');
$first_name = $this->getRequest()->getParam('first_name');
$last_name = $this->getRequest()->getParam('last_name');
$endpoint = "/recipients";
$data = array(
"list_id" => $this->listId,
"email" => $email,
"gender" => $gender,
"first_name" => $first_name,
"last_name" => $last_name,
);
$response = $this->curl($endpoint, $data);
var_dump($response);
}
/**
* #param $endpoint string the endpoint to call (see docs.newsletter2go.com)
* #param $data array tha data to submit. In case of POST and PATCH its submitted as the body of the request. In case of GET and PATCH it is used as GET-Params. See docs.newsletter2go.com for supported parameters.
* #param string $type GET,PATCH,POST,DELETE
* #return \stdClass
* #throws \Exception
*/
public function curl($endpoint, $data, $type = "GET")
{
if (!isset($this->access_token) || strlen($this->access_token) == 0) {
$this->getToken();
}
if (!isset($this->access_token) || strlen($this->access_token) == 0) {
throw new \Exception("Authentication failed");
}
return $this->_curl('Bearer ' . $this->access_token, $endpoint, $data, $type);
}
private function _curl($authorization, $endpoint, $data, $type = "GET")
{
$ch = curl_init();
$data_string = json_encode($data);
$get_params = "";
if ($type == static::METHOD_POST || $type == static::METHOD_PATCH) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
if ($type == static::METHOD_POST) {
curl_setopt($ch, CURLOPT_POST, true);
}
} else {
if ($type == static::METHOD_GET || $type == static::METHOD_DELETE) {
$get_params = "?" . http_build_query($data);
} else {
throw new \Exception("Invalid HTTP method: " . $type);
}
}
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $type);
curl_setopt($ch, CURLOPT_URL, static::BASE_URL . $endpoint . $get_params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization: ' . $authorization,
'Content-Length: ' . ($type == static::METHOD_GET || $type == static::METHOD_DELETE) ? 0 : strlen($data_string)
));
if (!$this->sslVerification) {
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response);
}
https://docs.newsletter2go.com/#!/Recipient/createRecipient
But I get a big response object, even though I only try to add one single recipient, and the new recipient is not added to the list.
object(stdClass)#188 (3) {
["status"]=>
int(200)
["info"]=>
object(stdClass)#169 (3) {
["links"]=>
object(stdClass)#43 (3) {
["_href"]=>
string(60) "https://api.newsletter2go.com/recipients?_limit=50&_offset=0"
["_next"]=>
string(61) "https://api.newsletter2go.com/recipients?_limit=50&_offset=50"
["_last"]=>
string(63) "https://api.newsletter2go.com/recipients?_limit=50&_offset=3433"
}
["count"]=>
int(3483)
["additional"]=>
object(stdClass)#167 (1) {
["active"]=>
int(0)
}
}
["value"]=>
array(50) {
[0]=>
object(stdClass)#85 (2) {
["_href"]=>
string(49) "https://api.newsletter2go.com/recipients/n9yldrar"
["id"]=>
string(8) "n9yldrar"
}
[1]=>
object(stdClass)#185 (2) {
["_href"]=>
string(49) "https://api.newsletter2go.com/recipients/pgwvgwmr"
["id"]=>
string(8) "pgwvgwmr"
}
...
[49]=>
object(stdClass)#87 (2) {
["_href"]=>
string(49) "https://api.newsletter2go.com/recipients/usa0dx4n"
["id"]=>
string(8) "usa0dx4n"
}
You must use a POST request to add a recipient, right now you are making a GET request. Change
$response = $this->curl($endpoint, $data);
to
$response = $this->curl($endpoint, $data, 'POST');
then it should work!
Mostly GET requests are used to get data, while POST requests are used to set data. The GET request you've posted returns all your recipients.

Adding RestAPI response to MySQL database

$cn = curl_init();
$url = 'https://URL';
curl_setopt($cn, CURLOPT_URL, $url);
curl_setopt($cn, CURLOPT_RETURNTRANSFER, TRUE);
$output = curl_exec($cn);
$aOutput = json_decode($output, TRUE);
//var_dump($aOutput);
$curl_error = curl_error($cn);
print_r($curl_error);
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
foreach($aOutput as $key => $data) {
var_dump($key['average_price']);
// var_dump($data[$key]["Average_Price"]);
// $sql = "INSERT INTO Market('type_id', 'average_price', 'adjusted_price')
// VALUES ($data);";
}
array(10763) {
[0]=>
array(3) {
["average_price"]=>
float(381907.23)
["adjusted_price"]=>
float(383184.18)
["type_id"]=>
int(32772)
}
[1]=>
array(3) {
["average_price"]=>
float(54090.07)
["adjusted_price"]=>
float(57340.16)
["type_id"]=>
int(32774)
}
I am attempting to add this entire multidimensional array to my database. The main thing I am having trouble with is the foreach loop.
I have tried $array[$key][$column], and many other ways but I only get NULL when dumping the variable.
I have attempted, $key['average_price'] etc still returns null.
You're getting $key and $data muddled up.
Easiest if you annotate it out:
If your $aOutput array is
array(10763) {
[0]=>
array(3) {
["average_price"]=>float(381907.23)
["adjusted_price"]=>float(383184.18)
["type_id"]=>int(32772)
}
[1]=>
array(3) {
["average_price"]=>float(54090.07)
["adjusted_price"]=>float(57340.16)
["type_id"]=>int(32774)
}
....
then
foreach($aOutput as $key => $data) {
// $key = 0
// $data = array(3) {
["average_price"]=>float(381907.23)
["adjusted_price"]=>float(383184.18)
["type_id"]=>int(32772)
}
// So what you want is $data['average_price']
You can simplify this by not even using hte key, just do
foreach($aOutput as $data) {
// $data = array(3) {
["average_price"]=>float(381907.23)
["adjusted_price"]=>float(383184.18)
["type_id"]=>int(32772)
}
// So what you want is $data['average_price']

How to concat the echo output with some base URL in JSON

I am a code like below
<?php
$movie_name="Dabangg 2";
$movie_name = urlencode($movie_name);
$url="http://api.themoviedb.org/3/search/movie?api_key=accd3ddbbae37c0315fb5c8e19b815a5&query=$movie_name";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Accept: application/json"));
$response = curl_exec($ch);
curl_close($ch);
$obj = json_decode($response);
foreach ($obj->results as $results){
echo $results->id;
echo $results->"http://d3gtl9l2a4fn1j.cloudfront.net/t/p/w92'.poster_path.'";
}
?>
and var_dump is
object(stdClass)#1 (4) {
["page"]=>
int(1)
["results"]=>
array(1) {
[0]=>
object(stdClass)#2 (10) {
["adult"]=>
bool(false)
["backdrop_path"]=>
string(32) "/rWGMdyTydjXXh9YphuU5gQ7wJ8X.jpg"
["id"]=>
int(147405)
["original_title"]=>
string(9) "Dabangg 2"
["release_date"]=>
string(10) "2012-12-21"
["poster_path"]=>
string(32) "/3tqT7N94fY73Ft6BVepnEqgwWyr.jpg"
["popularity"]=>
float(0.46)
["title"]=>
string(9) "Dabangg 2"
["vote_average"]=>
float(5.8)
["vote_count"]=>
int(2)
}
}
["total_pages"]=>
int(1)
["total_results"]=>
int(1)
}
my code is working fine. I just want to retrieve the poster_path with the base URL http://d3gtl9l2a4fn1j.cloudfront.net/t/p/w92 . HOw can I do this? The above
echo $results->"http://d3gtl9l2a4fn1j.cloudfront.net/t/p/w92'.poster_path.'";
is just my attempt to echo the full URL.
The output URL echo should be
http://d3gtl9l2a4fn1j.cloudfront.net/t/p/w92/3tqT7N94fY73Ft6BVepnEqgwWyr.jpg
Thanks
Unless im missing something...
echo 'http://d3gtl9l2a4fn1j.cloudfront.net/t/p/w92' . $results->poster_path;
This might help you:
<?php
$url_ahead = 'http://d3gtl9l2a4fn1j.cloudfront.net/t/p/w92';
$poster_path = $results[0]['poster_path']; //or something like this
//$poster_path = "/3tqT7N94fY73Ft6BVepnEqgwWyr.jpg"; //for static
// echo $url_ahead.''.$poster_path;
echo $url_ahead.$poster_path;
?>
$baseUrl = "http://d3gtl9l2a4fn1j.cloudfront.net/t/p/w92";
foreach ($obj->results as $results){
echo $results[0]->id; //this also should be changed from $results->id
$posterUrl = $results[0]['poster_path'];
echo $baseUrl.$posterUrl; //Can store like $poster_path = $baseUrl.$posterUrl;
}
Why need to use $results[0]->id and $results[0]['poster_path']? Because $results is also a Two/Multidimensional array.

PHP function help

This is the function:
function NewsDat($url="http://www.url.com/dat/news.dat", $max=5){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$curlresult = curl_exec($ch);
$posts = explode("\n", $curlresult); //chop it up by carriage return
unset($curlresult);
$num=0;
$result=array();
foreach($posts as $post){
$result[] = explode("::", $post);
$num++;
if($num>$max-1){
break;
}
}
return $result;
}
var_dump(NewsDat());
Which returns:
array(5) { [0]=> array(14) { [0]=> string(10) "1183443434" [1]=> string(1) "R" [2]=> string(46) "Here is some text"...
I need to echo: 1183443434 and Here is some text...
Can anyone help?
Basic array handling?
$result = NewsDat();
echo $result[0][0]; //holds "1183443434"
echo $result[0][2]; //holds "Here is some text"
But I don't know if the values are always at this positions when you run your function.
Well as NewsDat return an array of arrays, if you need this two fields on each lines, this should do the trick:
$news = NewsDat();
foreach($news as $single_new)
{
echo $single_new[0] . " - " . $single_new[2] . "\n";
}
If you only need these two fields, just:
$news = NewsDat();
$field1 = $news[0][0];
$field2 = $news[0][2];
echo $field1 . " - " . $field2 . "\n";

Categories