How to get token from wordpress-rest-api using Retrofit Android? - java

I’m developing Android app that’s based on a WordPress website, so I need to get a token to login the user to the app using the JWT method.
When I send a request, I don’t get any response from the server; probably there something wrong with my code. I installed the wordpress-rest-api plugin and jwt-auth-plugin on the website.
My code contains userModel.java which contains getters and setters for the user id, email, and token.
retroFitInterface.java:
#POST ("Authorization: Bearer")
Call<User> login (#Body Login login);
#GET ("secretinfo")
Call<ResponseBody>getSecret(#Header("Authorization")String authToken);
Login.java:
private String email,password;
public Login (String email,String password) {
this.email = email;
this.password = password;
}
}
MainActivity.java
Retrofit.Builder builder = new Retrofit.Builder().baseUrl("https://taqoh.com/wp-json/jwt-auth/v1/token").addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
RetroFitInterface retroFitInterface = retrofit.create(RetroFitInterface.class);
private Button button, button1;
private static String token;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.login_btn);
button1 = findViewById(R.id.get_token_btn);
}
private void login() {
Login login = new Login("isohunter1#hotmail.com", "qweqweqwe123");
Call<User>call = retroFitInterface.login(login);
call.enqueue(new Callback<User>() {
#Override
public void onResponse(Call<User> call, Response<User> response) {
if (response.isSuccessful()) {
Toast.makeText(MainActivity.this, response.body().getEmail(), Toast.LENGTH_LONG).show();
token = response.body().getToken();
}
}
#Override
public void onFailure(Call<User> call, Throwable t) {
Toast.makeText(MainActivity.this, "error", Toast.LENGTH_LONG).show();
}
});
}
private void getSecret() {
Call<ResponseBody>secret = retroFitInterface.getSecret(token);
secret.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.login_btn) {
login();
} else if (v.getId() == R.id.get_token_btn) {
getSecret();
}
}

Related

How do I execute two methods using onClickListener?

I'm new to android studio and I'm trying to create a simple weather app using OpenWeatherMap API. I am using OkHttp library to perform a GET request. All it does is take an input throught EditText and update the TextView on button click using a Button.
But the problem is, the TextView updates after two clicks on the Button. I want to update it right after the first click. So, how do I go over this?
Here is my code:
public class MainActivity extends AppCompatActivity {
private EditText cityName;
private TextView weatherData;
private TextView hiddenText;
private Button getBtn;
public String s = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
weatherData = (TextView)findViewById(R.id.weatherText);
getBtn = (Button)findViewById(R.id.getData);
cityName = (EditText)findViewById(R.id.cityName);
getBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getWeatherData(cityName.getText().toString());
weatherData.setText(s);
}
});
}
public void getWeatherData(String cityText){
String url = "https://api.openweathermap.org/data/2.5/weather?q=" + cityText + "&appid=ba45ceb57328448f7wd666hdc6d57aaf";
OkHttpClient client = new OkHttpClient();
final Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
s = "Something went wrong!";
}
});
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
if(response.isSuccessful()){
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
try{
s = response.body().string();
}
catch (IOException ioe){
s = "Error while getting JSON.";
}
}
});
}
}
});
}
}
I know that I can update the TextView in onResponse itself but I wanna know if it is possible to update it through onClickListener. If it's not possible, which method should I use? Any help would be appreciated.
you have to update text value in server response call back
public class MainActivity extends AppCompatActivity {
private EditText cityName;
private TextView weatherData;
private TextView hiddenText;
private Button getBtn;
public String s = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
weatherData = (TextView)findViewById(R.id.weatherText);
getBtn = (Button)findViewById(R.id.getData);
cityName = (EditText)findViewById(R.id.cityName);
getBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getWeatherData(cityName.getText().toString());
}
});
}
public void getWeatherData(String cityText){
String url = "https://api.openweathermap.org/data/2.5/weather?q=" + cityText + "&appid=ba45ceb57328448f7wd666hdc6d57aaf";
OkHttpClient client = new OkHttpClient();
final Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
s = "Something went wrong!";
}
});
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
if(response.isSuccessful()){
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
try{
s = response.body().string();
weatherData.setText(s);
}
catch (IOException ioe){
s = "Error while getting JSON.";
}
}
});
}
}
});
}
}
You are setting data on edit text on click after calling GET Request.
Update the textview with the data , once you get the response.
public class MainActivity extends AppCompatActivity {
private EditText cityName;
private TextView weatherData;
private TextView hiddenText;
private Button getBtn;
public String s = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
weatherData = (TextView)findViewById(R.id.weatherText);
getBtn = (Button)findViewById(R.id.getData);
cityName = (EditText)findViewById(R.id.cityName);
getBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getWeatherData(cityName.getText().toString());
}
});
}
public void getWeatherData(String cityText){
String url = "https://api.openweathermap.org/data/2.5/weather?q=" + cityText + "&appid=ba45ceb57328448f7wd666hdc6d57aaf";
OkHttpClient client = new OkHttpClient();
final Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
s = "Something went wrong!";
}
});
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
if(response.isSuccessful()){
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
try{
s = response.body().string();
weatherData.setText(s);
}
catch (IOException ioe){
s = "Error while getting JSON.";
}
}
});
}
}
});
}
}

