• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

How to send a token from the SharedPreferences to MySQL with a session PHP script?

serious017

Lurker
Jan 4, 2019
5
0
I have WEB VIEW app and I ask for help. I have the following scripts: SharedPreference.java, FirebaseInstanceIDService.java and login.php, where is login.php hosted on the server.

I need to send the recorded token from SharedPreference to the MySQL database using the login.php script that contains the session.

When I delete the session from login.php, the token is record to the MySQL, when I return the session to the login.php the token is not recorded in the database.

Where am I wrong? Please Help.

MainActivity.java

Code:
FirebaseMessaging.getInstance().subscribeToTopic("test");
FirebaseInstanceId.getInstance().getToken();

SharedPreference.java

Code:
  import android.content.Context;
    import android.content.SharedPreferences;

    public class SharedPreference {
        private static final String SHARED_PREF_NAME = "FCMSharedPref";
        private static final String TAG_TOKEN = "tagtoken";

        private static SharedPreference mInstance;
        private static Context mCtx;

        private SharedPreference(Context context) {
            mCtx = context;
        }
        public static synchronized SharedPreference getInstance(Context context) {
            if (mInstance == null) {
                mInstance = new SharedPreference(context);
            }
            return mInstance;
        }
        //this method will save the device token to shared preferences
        public boolean saveDeviceToken(String token){
            SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString(TAG_TOKEN, token);
            editor.apply();
            return true;
        }
        //this method will fetch the device token from shared preferences
        public String getDeviceToken(){
            SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
            return  sharedPreferences.getString(TAG_TOKEN, null);
        }
}

FirebaseInstanceIDService.java

