php - 将 Firebase token 发送到自己的服务器不起作用

标签 php android mysql firebase

我正在尝试将 token 发送到 mySQL 数据库以存储在那里。我在 onNewToken() 的 myFirebaseMessagingService 类中调用以下方法,但没有任何反应。该功能正在运行,但 token 和用户名未存储在数据库中。

  private void sendRegistrationToServer(String token) {
        JSONObject request = new JSONObject();
        try {
            //Populate the request parameters
            request.put(KEY_USERNAME, "testUser");
            request.put(KEY_TOKEN, token);
            Log.d("test","request: " + request.toString());

        } catch (JSONException e) {
            e.printStackTrace();
        }
        JsonObjectRequest jsArrayRequest = new JsonObjectRequest
                (Request.Method.POST, submitToken_url, request, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.v("test","This is php response");
                        try {
                            //Check if user got registered successfully
                            if (response.getInt(KEY_STATUS) == 0) {
                                //Set the user session
                               Log.v("test","Token Stored Successfully" + KEY_STATUS);

                            } else if (response.getInt(KEY_STATUS) != 0) {
                                Log.v("test","Token Storing Failed" + KEY_STATUS);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {

                        //Display error message whenever an error occurs
                        Toast.makeText(getApplicationContext(),
                                error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });

        // Access the RequestQueue through your singleton class.
        MySingleton.getInstance(this).addToRequestQueue(jsArrayRequest);
    }

这也是我的 php 文件:

<?php
$response = array();
include 'db/db_connect.php'; 
//Get the input request parameters
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE); //convert JSON into array
//Check for Mandatory parameters
if(isset($input['username']) && isset($input['token']) ){
    $username = $input['username'];
    $token = $input['token'];
        //Query to register new user
        $insertQuery  = "INSERT INTO firebaseUser(username,token) VALUES (?,?)";
        if($stmt = $con->prepare($insertQuery)){
            $stmt->bind_param("ssss",$username,$token);
            $stmt->execute();
            $response["status"] = 0;
            $response["message"] = "User Token Stored";
            $stmt->close();
        }
}

echo json_encode($response);
?>

我添加了一个日志,现在出现了这个错误 org.json.JSONException: Value [] of type org.json.JSONArray cannot be converted to JSONObject

我的单例类:

import android.content.Context;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

public class MySingleton {
    private static MySingleton mInstance;
private static Context mCtx;
private RequestQueue mRequestQueue;

private MySingleton(Context context) {
    mCtx = context;
    mRequestQueue = getRequestQueue();
}

public static synchronized MySingleton getInstance(Context context) {
    if (mInstance == null) {
        mInstance = new MySingleton(context);
    }
    return mInstance;
}

private RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        // getApplicationContext() is key, it keeps you from leaking the
        // Activity or BroadcastReceiver if someone passes one in.
        mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
    }
    return mRequestQueue;
}

public <T> void addToRequestQueue(Request<T> req) {
    getRequestQueue().add(req);
}

最佳答案

已解决。我已将我的 php 文件更新为以下内容:

<?php
$response = array();
include 'db/db_connect.php';

//Get the input request parameters
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE); //convert JSON into array

//Check for Mandatory parameters
if(isset($input['username']) && isset($input['token'])){
$username = $input['username'];
$token = $input['token'];


    //Query to register new user
    $insertQuery  = "INSERT INTO firebaseUsers(username, token) VALUES (?,?)";
    if($stmt = $con->prepare($insertQuery)){
        $stmt->bind_param("ss",$username,$token);
        $stmt->execute();
        $response["status"] = 0;
        $response["message"] = "Token Saved";
        $stmt->close();
    }

}
else{
$response["status"] = 1;
}
echo json_encode($response);
?>

关于php - 将 Firebase token 发送到自己的服务器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56998325/

相关文章:

java - 使用 PreferenceFragment 时从 Volley 获取空指针错误

php - Paypal - 使用 PHP 重定向?

php - 如何在 Doctrine 2 中使用多对一关联

php - laravel 数据表加载数据需要很长时间

android - Recycler view Array index out of bound Inconsistency Error while SwipeRefresh 和回收器同时滚动

android - 从 Firebase 检索数据以创建要在数据库中编辑的地址

php - 提高 MySQL 中 2 个左连接和多个 SUM 的性能

mysql - (Amazon Linux) MySQL 在 EC2 重启时停止工作

php - fetch_array() 不保留查询中的 ORDER BY

php - 包含内联大括号错误的 Smarty 模板