user3835979 user3835979 - 6 months ago 25
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

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));
}
}

.....
}

Answer

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.

Comments