0

I am a beginner in android,My Application send empty GCM registration ID to server . The call is correct because the server accepts it, no error, and add a row in the database but the regid string is empty. I studied all the answers but I can not find out what is wrong.

and tag is null as in this picture

enter image description here

MainActivity.java

package
 com.inducesmile.androidgooglecloudmessaging;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
public class MainActivity extends AppCompatActivity {
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
private static final String TAG = "MainActivity";
private BroadcastReceiver mRegistrationBroadcastReceiver;
private TextView registrationStatus;
private Button clickToRegister;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registrationStatus = (TextView)findViewById(R.id.is_register);
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences sharedPreferences = 
PreferenceManager.getDefaultSharedPreferences(context);
boolean sentToken = 
sharedPreferences.getBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER,
 false);
if (sentToken) {
registrationStatus.setText(getString(R.string.gcm_send_message));
} else {
registrationStatus.setText(getString(R.string.token_error_message));
}
}
};
clickToRegister = (Button)findViewById(R.id.register_push);
clickToRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
if (checkPlayServices()) {
// Start IntentService to register this application with GCM.
Intent intent = new Intent(this, RegistrationIntentService.class);
startService(intent);
}
}
@Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
 new IntentFilter(QuickstartPreferences.REGISTRATION_COMPLETE));
}
@Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
super.onPause();
}
/**
*
 Check the device to make sure it has the Google Play Services APK. If
* it doesn't, display a dialog that allows users to download the APK 
from
* the Google Play Store or enable it in the device's system settings.
*/
private boolean checkPlayServices() {
GoogleApiAvailability apiAvailability = 
GoogleApiAvailability.getInstance();
int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
apiAvailability.getErrorDialog(this, resultCode, 
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.i(TAG, "This device is not supported.");
finish();
}
return false;
}
return true;
}
}

MyInstanceIDListenerService.java

package com.inducesmile.androidgooglecloudmessaging;
import android.content.Intent;
import com.google.android.gms.iid.InstanceIDListenerService;
public class MyInstanceIDListenerService extends InstanceIDListenerService {
@Override
public void onTokenRefresh() {
//super.onTokenRefresh();
// Fetch updated Instance ID token and notify our app's server of any changes (if applicable).
Intent intent = new Intent(this, RegistrationIntentService.class);
startService(intent);
}
}

MyGcmListenerService.java

package com.inducesmile.androidgooglecloudmessaging;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.android.gms.gcm.GcmListenerService;
public class MyGcmListenerService extends GcmListenerService {
private static final String TAG = "MyGcmListenerService";
@Override
public void onMessageReceived(String from, Bundle data) {
//super.onMessageReceived(from, data);
String message = data.getString("message");
Log.d(TAG, "From: " + from);
Log.d(TAG, "Message: " + message);
if (from.startsWith("/topics/")) {
// message received from some topic.
} else {
// normal downstream message.
}
sendNotification(message);
}
private void sendNotification(String message) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("GCM Message Received")
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}

RegistrationIntentService.java

package khd.test.nk.gcm;

        import android.app.IntentService;
        import android.content.Intent;
        import android.content.SharedPreferences;
        import android.preference.PreferenceManager;
        import android.support.v4.content.LocalBroadcastManager;
        import android.util.Log;
        import android.widget.EditText;
        import android.widget.Toast;

        import com.google.android.gms.gcm.GoogleCloudMessaging;
        import com.google.android.gms.iid.InstanceID;
        import com.kosalgeek.genasync12.AsyncResponse;
        import com.kosalgeek.genasync12.PostResponseAsyncTask;

        import java.io.IOException;
        import java.util.HashMap;

        import okhttp3.MediaType;
        import okhttp3.OkHttpClient;
        import okhttp3.Request;
        import okhttp3.RequestBody;
        import okhttp3.Response;

public class RegistrationIntentService extends IntentService {
    EditText editText;
    private static final String TAG = "RegistrationIntentService";
    private static final String pathToServer = "http://cars.heliohost.org/gcmm/insertuser.php";
    public RegistrationIntentService() {
        super(TAG);
    }
    @Override
    protected void onHandleIntent(Intent intent) {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        try {
// Initially this call goes out to the network to retrieve the token, subsequent calls are local.
// R.string.gcm_defaultSenderId (the Sender ID) is typically derived from google-services.json.
            InstanceID instanceID = InstanceID.getInstance(this);
            String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
            Log.i(TAG, "GCM Registration Token: " + token);

            sendRegistrationToServer(token);
// You should store a boolean that indicates whether the generated token has been
// sent to your server. If the boolean is false, send the token to your server,
// otherwise your server should have already received the token.
            sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, true).apply();
        } catch (Exception e) {
            Log.d(TAG, "Failed to complete token refresh", e);
// If an exception happens while fetching the new token or updating our registration data
// on a third-party server, this ensures that we'll attempt the update at a later time.
            sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false).apply();
        }