I can't read an answer from server

I'm using Retrofit library for Android.
I'm trying to connect server, sending post request and well everything, But when i'm trying to get responce.body, i get the following answer :
2020-07-04 21:37:45.931 18419-18419/com.androidapplications.mymetroword D/otvet: com.androidapplications.mymetroword.Posts#22bd74
My Pojo
public class Posts {
#SerializedName("email")
#Expose
private String email;
#SerializedName("password")
#Expose
private String password;
//getters and constructor
}
My Interface
public interface ApiServices {
#FormUrlEncoded
#POST("authuser")
Call<Posts> createPost(
#Field("email") String email,
#Field("password") String password
);
}
My MainActivity
public class MainActivity extends AppCompatActivity {
EditText email_add;
Button btn_sign_in;
EditText password;
SharedPreferences sharedPreferences;
public static final String BASE_URL = "https://shavkunov.tk/";
ApiServices apiServices;
public String stat_auth;
TextView msg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
//some variables
}
public void postRequest() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
apiServices = retrofit.create(ApiServices.class);
Call<Posts> call = apiServices.createPost("1naesis#gmail.com", "1");
call.enqueue(new Callback<Posts>() {
#Override
public void onResponse(Call<Posts> call, Response<Posts> response) {
if (response.isSuccessful()) {
switch (response.code()) {
case 200 :
Log.d("otvet", "" + response.body());
break;
case 201 :
break;
}
}
else {
Toast.makeText(MainActivity.this, "упс", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<Posts> call, Throwable t) {
Toast.makeText(MainActivity.this, "error: "+ t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public void onClickSignIn(View view) { //текст-кнопка "
postRequest();
}
}
Please, help me)
You need to override the ToString() method in this class using the IDE or by typing it your self as now you are accessing the object allocation id and not the object values.
https://stackoverflow.com/a/10734148/13867485 look at this

Retrofit, TimeoutException

I'm using retrofit authentication, and I have a timeoutexception. I saw many questions, but I can't solve this.
Here's the code
public class FragmentRegistration extends Fragment {
View mainView;
EditText username, email, password, name;
Button button;
ApiClient pentairAPIClient = ApiClient.getInstance();
SupportopObj supportopObj = new SupportopObj();
SupportopObjActivate supportopObjActivate = new SupportopObjActivate();
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mainView = inflater.inflate
(R.layout.registration, container, false);
username = mainView.findViewById(R.id.username);
email = mainView.findViewById(R.id.email);
password = mainView.findViewById(R.id.password);
name = mainView.findViewById(R.id.name);
button = mainView.findViewById(R.id.register);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//String s = name.getText().toString();
//String split[] = s.split(" ");
supportopObj.setFirstName("Tester");
supportopObj.setLastName("Testryan");
supportopObj.setUsername(username.getText().toString());
supportopObj.setEmail(email.getText().toString());
supportopObj.setPassword(password.getText().toString());
supportopObjActivate.setUsername(supportopObj.getUsername());
supportopObjActivate.setEmail(supportopObj.getEmail());
supportopObjActivate.setPassword(supportopObj.getPassword());
supportopObjActivate.setType("generic");
updateApp();
}
});
return mainView;
}
public void updateApp() {
Call<ResponseBody> call = pentairAPIClient.registration(supportopObj);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
activationCall();
} else {
Toast.makeText(getContext(), "Something went wrong",
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(getContext(), "Error...", Toast.LENGTH_SHORT).show();
}
});
}
public void activationCall() {
Call<ResponseBody> callActive = pentairAPIClient.activation(supportopObjActivate);
callActive.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
try {
String data = response.body().string();
JSONObject obj = new JSONObject(data);
String client_id = obj.getString("client_id");
String client_secret = obj.getString("client_secret");
tokenCall(client_id, client_secret);
} catch (JSONException | IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getContext(), "error", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(getContext(), "Error in activation",
Toast.LENGTH_SHORT).show();
}
});
}
public void tokenCall(String client_id, String client_secret) {
Call<ResponseBody> token = pentairAPIClient.get_token("password", client_id, client_secret,
supportopObj.getEmail(), supportopObj.getPassword());
token.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
Toast.makeText(getContext(), String.valueOf(response.body()), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Something wrong.....", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(getContext(), "You're on failure", Toast.LENGTH_SHORT).show();
}
});
}
}
I have no error in retrofit, I'm doing debugging and I see all the process, so I getting client id and secret successfully, then I'm getting a timeoutexception in the last onfailure(),
#Override
public void onFailure(Call<ResponseBody> call, Throwable t)
{
Toast.makeText(getContext(), "You're onfailure",Toast.LENGTH_SHORT).show();
}
watch the code, that's the last line. How to fix it? The app not crashes, but in debug he drops timeoutexception like this. t={SocketTimeoutException#830038722120}java.net.SocketTimeoutException: timeout . In OkHttpClient the
readTimeout(10, TimeUnit.SECONDS).connectTimeout(10, TimeUnit.SECONDS).writeTimeout(10, TimeUnit.SECONDS); all are 10, i tried to set it 100, not helps. Help me. Thanks.

Correct code location to check Firebase if a user has been created already?

I've created a method to take a users facebook data, after they login, and create a "user" for them on my firebase database. this method, addUser(), also creates and sets the variables for said user. But I have to leave the method in, login, so it creates my variables, then comment the method out for future testing, or it will reset all the values.
So where can I add "addUser()" to create said user the first time, and make sure it never call it again, as long as the user already exists?
The MainActivity (start and login)
public class MainActivity extends AppCompatActivity {
CallbackManager callbackManager;
ShareDialog shareDialog;
LoginButton login;
ProfilePictureView profile;
Dialog details_dialog;
TextView details_txt;
JSONObject response;
/* Used to track user logging in/out off Facebook */
private AccessTokenTracker mFacebookAccessTokenTracker;
/* A reference to the Firebase */
private Firebase mFirebaseRef;
/* A reference to the Firebase */
private Firebase userRef;
/* Data from the authenticated user */
public static AuthData mAuthData;
/* Listener for Firebase session changes */
private Firebase.AuthStateListener mAuthStateListener;
public static String uName = null;
public static String uEmail = null;
public static String uUrl = null;
public static int mTokens = 50;
public static String uID = null;
public static int getLiveTokens() {
return liveTokens;
}
public static void setLiveTokens(int liveTokens) {
MainActivity.liveTokens = liveTokens;
}
public static int liveTokens = 0;
public static int getLiveSpins() {
return liveSpins;
}
public static void setLiveSpins(int liveSpins) {
MainActivity.liveSpins = liveSpins;
}
public static int liveSpins = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFirebaseRef = new Firebase("https://<url>.firebaseio.com/");
callbackManager = CallbackManager.Factory.create();
login = (LoginButton) findViewById(R.id.login_button);
profile = (ProfilePictureView) findViewById(R.id.picture);
shareDialog = new ShareDialog(this);
login.setReadPermissions("public_profile email");
details_dialog = new Dialog(this);
details_dialog.setContentView(R.layout.dialog_details);
details_dialog.setTitle("Details");
details_txt = (TextView) details_dialog.findViewById(R.id.details);
getLoginDetails(login);
mFacebookAccessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
//Log.i(Tag, "Facebook.AccessTokenTracker.OnCurrentAccessTokenChanged");
// Toast.makeText(getApplicationContext(), "FBAccessTokenChange", Toast.LENGTH_LONG).show();
MainActivity.this.onFacebookAccessTokenChange(currentAccessToken);
}
};
if (AccessToken.getCurrentAccessToken() != null) {
RequestData();
getLoginDetails(login);
getUserInfo();
Toast.makeText(getApplicationContext(), "Already Logged In", Toast.LENGTH_LONG).show();
}
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (AccessToken.getCurrentAccessToken() != null) {
profile.setProfileId(null);
}
}
});
mAuthStateListener = new Firebase.AuthStateListener() {
#Override
public void onAuthStateChanged(AuthData authData) {
// mAuthProgressDialog.hide();
setAuthenticatedUser(authData);
}
};
/* Check if the user is authenticated with Firebase already. If this is the case we can set the authenticated
* user and hide hide any login buttons */
mFirebaseRef.addAuthStateListener(mAuthStateListener);
}
public void addUser() {
this.uID = mAuthData.getUid();
Toast.makeText(getApplicationContext(), "Setting Up User Account", Toast.LENGTH_LONG).show();
Firebase rootRef = new Firebase("https://<url>.firebaseio.com/users/");
Firebase userRef = rootRef.child(mAuthData.getUid() + "/");
userRef.child("name").setValue(mAuthData.getProviderData().get("displayName"));
userRef.child("provider").setValue(mAuthData.getProvider());
userRef.child("email").setValue(mAuthData.getProviderData().get("email"));
userRef.child("tokens").setValue("100");
userRef.child("spins").setValue("100");
userRef.child("totalspins").setValue("0");
userRef.child("topwin").setValue("0");
}
protected void getLoginDetails(LoginButton login){
login.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult login_Result) {
getUserInfo();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException exception) {
}
});
}
// LoginResult login_result
protected void getUserInfo() {
// LoginResult login_result.getAccessToken()
GraphRequest data_request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject json_object, GraphResponse response) {
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
intent.putExtra("jsondata", json_object.toString());
intent.putExtra("Uid", uID);
startActivity(intent);
}
});
Bundle permission_param = new Bundle();
permission_param.putString("fields", "id,name,email,picture.width(120).height(120)");
data_request.setParameters(permission_param);
data_request.executeAsync();
}
public void RequestData() {
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
JSONObject json = response.getJSONObject();
try {
if (json != null) {
String text = "<b>Name :</b> " + json.getString("name") + "<br><br><b>Email :</b> " + json.getString("email") + "<br><br><b>Profile link :</b> " + json.getString("link");
details_txt.setText(Html.fromHtml(text));
profile.setProfileId(json.getString("id"));
uName = json.getString("name");
uEmail = json.getString("email");
uUrl = json.getString("id");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link,email,picture");
request.setParameters(parameters);
request.executeAsync();
}
/**
* This method will attempt to authenticate a user to firebase given an oauth_token (and other
* necessary parameters depending on the provider)
*/
private void authWithFirebase(final String provider, Map<String, String> options) {
if (options.containsKey("error")) {
showErrorDialog(options.get("error"));
} else {
//mAuthProgressDialog.show();
// if the provider is not twitter, we just need to pass in the oauth_token
mFirebaseRef.authWithOAuthToken(provider, options.get("oauth_token"), new AuthResultHandler(provider));
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
private void setAuthenticatedUser(AuthData authData) {
if (authData != null) {
/* show a provider specific status text */
String name = null;
if (authData.getProvider().equals("facebook")) {
name = (String) authData.getProviderData().get("displayName");
} else if (authData.getProvider().equals("anonymous")
|| authData.getProvider().equals("password")) {
name = authData.getUid();
} else {
Toast.makeText(getApplicationContext(), "invalid provider", Toast.LENGTH_LONG).show();
}
if (name != null) {
//success
// Toast.makeText(getApplicationContext(), "Log " + name + " (" + authData.getProvider() + ")", Toast.LENGTH_LONG).show();
}
} else {
}
// Firebase Authenticated
this.mAuthData = authData;
MainActivity.uID = mAuthData.getUid();
//addUser();
/* invalidate options menu to hide/show the logout button */
supportInvalidateOptionsMenu();
}
/**
* Show errors to users
*/
private void showErrorDialog(String message) {
new AlertDialog.Builder(this)
.setTitle("Error")
.setMessage(message)
.setPositiveButton(android.R.string.ok, null)
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
private class AuthResultHandler implements Firebase.AuthResultHandler {
private final String provider;
public AuthResultHandler(String provider) {
this.provider = provider;
}
#Override
public void onAuthenticated(AuthData authData) {
// mAuthProgressDialog.hide();
// Toast.makeText(getApplicationContext(), "Auth Success", Toast.LENGTH_LONG).show();
// Toast.makeText(getApplicationContext(), authData.getUid(), Toast.LENGTH_LONG).show();
// createUser();
setAuthenticatedUser(authData);
String mEmail = authData.getUid();
// uID = authData.getUid();
String mProvide = mAuthData.getProvider();
}
#Override
public void onAuthenticationError(FirebaseError firebaseError) {
//mAuthProgressDialog.hide();
showErrorDialog(firebaseError.toString());
}
}
public void createUser(){
Firebase rootRef = new Firebase("https://<url>.firebaseio.com/");
Firebase userRef = rootRef.child("users").child(mAuthData.getUid());
userRef.child("provider").setValue(mAuthData.getProvider());
userRef.child("provider").setValue(mAuthData.getProviderData().get("displayName)"));
rootRef.createUser(mAuthData.getProviderData().get("email").toString(), mAuthData.getProviderData().get("id").toString(), new Firebase.ValueResultHandler<Map<String, Object>>() {
#Override
public void onSuccess(Map<String, Object> result){
Toast.makeText(getApplicationContext(), "Yes-UID=" + result.get("Uid") , Toast.LENGTH_LONG).show();
}
#Override
public void onError(FirebaseError firebaseError){
Toast.makeText(getApplicationContext(), "Not Created", Toast.LENGTH_LONG).show();
}
});
}
private void logout() {
if (this.mAuthData != null) {
/* logout of Firebase */
mFirebaseRef.unauth();
/* Logout of any of the Frameworks. This step is optional, but ensures the user is not logged into
* Facebook/Google+ after logging out of Firebase. */
if (this.mAuthData.getProvider().equals("facebook")) {
/* Logout from Facebook */
LoginManager.getInstance().logOut();
}
/* Update authenticated user and show login buttons */
setAuthenticatedUser(null);
}
}
#Override
protected void onResume() {
super.onResume();
AppEventsLogger.activateApp(this);
}
#Override
protected void onPause() {
super.onPause();
AppEventsLogger.deactivateApp(this);
}
/* ************************************
* FACEBOOK *
**************************************
*/
private void onFacebookAccessTokenChange(AccessToken token) {
if (token != null) {
//mAuthProgressDialog.show();
mFirebaseRef.authWithOAuthToken("facebook", token.getToken(), new AuthResultHandler("facebook"));
} else {
// Logged out of Facebook and currently authenticated with Firebase using Facebook, so do a logout
if (this.mAuthData != null && this.mAuthData.getProvider().equals("facebook")) {
mFirebaseRef.unauth();
setAuthenticatedUser(null);
}
}
}
public static int getmTokens() {
return getLiveTokens();
}
public static void setmTokens(int mTokens) {
MainActivity.mTokens = mTokens;
}
public static void takemTokens(int mTokens) {
MainActivity.mTokens -= mTokens;
}
public static void givemTokens(final int ttokens) {
//MainActivity.mTokens += tokens;
// TODO
// if (ttokens > MainActivity.getmTopWin()){
// MainActivity.setmTopWin(ttokens);
//}
Firebase ref = new Firebase("https://<url>.firebaseio.com/users/" + MainActivity.uID + "/");
final Firebase tokensRef = ref.child("tokens");
tokensRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int iii = new Integer(dataSnapshot.getValue().toString());
iii += ttokens;
tokensRef.setValue(iii);
setLiveTokens(iii);
checkmTopWin(ttokens);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
//tokensRef.removeEventListener(MainActivity);
}
public static int mSpins = 30;
public static int getmSpins() {
return getLiveSpins();
}
public static void setmSpins(int mspins) {
MainActivity.mSpins = mspins;
}
public static void takemSpins(final int mspins) {
Firebase ref = new Firebase("https://<url>.firebaseio.com/users/" + MainActivity.uID + "/");
final Firebase tokensRef = ref.child("spins");
tokensRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int i = Integer.valueOf(dataSnapshot.getValue().toString());
i -= mspins;
tokensRef.setValue(i);
setLiveSpins(i);
}
#Override
public void onCancelled(FirebaseError firebaseError) {}
});
}
public static void givemSpins(final int mspins){
Firebase ref = new Firebase("https://<url>.firebaseio.com/users/" + MainActivity.uID + "/");
final Firebase tokensRef = ref.child("spins");
tokensRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int i = Integer.valueOf(dataSnapshot.getValue().toString());
i += mspins;
tokensRef.setValue(i);
}
#Override
public void onCancelled(FirebaseError firebaseError) {}
});
}
public static int slotVari = 0;
public static int getSlotVari() {
return slotVari;
}
public static void setSlotVari(int slotVari) {
MainActivity.slotVari = slotVari;
}
public static int mTotalSpins;
public static int getmTotalSpins() {
return mTotalSpins;
}
public static void setmTotalSpins(int mTotalSpins) {
MainActivity.mTotalSpins = mTotalSpins;
}
public static void incmTotalSpins(){
Firebase ref = new Firebase("https://<url>.firebaseio.com/users/" + MainActivity.uID + "/");
final Firebase tokensRef = ref.child("totalspins");
tokensRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int i = Integer.valueOf(dataSnapshot.getValue().toString());
i++;
tokensRef.setValue(i);
}
#Override
public void onCancelled(FirebaseError firebaseError) {}
});
MainActivity.mTotalSpins++;
}
public static int mTopWin;
public static int getmTopWin() {
return mTopWin;
}
public static void setmTopWin(int mTopWin) {
Firebase ref = new Firebase("https://<url>.firebaseio.com/users/" + MainActivity.uID + "/");
Firebase tokensRef = ref.child("topwin");
tokensRef.setValue(mTopWin);
MainActivity.mTopWin = mTopWin;
}
public static void checkmTopWin(final int mTokensWon) {
Firebase ref = new Firebase("https://<url>.firebaseio.com/users/" + MainActivity.uID + "/");
final Firebase tokensRef = ref.child("topwin");
tokensRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int i = Integer.valueOf(dataSnapshot.getValue().toString());
if (i < mTokensWon){
tokensRef.setValue(mTokensWon);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {}
});
}
}
You need to set a preference like FIRST_LAUNCH and check if its true each time your user logs in. First time the application launches, the FIRST_LAUNCH preference won't be found. So call your addUser() function to create a new entry in your FireBase database.
SharedPreferences pref = getSharedPreferences(Constants.ApplicationTag, Activity.MODE_PRIVATE);
if (!pref.contains(Constants.FIRST_LAUNCH)) {
addUser();
pref.edit().putBoolean(Constants.FIRST_LAUNCH, true).commit();
}
So you might be thinking of if an user uninstalls your application and then reinstalls it, the preferences will be gone and the addUser() function will be called again. No problem, you won't get a new Firebase entry as long as the path to the child attribute is the same. The values will be replaced to the specific path (if it does exist), with current information of user.
Now if you want to check if your user already exists in Firebase database you need to add a listener like this. I'm attaching a code sample for better understanding.
Firebase rootRef = new Firebase("https://<url>.firebaseio.com/users/");
Firebase userRef = rootRef.child(mAuthData.getUid() + "/");
userRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// User exists. Do nothing
} else addUser();
}
#Override
public void onCancelled(FirebaseError firebaseError) {}
});

