1

My tokenid is being generated on the phone. However it is not inserting into the database. Currently my phone is able to receive the notification from the firebase console. I am using firebase to do this. My register.php is working and it can post to DB. I am using Httpclient to send to the database. The register.php is the name of the file in my server. My database is being hosted on Uscloudlogin. The ontokenrefresh method in is not firing in MyFirebaseInstanceIDService.java in my android phone and emulator.I checked all the pages and it does not show any error.I followed the tutorial here https://www.youtube.com/watch?v=LiKCEa5_Cs8&t=3s How should i fix this? Please help.

MyFirebaseInstanceIDService.java

package **********;

import android.util.Log;


import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
 private static final String TAG = "MyFirebaseIIDService";

/**
 * Called if InstanceID token is updated. This may occur if the security of
 * the previous token had been compromised. Note that this is called when   the InstanceID token
 * is initially generated so this is where you would retrieve the token.
 */
// [START refresh_token]
@Override
  public void onTokenRefresh() {
    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "Refreshed token: " + refreshedToken);
    sendRegistrationToServer(refreshedToken);
}

private void sendRegistrationToServer(String token) {
    // Create a new HttpClient and Post Header
    OkHttpClient client = new OkHttpClient();
    RequestBody body = new FormBody.Builder()
            .add("Token",token)
            .build();

    Request request = new Request.Builder()
            .url("********")
            .post(body)
            .build();

    try {
        client.newCall(request).execute();
    } catch (IOException e) {
        e.printStackTrace();
    }
  }
 }

MainActivity.java

package ******;

import android.os.Bundle;


import org.apache.cordova.*;

import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.FirebaseMessaging;

public class MainActivity extends CordovaActivity
{
private static final String TAG = "MainActivity";
String Token;
boolean thread_running=true;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    // Set by <content src="index.html" /> in config.xml
    setContentView(R.layout.main);

    if (getIntent().getExtras() != null) {
        for (String key : getIntent().getExtras().keySet()) {
            Object value = getIntent().getExtras().get(key);
            Log.d(TAG, "Key: " + key + " Value: " + value);
        }
    }
    Button logTokenButton = (Button) findViewById(R.id.logTokenButton);
    logTokenButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Get token
            String token = FirebaseInstanceId.getInstance().getToken();

            // Log and toast
            String msg = getString(R.string.msg_token_fmt, token);
            Log.d(TAG, msg);
            Toast.makeText(MainActivity.this, msg, 
      Toast.LENGTH_SHORT).show();

        }


    });
    FirebaseMessaging.getInstance().subscribeToTopic("test");
    String a = FirebaseInstanceId.getInstance().getToken();

    Thread t = new Thread(new Runnable(){
        @Override
        public void run() {

            while (thread_running){
                Token = FirebaseInstanceId.getInstance().getToken();
                if (Token != null){ 
                    System.out.println("Device Token is "+Token);


                    thread_running=false;
                }else {
                    System.out.println("token is not loaded");
                }
                try {
                    Thread.sleep(1000);
                }catch(InterruptedException e) {
                    e.printStackTrace();
                }


            }
          }

    });

    t.start();

 }
}

Register.php

<?php 
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

error_reporting(E_ERROR);
echo "testing";
try{
if (isset($_POST["Token"])) {

    $_uv_Token=$_POST["Token"];
    $conn = new mysqli("localhost", "*****", "****", "****");
    $query="INSERT INTO users (Token) VALUES ( '$_uv_Token') " ." ON  
    DUPLICATE KEY UPDATE Token = '$_uv_Token';";
    $result = $conn->query($query);

    $json_out = 99;

    if (!$result){
        $json_out = "[" . json_encode(array("result"=>0)) . "]";        
    }
    else {
        $json_out = "[" . json_encode(array("result"=>1)) . "]";        
    }

    echo $json_out;

    $conn->close();

   }else{
    echo "NO POST REQUEST";
   }
 }

 catch(Exception $e) {
 $json_out =  "[".json_encode(array("result"=>0))."]";
 echo $json_out;
  }




 ?>
amus
  • 11
  • 1
  • 5
  • Dont try and frig a JSON String. Create a PHP Object/Array in the format that you want to receive that data and then just use `json_encode($theWholeDataStructure)`. – RiggsFolly Jan 21 '17 at 11:09
  • Also the debugging `echo`'s will destroy the data returned to the java code – RiggsFolly Jan 21 '17 at 11:09
  • Your script is at risk of [SQL Injection Attack](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) Have a look at what happened to [Little Bobby Tables](http://bobby-tables.com/) Even [if you are escaping inputs, its not safe!](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) Use [prepared parameterized statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) – RiggsFolly Jan 21 '17 at 11:10

0 Answers0