// Notify UI that registration has completed, so the progress indicator can be hidden.
        Intent registrationComplete = new Intent(QuickstartPreferences.REGISTRATION_COMPLETE);
        LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
    }

    /******************************************************************************************************/
    private void sendRegistrationToServer(String token) {
        final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(JSON, bowlingJson(token));
        Request request = new Request.Builder()
                .url(pathToServer)
                .post(body)
                .build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            Log.d(TAG, String.valueOf(response));
            Log.d(TAG, "Response" + response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private String bowlingJson(String token) {
        return "{'registrationId': " + token + "}";

    }
}

php

<?php
include_once './db_functions.php';
//Create Object for DB_Functions clas
$db = new DB_Functions(); 

$registration_id = $_POST["registrationId"];
$res = $db->insertUser($registration_id);
echo " RegId ".$registration_id ;
if(isset($_POST['registrationId'])) {
    echo "GCM Reg Id bas been shared successfully with Server";
} else {             
    echo  "Error occured while sharing GCM Reg Id with Server web app";  ;                      
}
?>

<?php
 
class DB_Functions {
 
    private $db;
 
    function __construct() {
        include_once './db_connect.php';
        // Connect to database
        $this->db = new DB_Connect();
        $this->db->connect();
    }
    // destructor
    function __destruct() {
 
    }
    /**
     * Insert new user
     * 
     */
    public function insertUser($registration_id) {
        // Insert user into database
        $result = mysql_query("insert into user (gcm_regid, created_at) values ('$registration_id', NOW())");        
        if ($result) {
            return true;
        } else {             
            return false;                      
        }
    }
    /**
     * Select all user
     * 
     */
     public function getAllUsers() {
        $result = mysql_query("select * FROM user");
        return $result;
    }
    /**
     * Get GCMRegId
     * 
     */
    public function getGCMRegID($id){
         $result = mysql_query("SELECT gcm_regid FROM user WHERE id = "."'$id'");
         return $result;
    }
}
?>

Screenshot 1

thanks in advance

php config.php

<?php

define("DB_HOST","localhost");

define("DB_USER","root");

define("DB_PASSWORD","30501001515");

define("DB_NAME","clients");

define("GOOGLE_API_KEY","AIzaSyBv_v_UAb1JpbDw8rwgQgMzqS3DyPoQCFA");
?>

registeruser.php

<?php
 
 if(isset($_POST['registrationId'])){
     $registration_id = $_POST['registrationId'];
     include_once 'userregistration.php'; 
     $UserRegistrationClass = new UserRegistrationFromDevice();
     $UserRegistrationClass->saveNewRegisteredUser($registration_id); 
  } 
 
?>

Database.php

<?php
 
include_once 'db.php';
 
 class DatabaseLayer{
  
  private $tables;
 
 public function __constructor(){
  
  $this->tables = "user";
 }
 
 public function insertUserRegistrationId($registration_id){
  
  if(!$this->getAllRegisteredUsers($registration_id)){
   $com = new DbConnect(); 
   $sql = "insert into user (gcm_regid, created_at) values ('$registration_id', NOW())";   
      mysqli_query($com->getDb(), $sql);
  }
 }
 
 public function getAllRegisteredUsers($registration_id){
  $com = new DbConnect();
  $sql = "Select * from  user where gcm_regid = " + $registration_id;
  $result = mysqli_query($com->getDb(), $sql);
  if(count($result) == 1){
   return true;
  }
  return false;
 }
 
 public function getRegistrationId(){
  
  $com = new DbConnect();
  $sql = "select gcm_regid from user limit 1";
  $result = mysqli_query($com->getDb(), $sql);
  $row = mysqli_fetch_row($result);  
  //print_r($row[0]);
  if(count($row) == 1){
   return $row[0];
  }
  return false;
 } 
}
 
?>

table

CREATE TABLE IF NOT EXISTS `user` (
`gcm_regid` text NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`id` int(8) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;
NawalSalameh
  • 109
  • 1
  • 13
  • run app and put break point at line String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); and see what are you getting in token – Khizar Hayat Mar 09 '16 at 13:32
  • @khizarHayat thak you , I will try. – NawalSalameh Mar 09 '16 at 13:40
  • Welcome. check and let me know if need more help – Khizar Hayat Mar 09 '16 at 13:45
  • @khizar Hayat this is the value for token, token:fjQr8LfEt5s:APA91bGRvhGRYZMykpraJXv39EjEOYFvtcEpdUenXDe0vdcDPRxhDTx0VHwy4MIgjbRD_ve0qEuLSOiCFVlMLyYTw8EAXc6j7iUrVMo8lXnx8Wc87r5SZUt_2cjb6jmHpopM99EzaFe4. – NawalSalameh Mar 09 '16 at 16:15
  • @khizar Hayat i found that tag is null as in the picture above – NawalSalameh Mar 09 '16 at 21:24
  • You create the JSON as `"{'registrationId': " + token + "}"`. However, the token is alphanumeric string, you need to put it in quotes: `"{'registrationId': '" + token + "'}"` or the JSON would be invalid. – StenSoft Mar 09 '16 at 21:38
  • token is ok when you inserting it in db there may be issue in sql. i am not well in queires. but issue is in query not in android integration – Khizar Hayat Mar 10 '16 at 04:23
  • @StenSoft thank you , i tried that , but still not receiving regid. – NawalSalameh Mar 11 '16 at 06:21
  • @KhizarHayat I tried many php codes and still the same issue, I wish I can find the right php codes,I am a beginner,cannot find right way to snd push notification,and need it in my project,can you please send me the right codes and how to test it , I have been trying that codes and other for 3 weeks and no result . i will update my question to add php codes. thank you in advance brother. – NawalSalameh Mar 11 '16 at 06:32
  • @KhizarHayat can you test the codes,please. – NawalSalameh Mar 11 '16 at 06:46
  • I am android guy. i can't help you in php – Khizar Hayat Mar 11 '16 at 06:58
  • I have a sample php and i posted here http://stackoverflow.com/questions/35933382/react-native-push-notification-for-android/35934124#35934124 – Khizar Hayat Mar 11 '16 at 07:02
  • Note that most web servers don't understand JSON in POST payload (so `$_POST` will be empty) and [you would need to parse the payload yourself](https://stackoverflow.com/questions/18866571/receive-json-post-with-php#18867369) – StenSoft Mar 11 '16 at 18:10
  • thanks guys,,,,,,, – NawalSalameh May 10 '16 at 07:34

0 Answers0