Code:
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 FirebaseInstanceIDService extends FirebaseInstanceIdService {

    private static final String TAG = "FirebaseIIDService";

    @Override
    public void onTokenRefresh() {

        String token = FirebaseInstanceId.getInstance().getToken();

        registerToken(token);
    }

    private void registerToken(String token) {

        OkHttpClient client = new OkHttpClient();
        RequestBody body = new FormBody.Builder()
                .add("Token",token)
                .build();

        Request request = new Request.Builder()
                .url("https://localhost/login.php”)
                .post(body)
                .build();

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

    private void storeToken(String token) {
        //saving the token on shared preferences
        SharedPreference.getInstance(getApplicationContext()).saveDeviceToken(token);
    }
}

login.php

Code:
session_start();

require_once(dirname(__FILE__) . "/users/su.inc.php");

    $UserK = new User();

    // Login from post data
    if( isset($_POST["username"]) )
    {

        $userId = $UserK->loginUser($_POST["username"], $_POST["password"]);
        if(!$userId) {
        $error = ‘Error username or password’;
        http_response_code(401);
    }
        else
        {

        if (isset($_REQUEST["Token"])) {
            require_once ("config.php");

            $_uv_Token=$_REQUEST["Token"];

            $conn = connect_db();

            $q="INSERT INTO user_push_notification (userId, Token) VALUES ({$userId}, '{$_uv_Token}') "
                ." ON DUPLICATE KEY UPDATE Token = '$_uv_Token', userId={$userId};";

            mysqli_query($conn,$q) or die(mysqli_error($conn));

        }


        header("Location: menu.php");
        exit;
        }

} // Validation end
 
Can anyone help me edit this code and adjust for FirebaseInstanceIDService?

Code:
SharedPreferences SharedPreference;   
Editor editor;

    private class GetGoogleAuthTask extends AsyncTask<Void, Void, String>  {
             @Override
             protected String doInBackground(Void... params) {
                 String token = null;

                 try {
                     token=GoogleAuthUtil.getToken(User_SignUp.this,Plus.AccountApi.getAccountName(mGoogleApiClient),"oauth2:"+Scopes.PLUS_LOGIN+" "+Scopes.PLUS_ME); //Change the permissions as per your need.
                 } catch (IOException transientEx) {
                     // Network or server error, try later
                     Log.e(TAG, transientEx.toString());
                 } catch (UserRecoverableAuthException e) {
                     // Recover (with e.getIntent())
                     Log.e(TAG, e.toString());
                    // Intent recover = e.getIntent();
                    // startActivityForResult(recover, REQUEST_CODE_TOKEN_AUTH);
                 } catch (GoogleAuthException authEx) {
                     // The call is not ever expected to succeed
                     // assuming you have already verified that
                     // Google Play services is installed.
                     Log.e(TAG, authEx.toString());
                 }

                 return token;
             }

             @Override
             protected void onPostExecute(String token) {

                 if(token!=null)
                 {
                  Log.i(TAG, "Access token retrieved:" + token);
                  SharedPreference = getApplicationContext().getSharedPreferences("TokenPreference", 0);
                  editor = SharedPreference.edit();
                  editor.putString("access_token",token);                              
                  editor.commit();                     

                 }

             }

         }

Code:
new GetGoogleAuthTask().execute();
 
Upvote 0
Relax mate, look at the problem systematically. First thing to establish is whether your onPostExecute() method is functioning correctly.
Run the app in debug mode, and set a breakpoint in that method. Step through it line by line. Is the token null?

Debug mode

Code:
2019-01-06 17:39:20.750 9499-9499/com.test/chromium: [INFO:CONSOLE(216)] "Uncaught SyntaxError: Unexpected token <", source: https://localhost/ (216)
2019-01-06 17:40:19.457 1633-1633/? W/WindowManager: removeWindowToken: Attempted to remove non-existing token: android.os.Binder@5f54084
2019-01-06 17:42:58.624 8290-8348/? W/PlayCommon: [462] com.google.android.play.b.g.a(473): No account for auth token provided
2019-01-06 17:46:11.688 1633-1633/? W/WindowManager: removeWindowToken: Attempted to remove non-existing token: android.os.Binder@5ee65d6
2019-01-06 17:57:59.053 8290-8348/? W/PlayCommon: [462] com.google.android.play.b.g.a(473): No account for auth token provided

But, on local srv (phpMyAdmin) token create whit login.php without a session!!!

Code:
 Edit  Copy  Delete  3   fHqhzyT6_4k:APA91bGVuZvX55Ax8hY5TRNyqTLTgaXuHS1kco...
 
Upvote 0
Debug mode

Code:
2019-01-06 17:39:20.750 9499-9499/com.test/chromium: [INFO:CONSOLE(216)] "Uncaught SyntaxError: Unexpected token <", source: https://localhost/ (216)
2019-01-06 17:40:19.457 1633-1633/? W/WindowManager: removeWindowToken: Attempted to remove non-existing token: android.os.Binder@5f54084
2019-01-06 17:42:58.624 8290-8348/? W/PlayCommon: [462] com.google.android.play.b.g.a(473): No account for auth token provided
2019-01-06 17:46:11.688 1633-1633/? W/WindowManager: removeWindowToken: Attempted to remove non-existing token: android.os.Binder@5ee65d6
2019-01-06 17:57:59.053 8290-8348/? W/PlayCommon: [462] com.google.android.play.b.g.a(473): No account for auth token provided

But, on local srv (phpMyAdmin) token create whit login.php without a session!!!

Code:
 Edit  Copy  Delete  3   fHqhzyT6_4k:APA91bGVuZvX55Ax8hY5TRNyqTLTgaXuHS1kco...

This problem is difficult for me because I'm preparing my final exam at college and I have to do this and I have no idea how.

I have a project that I have to present to my professor.

My problem is related to Android Studio and Webview and FCM.

The webview app is a small reminder. The php code is hosted on the local server, MySql record: the name of the exam, the date of the test and the time of the test. The php script via the cronjob send the email reminder to the student, but must in the android application that the logged user receives the push notification (FCM).

I use webview when calling my domain URL: https://localhost/login.php and users login on login.php over their phone. Everything is set and scripted work, but it does not work when login.php has a session and therefore can not connect the userId and token because I can not take the token from the android.

PLEASE HELP ME :(
 
Last edited:
Upvote 0

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones