1

I have two non-activity class and I need to send one string from one class to another, my approach is to use shared preference but I cannot get the shared string in the second class. First class will run every time the app is opened and will generate a token

First class:

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

private static final String TAG = "MyFirebaseIDService";

/**
 * 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);
}
// [END refresh_token]

/**
 * Persist token to third-party servers.
 *
 * Modify this method to associate the user's FCM InstanceID token with any server-side account
 * maintained by your application.
 *
 * @param token The new token.
 */
public void sendRegistrationToServer(String token) {
    // TODO: Implement this method to send token to your app server.
    SharedPreferences sp = getSharedPreferences("PUSHToken", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sp.edit();
    editor.putString("PUSHToken", token);
    editor.commit();

}
}

I am trying to pass the string token and store in my second non-activity class for my volley request:

public class VolleyPut {

private static final String TAG = "VolleyPut";
private static VolleyPut instance = null;
public static final String KEY_TOKEN = "token";
//for Volley API
public RequestQueue requestQueue;

SharedPreferences sp2=getSharedPreferences("PUSHToken", Context.MODE_PRIVATE);
String token = sp2.getString("PUSHToken", "");

private VolleyPut(Context context)
{

    this.token = token;
    requestQueue = Volley.newRequestQueue(context.getApplicationContext());

    return;

}

public static synchronized VolleyPut getInstance(Context context)
{
    if (null == instance)
        instance = new VolleyPut(context);

    return instance;
}

public static synchronized VolleyPut getInstance()
{
    if (null == instance)
    {
        throw new IllegalStateException(VolleyPut.class.getSimpleName() +
                " is not initialized, call getInstance(...) first");
    }
    return instance;

}

public void VolleyPUT(String domain, String api, final String finalToken, final CustomListener<String> listener){

    JSONArray jsonArray = new JSONArray();
    JSONObject jsonObject = new JSONObject();
    try{

        jsonObject.put("token", token);
        jsonArray.put(jsonObject);
        Log.i("JsonString :", jsonObject.toString());

    }catch (Exception e){
        System.out.println("Error:" + e);
    }

    StringRequest sr = new StringRequest(Request.Method.PUT, domain + api,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.e("HttpClient", "success! response: " + response);
                    if(null != response)
                        listener.getResult(response);
                    return;
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    if (null != error.networkResponse)
                    {
                        Log.d(TAG + ": ", "Error Response code: " + error.networkResponse.statusCode);
                        //listener.getResult(false);
                    }
                }
            })
    {

        @Override
        public Map<String,String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers= new HashMap<>();
            headers.put("Authorization",finalToken);
            headers.put("Content-Type","application/json");
            headers.put(KEY_TOKEN,token);
            return headers;
        }
    };
    requestQueue.add(sr);
}
}

However I am getting error unable to resolve method getsharedpreference in my second class. How is the way to solve this and are there anyway to pass strings between non-activity class?

Surya Prakash Kushawah
  • 3,185
  • 1
  • 22
  • 42
JerryKo
  • 384
  • 7
  • 25

2 Answers2

1

The problem is that FirebaseInstanceIdService innherits from class android.content.Context so, in MyFirebaseInstanceIDService you have a Context and can use getSharedPreferences.

The solution is (to modify the minimum code) pass a context to the second class, and use it to get the shared preferences.

Better solution (my own think) is create a custom Application and use it always as a common context for all your app. Lower params and lower dependencies, because you always have the "CustomApplication" and can use it.

Here how to implement it:

https://stackoverflow.com/a/27416998/585540

Remember, if you use this approach, must put it in Manifest:

<application ....
        android:name="com.you.yourapp.CustomApplication"
        ......>
Community
  • 1
  • 1
Neonamu
  • 736
  • 1
  • 7
  • 21
0

You can create a global variable as:-

public Context context;


public VolleyPut(Context context)
{

this.token = token;
this.context=context
requestQueue = Volley.newRequestQueue(context.getApplicationContext());

return;

}

SharedPreferences sp2=**context**.getSharedPreferences("PUSHToken", Context.MODE_PRIVATE);

This will resolve error unable to resolve method getsharedpreference

Manohar
  • 22,116
  • 9
  • 108
  • 144
Nainal
  • 1,728
  • 14
  • 27