user3835979 user3835979 - 2 years ago 74
PHP Question

not receiving any values from php server

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


java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.util.ArrayList.get(int)' on a null object reference

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



$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);
$pushStatus = sendPushNotification($gcmRegids,$message);

function sendPushNotification($reg_ids, $message) {
$url = '';
$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));

//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>();
public void onMessageReceived(String from, Bundle data) {
if(data != null) {
arr = data.getStringArrayList("message");


Answer Source

You can't get simply an Php into Android/java array .. you have to convert to.. 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download