Android Facebook SDK 4.X , how to get Email address and Facebook Access Token to pass it to Web Service

EDIT :
My Question is how to get Email , UserId , Facebook Authentication with Facebook SDK 4.X , at this moment , with Ming Respond , i know how can i get Email , User Id , so my question is how to get Facebook Authentication since Session and GraphUser has just been replaced by LoginManager and AccessToken and there is no information about it?
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import java.util.Arrays;
public class RegisterActivity extends Activity {
private String fbUserID;
private String fbProfileName;
private String fbAuthToken;
private LoginButton fbLoginBtn;
private static final String TAG = "FacebookLogin";
CallbackManager callbackManager;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker profileTracker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_activity);
fbLoginBtn = (LoginButton) findViewById(R.id.connect_with_facebook_button);
fbLoginBtn.setReadPermissions(Arrays.asList("email", "user_photos", "public_profile"));
fbLoginBtn.setBackgroundResource(R.drawable.connect_facebook_button);
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(
AccessToken oldAccessToken,
AccessToken currentAccessToken) {
fbAuthToken = currentAccessToken.getToken();
fbUserID = currentAccessToken.getUserId();
Log.d(TAG, "User id: " + fbUserID);
Log.d(TAG, "Access token is: " + fbAuthToken);
}
};
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(
Profile oldProfile,
Profile currentProfile) {
fbProfileName = currentProfile.getName();
Log.d(TAG, "User name: " + fbProfileName );
}
};
fbLoginBtn.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject user,
GraphResponse response) {
String id = user.optString("id");
String firstName = user.optString("first_name");
String lastName = user.optString("last_name");
String email = user.optString("email");
}
#Override
public void onSaveInstanceState(Bundle savedState) {
super.onSaveInstanceState(savedState);
}
fbLoginBtn.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest.newMeRequest(
loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject me, GraphResponse response) {
if (response.getError() != null) {
// handle error
} else {
String email = me.optString("email");
String id = me.optString("id");
// send email and id to your web server
}
}
}).executeAsync();
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
Easiest answer that i found after hours of searching is as follows,the highest voted answer didn't work for me and email was alway empty
LoginManager.getInstance().registerCallback(mCallbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object,GraphResponse response) {
JSONObject json = response.getJSONObject();
try {
if(json != null){
String text = json.getString("email");
Log.d("email",text);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link,email,picture");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
I believe setting parameters as required fields to the Graph Request is a crucial thing here. You can also use this code with LoginButton, works without issue.
****** Update********
After using this code with many accounts found that if the email isn't verified it won't be returned, in such case following code helped along with abo
facebookLoginButton.setReadPermissions("email");
Hope this helps further
I must add extra field for user Email.
//register facebook login callback
LoginManager.getInstance().registerCallback(mCallbackManager, new FacebookCallback<LoginResult>()
{
#Override
public void onSuccess (LoginResult loginResult)
{
Log.d(TAG, "FB: login success");
showLoading(true);
final String token = loginResult.getAccessToken().getToken();
//prepare fields with email
String[] requiredFields = new String[]{"email"};
Bundle parameters = new Bundle();
parameters.putString("fields", TextUtils.join(",", requiredFields));
GraphRequest requestEmail = new GraphRequest(loginResult.getAccessToken(), "me", parameters, null, new GraphRequest.Callback()
{
#Override
public void onCompleted (GraphResponse response)
{
if (response != null)
{
GraphRequest.GraphJSONObjectCallback callbackEmail = new GraphRequest.GraphJSONObjectCallback()
{
#Override
public void onCompleted (JSONObject me, GraphResponse response)
{
if (response.getError() != null)
{
Log.d(TAG, "FB: cannot parse email");
showDialog(getString(R.string.dialog_message_unknown_error));
showLoading(false);
}
else
{
String email = me.optString("email");
// send email and id to your web server
//...
}
}
};
callbackEmail.onCompleted(response.getJSONObject(), response);
}
}
});
requestEmail.executeAsync();
}
#Override
public void onCancel ()
{
Log.d(TAG, "FB: login cancel");
showDialog(getString(R.string.dialog_message_unknown_error));
}
#Override
public void onError (FacebookException e)
{
Log.d(TAG, "FB: login error " + e.getMessage());
showDialog(getString(R.string.dialog_message_unknown_error));
}
});

Categories