Awkward session error with magento cookie parsing in Android App - android

I am working on an Android app which uses sessions by managing cookies from an API based on magento backend.
On the app side, I am using Volley Library for network request. I have successfully got the network response and from that I have fetched the "Set-Cookie" value. Now when I am attaching this cookie to the header but the server doesn't validate my session.
The strange thing is I tried to request the same JSON request from a rest client and then used the cookie from that and added to the header as a static value and then I was provided session access. I completely have no idea regarding what is going on. Why the cookies from rest client is working while the cookie value from my network response doesn't.
Here is my SignIn Activity code where I am doing a login json request and storing the cookie value.
package com.paaltao.activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NetworkResponse;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.github.mrengineer13.snackbar.SnackBar;
import com.paaltao.R;
import com.paaltao.classes.MyApp;
import com.paaltao.classes.PersistentCookieStore;
import com.paaltao.classes.ProgressWheel;
import com.paaltao.classes.SharedPreferenceClass;
import com.paaltao.logging.L;
import com.paaltao.network.VolleySingleton;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import static com.paaltao.extras.Keys.UserCredentials.*;
import static com.paaltao.extras.urlEndPoints.BASE_URL;
import static com.paaltao.extras.urlEndPoints.LOGIN;
import static com.paaltao.extras.urlEndPoints.UAT_BASE_URL;
public class SignInActivity extends AppCompatActivity {
private static final String SET_COOKIE_KEY = "Set-Cookie";
private static final String COOKIE_KEY = "Cookie";
private static final String SESSION_COOKIE = "sessionid";
Button SignUpBtn;
Button SignInBtn;
ProgressWheel progressBar;
EditText email, password;
TextView forgotPassword;
String emailId,accessToken,api_ver,token,firstName,lastName,cookie,newCookie;
Boolean login_success;
SharedPreferenceClass preferenceClass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
Toolbar toolbar = (Toolbar) this.findViewById(R.id.app_bar);
toolbar.setTitleTextColor(Color.WHITE);
toolbar.setBackgroundColor(getResources().getColor(R.color.transparent));
this.setSupportActionBar(toolbar);
this.setTitle("Sign in");
initiate();
onItemClick();
}
public void initiate() {
SignUpBtn = (Button) findViewById(R.id.signUpBtn);
email = (EditText) findViewById(R.id.email_field);
password = (EditText) findViewById(R.id.password_field);
SignInBtn = (Button) findViewById(R.id.signInBtn);
forgotPassword = (TextView) findViewById(R.id.forgot_password);
progressBar = (ProgressWheel)findViewById(R.id.action_progress);
preferenceClass = new SharedPreferenceClass(getApplicationContext());
}
public boolean validationCheck() {
if (email.getText().toString().length() == 0)
email.setError("Please provide your email. Your email must be in the format abc#xyz.com");
else if (password.getText().toString().length() == 0)
password.setError("Please provide a password");
else return true;
return false;
}
public void onItemClick() {
SignInBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (validationCheck()) {
sendJsonRequest();
}
}
});
SignUpBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SignInActivity.this, SignUpActivity.class);
startActivity(intent);
}
});
forgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SignInActivity.this, ForgotPasswordActivity.class);
startActivity(intent);
}
});
}
public static String getRequestUrl() {
return UAT_BASE_URL
+ LOGIN;
}
public void sendJsonRequest() {
progressBar.setVisibility(View.VISIBLE);
final JSONObject jsonObject = new JSONObject();
final JSONObject signIn = new JSONObject();
try {
jsonObject.put("email", email.getText().toString());
jsonObject.put("password", password.getText().toString());
signIn.put("emailSignIn", jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, getRequestUrl(), signIn, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
if (progressBar.getVisibility() == View.VISIBLE) {
progressBar.setVisibility(View.GONE);
}
parseJSONResponse(jsonObject);
//Calling the Snackbar
Log.e("response", jsonObject.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
if (progressBar.getVisibility() == View.VISIBLE) {
progressBar.setVisibility(View.GONE);
}
if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError) {
new SnackBar.Builder(SignInActivity.this)
.withMessage("No Internet Connection!")
.withTextColorId(R.color.white)
.withDuration((short) 6000)
.show();
} else if (volleyError instanceof AuthFailureError) {
//TODO
} else if (volleyError instanceof ServerError) {
//TODO
} else if (volleyError instanceof NetworkError) {
//TODO
} else if (volleyError instanceof ParseError) {
//TODO
}
}
}) {
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
// since we don't know which of the two underlying network vehicles
// will Volley use, we have to handle and store session cookies manually
// MyApp.get().checkSessionCookie(response.headers);
L.m(response.headers.toString());
L.m(Arrays.toString(response.data));
L.m(response.headers.get("Set-Cookie"));
preferenceClass.saveCookiee(response.headers.get("Set-Cookie"));
cookie = response.headers.get("Set-Cookie");
String[] splitCookie = cookie.split(";");
String[] splitSessionId = splitCookie[0].split("=");
newCookie = splitSessionId[1];
//cookie = response.headers.values().toString();
Log.e("split",newCookie);
preferenceClass.saveCookie(newCookie);
return super.parseNetworkResponse(response);
}
#Override
public Map<String, String> getHeaders ()throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null
|| headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
// MyApp.get().addSessionCookie(headers);
return headers;
}
}
;
requestQueue.add(jsonObjectRequest);
}
public void parseJSONResponse(JSONObject jsonObject) {
if (jsonObject == null || jsonObject.length() == 0) {
return;
}
try {
JSONObject dataObject = jsonObject.getJSONObject(KEY_DATA);
JSONObject signInObject = dataObject.getJSONObject(KEY_SIGN_IN);
JSONObject accessTokenObject = signInObject.getJSONObject(KEY_ACCESS_TOKEN);
JSONObject errorNodeObject = dataObject.getJSONObject(KEY_ERROR_NODE);
if(dataObject.has(KEY_VENDOR)){
if (dataObject.isNull(KEY_VENDOR)){
return;
}
else {JSONObject vendorObject = dataObject.getJSONObject(KEY_VENDOR);
if(vendorObject != null){
String vendor_login = vendorObject.getString(KEY_HAS_SHOP);
if(vendor_login != null && vendor_login.contains("true")){
preferenceClass.saveVendorLoginSuccess(vendor_login);
}}}
}
emailId = signInObject.getString(KEY_EMAIL);
firstName = signInObject.getString(KEY_FIRST_NAME);
lastName = signInObject.getString(KEY_LAST_NAME);
login_success = signInObject.getBoolean(KEY_USER_LOGIN_SUCCESS);
preferenceClass.saveFirstName(firstName);
preferenceClass.saveLastName(lastName);
preferenceClass.saveUserEmail(emailId);
if(accessTokenObject.has(KEY_TOKEN)){
token = accessTokenObject.getString(KEY_TOKEN);}
String errorCode = errorNodeObject.getString(KEY_ERROR_CODE);
String message = errorNodeObject.getString(KEY_MESSAGE);
if (login_success){
Log.e("TAG",login_success.toString());
if (token!= null && token.length()!=0){
preferenceClass.saveAccessToken(token);
preferenceClass.saveUserEmail(emailId);
Intent intent = new Intent(SignInActivity.this,HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
}
else{
Log.e("TAG",login_success.toString());
new SnackBar.Builder(SignInActivity.this)
.withMessage("Username or Password is Incorrect!")
.withTextColorId(R.color.white)
.withDuration((short) 6000)
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
and this is the code for the fragment where I am doing a check session test with the stored cookie received from network response (Note: I replaced the cookie with the one I got from rest client and it worked!!)
package com.paaltao.fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.support.v4.app.Fragment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NetworkResponse;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpClientStack;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.HttpStack;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.github.mrengineer13.snackbar.SnackBar;
import com.paaltao.R;
import com.paaltao.activity.AddressActivity;
import com.paaltao.activity.IntroPageActivity;
import com.paaltao.activity.PaaltaoInfo;
import com.paaltao.activity.EditProfileActivity;
import com.paaltao.classes.MyApp;
import com.paaltao.classes.PersistentCookieStore;
import com.paaltao.classes.SharedPreferenceClass;
import com.paaltao.logging.L;
import com.paaltao.network.VolleySingleton;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.CookieStore;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import cn.pedant.SweetAlert.SweetAlertDialog;
import static com.paaltao.extras.Keys.UserCredentials.KEY_ACCESS_TOKEN;
import static com.paaltao.extras.Keys.UserCredentials.KEY_DATA;
import static com.paaltao.extras.Keys.UserCredentials.KEY_ERROR_CODE;
import static com.paaltao.extras.Keys.UserCredentials.KEY_ERROR_NODE;
import static com.paaltao.extras.Keys.UserCredentials.KEY_MESSAGE;
import static com.paaltao.extras.Keys.UserCredentials.KEY_SIGN_OUT;
import static com.paaltao.extras.urlEndPoints.BASE_URL;
import static com.paaltao.extras.urlEndPoints.SIGN_OUT;
import static com.paaltao.extras.urlEndPoints.UAT_BASE_URL;
//This is a user account fragment.
public class AccountFragment extends Fragment {
private static final String SET_COOKIE_KEY = "Set-Cookie";
private static final String COOKIE_KEY = "Cookie";
private static final String SESSION_COOKIE = "sessionid";
RelativeLayout accountLink,my_address,signOut;
View view;
String accessToken;
TextView firstName,lastName,about,terms,privacy,notificationSettings;
SharedPreferenceClass preferenceClass;
SweetAlertDialog dialog;
Context context;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_account, container, false);
initialize();
onItemClick();
return view;
}
public static String getRequestUrl() {
return UAT_BASE_URL
+ SIGN_OUT;
}
public void sendJsonRequest(){
final JSONObject jsonObject = new JSONObject();
final JSONObject signOut = new JSONObject();
try{
jsonObject.put("accessToken","67drd56g");
signOut.put("signOut", jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,getRequestUrl(),signOut,new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Log.e("error", jsonObject.toString());
Log.e("json", signOut.toString());
parseJSONResponse(jsonObject);
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError) {
new SnackBar.Builder(getActivity())
.withMessage("No Internet Connection!")
.withTextColorId(R.color.white)
.withDuration((short) 6000)
.show();
} else if (volleyError instanceof AuthFailureError) {
//TODO
} else if (volleyError instanceof ServerError) {
//TODO
} else if (volleyError instanceof NetworkError) {
//TODO
} else if (volleyError instanceof ParseError) {
//TODO
}
}
});
requestQueue.add(jsonObjectRequest);
}
public void parseJSONResponse(JSONObject jsonObject) {
if (jsonObject == null || jsonObject.length() == 0) {
return;
}
try {
JSONObject dataObject = jsonObject.getJSONObject(KEY_DATA);
JSONObject signOutObject = jsonObject.getJSONObject(KEY_SIGN_OUT);
JSONObject errorNodeObject = dataObject.getJSONObject(KEY_ERROR_NODE);
accessToken = signOutObject.getString(KEY_ACCESS_TOKEN);
String errorCode = errorNodeObject.getString(KEY_ERROR_CODE);
String message = errorNodeObject.getString(KEY_MESSAGE);
if (errorCode.equals("200")){
preferenceClass.clearAccessToken();
preferenceClass.clearFirstName();
preferenceClass.clearLastName();
preferenceClass.clearUserEmail();
Log.e("accessToken",accessToken);
Intent intent = new Intent(getActivity(),IntroPageActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
getActivity().finish();
}
else{
new SnackBar.Builder(getActivity())
.withMessage("Error in signing out")
.withTextColorId(R.color.white)
.withDuration((short) 6000)
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void sendJsonRequest1(){
final JSONObject jsonObject = new JSONObject();
final JSONObject sessionCheck = new JSONObject();
try{
jsonObject.put("accessToken","67drd56g");
sessionCheck.put("checkSession", jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,getRequestUrl1(),sessionCheck,new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Log.e("error", jsonObject.toString());
Log.e("json", sessionCheck.toString());
Log.e("url",getRequestUrl());
L.m(jsonObject.toString());
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError) {
} else if (volleyError instanceof AuthFailureError) {
//TODO
} else if (volleyError instanceof ServerError) {
//TODO
} else if (volleyError instanceof NetworkError) {
//TODO
} else if (volleyError instanceof ParseError) {
//TODO
}
}
})
{
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
// since we don't know which of the two underlying network vehicles
// will Volley use, we have to handle and store session cookies manually
// MyApp.get().checkSessionCookie(response.headers);
//L.m(response.headers.toString());
return super.parseNetworkResponse(response);
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null
|| headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
String sessionId = preferenceClass.getCookie();
Log.e("cOOOKIE","frontend="+sessionId);
Log.e("sessionid","frontend=7fgenogpffjvvmdg1gf439hta7");
// headers.put(COOKIE_KEY,"frontend="+sessionId);
headers.put(COOKIE_KEY,"frontend=e7qfldgsnf7aop381a8vk3b866");
return headers;
}};
requestQueue.add(jsonObjectRequest);
}
private String getRequestUrl1() {
return UAT_BASE_URL+"checkSession";
}
public void initialize(){
accountLink = (RelativeLayout)view.findViewById(R.id.account_link);
my_address = (RelativeLayout)view.findViewById(R.id.my_address);
signOut = (RelativeLayout)view.findViewById(R.id.signOut);
preferenceClass = new SharedPreferenceClass(getActivity());
firstName = (TextView)view.findViewById(R.id.firstName);
lastName = (TextView)view.findViewById(R.id.lastName);
about = (TextView)view.findViewById(R.id.about);
terms = (TextView)view.findViewById(R.id.terms);
privacy = (TextView)view.findViewById(R.id.privacy);
if(preferenceClass.getFirstName() != null)
firstName.setText(preferenceClass.getFirstName());
if(preferenceClass.getLastName() != null)
lastName.setText(preferenceClass.getLastName());
notificationSettings = (TextView)view.findViewById(R.id.notification_settings);
}
public void onItemClick(){
notificationSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendJsonRequest1();
}
});
accountLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), EditProfileActivity.class));
}
});
my_address.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), AddressActivity.class));
}
});
signOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
confirmSignOut();
}
});
about.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), PaaltaoInfo.class);
intent.putExtra("page","about_paaltao");
startActivity(intent);
}
});
terms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), PaaltaoInfo.class);
intent.putExtra("page","terms");
startActivity(intent);
}
});
privacy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), PaaltaoInfo.class);
intent.putExtra("page","privacy_policy");
startActivity(intent);
}
});
}
public void confirmSignOut(){
dialog = new SweetAlertDialog(getActivity(), SweetAlertDialog.NORMAL_TYPE);
dialog.setTitleText("Signout")
.setContentText("Are you sure you want to sign out?")
.setConfirmText("Yes")
.setCancelText("No")
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sDialog) {
sendJsonRequest();
}
})
.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sDialog) {
dialog.cancel();
}
})
.show();
}
}
There is no structural difference between the rest client cookie and the one recieved in app:
rest client cookie : frontend=48b1i38fgls4d0241mp6d6rrr0
app side cookie : frontend=86n349m3patu37eud00ntobd90
Thanks in advance. It will be a life saver if some one can help.

Related

How to show image fetched from mysqldatabase to imageview

Here this is the layout in which I have to set the image of the user who successfully logged in
and I have saved the url of the image in the table where all the details of the users are there....
So what I was trying is I am fetching the url of the image from the database and then tried to set it into imageview.. I have checked that the url is comming to the variable...
so as you can see in the above image it is not setting the image in imageview but when I assign the url first to the imgurl variable at the time of defining the variable then it works fine...
I don't know why this is happening... am I doing anything wrong or is there any other way to achieve this?
This is the code of the file...
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class Dashboard extends AppCompatActivity {
TextView usrname;
ImageView profileimg;
public static String imgurl = "";//here
/**
* Shared Preferences
**/
SharedPreferences sharedPreferences;
public static final String mypreference = "mypref";
public static final String Name = "nameKey";
public static final String Email = "emailKey";
/**
* Shared Preferences
**/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
profileimg = findViewById(R.id.iv_display_image);
usrname = findViewById(R.id.tv_username);
/**Shared Preferences**/
sharedPreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
/**Shared Preferences**/
//fetching session data
String name = sharedPreferences.getString(Name, "0");
usrname.setText(name);
fetchimg(name);
LoadImage loadImage = new LoadImage(profileimg);
Log.d("Oncreate img url", imgurl);
loadImage.execute(imgurl);
}
private void fetchimg(String name) {
StringRequest request = new StringRequest(Request.Method.POST, "https://**url**//fetchimg.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.startsWith("Here")) {
String urlstr = getUrl(response, "Here ");
seturl(urlstr);
Log.d("urlstr value:", urlstr);
} else {
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
Log.d("vOLLEY ERROR", response.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
Log.d("vOLLEY ERROR", error.getMessage().toString());
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("login_name", "xxxxx");
params.put("login_pass", "xxxxx");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(Dashboard.this);
requestQueue.add(request);
}
private void seturl(String urlstr) {
this.imgurl = urlstr;
Log.d("Image url set inside seturl", imgurl);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.dashboardmenu, menu);
return true;
}
public void openeditprofile(View view) {
startActivity(new Intent(this, EditProfileActivity.class));
}
private class LoadImage extends AsyncTask<String, Void, Bitmap> {
ImageView imageView;
public LoadImage(ImageView profileimg) {
this.imageView = profileimg;
}
#Override
protected Bitmap doInBackground(String... strings) {
String urlLink = strings[0];
Bitmap bitmap = null;
try {
InputStream inputStream = new java.net.URL(urlLink).openStream();
bitmap = BitmapFactory.decodeStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
profileimg.setImageBitmap(bitmap);
}
}
public static String getUrl(String string, String word) {
// Check if the word is present in string
// If found, remove it using removeAll()
if (string.contains(word)) {
// To cover the case
// if the word is at the
// beginning of the string
// or anywhere in the middle
String tempWord = word + " ";
string = string.replaceAll(tempWord, "");
// To cover the edge case
// if the word is at the
// end of the string
tempWord = " " + word;
string = string.replaceAll(tempWord, "");
}
// Return the resultant string
return string;
}
}
You are fetching image asynchronously, your Asynctask execute will be called with empty imgUrl as it not already fetched, move AsyncTask execution code in onResponse of fetching
private void fetchimg(String name) {
StringRequest request = new StringRequest(Request.Method.POST, "https://**url**//fetchimg.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.startsWith("Here")) {
String urlstr = getUrl(response, "Here ");
seturl(urlstr);
//here the url is ready to consume
Log.d("urlstr value:", urlstr);
//load the image now
LoadImage loadImage = new LoadImage(profileimg);
Log.d("Oncreate img url", imgurl);
loadImage.execute(imgurl);
} else {
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
Log.d("vOLLEY ERROR", response.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
Log.d("vOLLEY ERROR", error.getMessage().toString());
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("login_name", "xxxxx");
params.put("login_pass", "xxxxx");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(Dashboard.this);
requestQueue.add(request);
}
use **Glide** to display Image from Url into image view.
You have to add glide lib in app-level build.gradle file.
implementation 'com.github.bumptech.glide:glide:4.12.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0'
Glide.with(this).load(url)
.transform(CenterCrop(), RoundedCorners(radius))
.placeholder(R.drawable.drawable_image_placeholder)
.error(R.drawable.drawable_image_placeholder)
.into(ivProfile)
drawable_image_placeholder is the default imageview that displays
when getting the error to load the image. ivProfile is imageview .

Android volley token changes every request

I want to get the results about imei adresses after my inquiry on the inquiry site. The site has token input during the query and I can get this token as follows. But when i run the second volley queue i soppose the token changes and the result doesn't come. How can I solve this problem. The site that i questioned the imei adress and my codes are below.
package com.myapp.query;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import android.os.Bundle;
import android.widget.Toast;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import androidx.appcompat.app.AppCompatActivity;
public class imeiSorgulama extends AppCompatActivity {
StringRequest stringRequest;
RequestQueue queue;
String token, tag, value, tag2, value2, result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_imei_sorgulama);
queue = Volley.newRequestQueue(this);
final String url = "https://www.turkiye.gov.tr/imei-sorgulama";
stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
tag = "<input type=\"hidden\" name=\"token\" value=\"";
value = response.substring(response.indexOf(tag) + tag.length());
token = value.substring(0, value.indexOf("\""));
try {
token = URLEncoder.encode(token,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
imeiQuery();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(imeiSorgulama.this, error+"", Toast.LENGTH_SHORT).show();
}
}
);
queue.add(stringRequest);
}
private void imeiQuery() {
final String url = "https://www.turkiye.gov.tr/imei-sorgulama?submit";
stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
tag2 = "<dl class=\"compact\">";
value2 = response.substring(response.indexOf(tag2) + tag2.length());
result = value2.substring(0, value2.indexOf("</dl>"));
Toast.makeText(imeiSorgulama.this, result+"", Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(imeiSorgulama.this, error+"", Toast.LENGTH_SHORT).show();
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("txtImei", "545454545454545");
params.put("token=", token);
return params;
}
};
queue.add(stringRequest);
}
}

Run a piece of code only once in background whenever user login

Ia trying to get user locations whenever its login the application.I made a class and its working perfect seperately but when I embed it in my main project it didnt submit the location values in database.I want that whenever user login that class run for only once and submits its coordinates in database.
Here Is the code of my location class :
I want that when user login this class class run for once only all I want is to get user location when its loged in.
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
public class getposition extends AppCompatActivity {
String URL_LOGIN = "api"
Button btn;
TextView tv1,tv2;
LocationManager locationManager;
static final int REQUEST_LOCATION = 1;
String lg, lt , chk;
String lat_long;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_getposition);
btn = findViewById(R.id.send);
tv1 = findViewById(R.id.lang);
tv2 = findViewById(R.id.lat);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
chk = getLocation();
loadlocation();
if(chk != "false"){
String foo = chk;
String[] split = foo.split("_");
lt = split[0];
lg = split[1];
Toast.makeText(getApplicationContext(),chk,Toast.LENGTH_LONG).show();
}
}
private void loadlocation() {
final RequestQueue requestQueue = Volley.newRequestQueue(getposition.this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
tv1.setText(response);
tv2.setText(response);
requestQueue.stop();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
tv1.setText("Something went wrong///");
error.printStackTrace();
requestQueue.stop();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("user_id","12" );
params.put("user_lat", lt);
params.put("user_lng", lg);
return params;
}
};
VolleySingleton.getInstance(getposition.this).addToRequestQueue(stringRequest);
}
public String getLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
else {
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
double latt = location.getLatitude();
double lng = location.getLongitude();
lat_long = latt + "_" + lng;
tv1.setText("Latitude: " + latt);
tv2.setText("Longitude: " + lng);
} else {
lat_long = "false";
tv1.setText("Unable to find correct location.");
tv2.setText("Unable to find correct location. ");
}
}
return lat_long;
}
}
This is my login class:
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.vshine.neuron.riseshine.VolleySingleton;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.vshine.neuron.riseshine.MainActivity;
import com.vshine.neuron.riseshine.R;
import com.vshine.neuron.riseshine.getregistered;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class login extends AppCompatActivity {
Button login_button;
ImageButton GetRegistered;
EditText userName_edt, password_edt;
String user_name, password;
Context mctx;
String json_response;
String URL_LOGIN = "api"
public static final String PREFS_NAME = "MyPreferenceFiles";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mctx = this;
initBasic();
initLogin();
}
private void initBasic() {
login_button = (Button) findViewById(R.id.login_button);
GetRegistered = (ImageButton) findViewById(R.id.register);
userName_edt = (EditText) findViewById(R.id.user_name);
password_edt = (EditText) findViewById(R.id.password);
}
private void initLogin() {
GetRegistered.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent= new Intent(login.this,getregistered.class);
startActivity(intent);
}
});
login_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
user_name = userName_edt.getText().toString();
password = password_edt.getText().toString();
if (user_name.trim().equals("") || password.trim().equals("")) {
ShowToastMessage("Please enter the credentials properly");
}
else {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting response to json object
JSONObject obj = new JSONObject(response);
//if no error in response
// json_response = j_obj.getString("message");
if (response!= null) {
// Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
json_response = obj.getString("message");
// ShowToastMessage(json_response);
//getting the user from the response
JSONObject userJson = obj.getJSONObject("response");
//creating a new user object
String u_id = String.valueOf(userJson.getInt("id"));
// ShowToastMessage(u_id);
//storing the user in shared preferences
SharedPreferences.Editor editor = getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("User_id", u_id);
editor.commit();
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
} else {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("user_name", user_name);
params.put("password", password);
return params;
}
};
VolleySingleton.getInstance(login.this).addToRequestQueue(stringRequest);
}
}
});
}
private void ShowToastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}

Unable to get json data on emulator in android studio

I am using android studio ,mysql database and notepad++ for php files.
The database has a table named login and has 3 attributes:
id
firstname
lastname
all are of the type varchar.
When I try to execute this code of android and php I don't get any error and the code is executed successfully but the data from the database does not get displayed on the emulator.
*******************Android code************************
package com.example.digi.college;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
EditText firstname, lastname, id;
Button insert, show;
TextView result;
RequestQueue requestQueue;
String inserturl = "http://192.168.1.104/android/register.php";
String displayurl = "http://192.168.1.104/android/display.php";
String hello="hello how are you";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
id = (EditText) findViewById(R.id.editText);
firstname = (EditText) findViewById(R.id.editText2);
lastname = (EditText) findViewById(R.id.editText3);
insert = (Button) findViewById(R.id.button);
show = (Button) findViewById(R.id.button2);
result = (TextView) findViewById(R.id.textView);
requestQueue = Volley.newRequestQueue(getApplicationContext());
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
displayurl, new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
try {
JSONArray students = response.getJSONArray("students");
for (int i = 0; i < students.length(); i++) {
JSONObject login = students.getJSONObject(i);
String id = login.getString("id");
String firstname = login.getString("firstname");
String lastname = login.getString("lastname");
result.append(id+" "+firstname+" "+lastname+"\n");
}
result.append("===\n");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
}
});
insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringRequest request = new StringRequest(Request.Method.POST, inserturl, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> parameters = new HashMap<String, String>();
parameters.put("id",id.getText().toString());
parameters.put("firstname",firstname.getText().toString());
parameters.put("lastname",lastname.getText().toString());
return parameters;
}
};
requestQueue.add(request);
}
});
}
}
*****************Php Code for insert.php******************
<?php
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$id=$_POST['id'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$db = mysql_connect("localhost", "root", "");
mysql_select_db("ntu", $db);
$sql = mysql_query("INSERT INTO login (id,firstname,lastname) VALUES ('$id','$firstname', '$lastname')");
mysql_close($db);
}
?>
*************Php code for display.php*************
<?php
$db = mysql_connect("localhost", "root", "");
mysql_select_db("ntu", $db);
$sql = mysql_query("SELECT * FROM login");
$a = array();
$index = 0;
while($row = mysql_fetch_assoc($sql))
{
$a[$index] = $row;
$index++;
}
echo json_encode(array("students"=>$a));
mysql_close($db);
?>
I think you have missed the put the internet permission in androidmanifeast.xml file give internet permission and check.

Facebook integration in android application [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
Is there any api for facebook to integration in android?
I got a requirement to publish images to facebook through android application.
Please give links or suggestions regarding this..
If you had taken the time to Google "Android Facebook SDK" you'd have immediately found the official Android Facebook SDK: http://github.com/facebook/facebook-android-sdk
Having used it in a project I can say it's a little rough around the edges as the new oAuth / Graph API based stuff is quite young, but it works well with a little tweaking.
import java.awt.BorderLayout;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import com.sun.medialib.mlib.Image;
import net.xeomax.FBRocket.FBRocket;
import net.xeomax.FBRocket.Facebook;
import net.xeomax.FBRocket.LoginListener;
import net.xeomax.FBRocket.ServerErrorException;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Handler.Callback;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
public class TestRocket extends Activity implements LoginListener {
public FBRocket fbRocket;
public static String currentFileName ;
public final String images[] = {"http://safesport.site40.net/tv.jpg"};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
shareFacebook();
}
public void shareFacebook() {
fbRocket = new FBRocket(this, "test",
"ommited");
if (fbRocket.existsSavedFacebook()) {
fbRocket.loadFacebook();
return;
} else {
//fbRocket.login(R.layout.testrocket);
fbRocket.login(R.layout.testrocket);
}
}
public void onLoginFail() {
fbRocket.displayToast("Login failed!");
//fbRocket.login(R.layout.correr);
}
public String setFileName(String filename) {
// TODO Auto-generated method stub
TestRocket.currentFileName = filename;
return filename;
}
public void onLoginSuccess(Facebook facebook) {
SimpleDateFormat sdf = new SimpleDateFormat("dd:MM:yyyy");
SimpleDateFormat sdf1 = new SimpleDateFormat("HH:mm:ss");
String data = sdf.format(new Date());
String time = sdf1.format(new Date());
try {
facebook.setStatus("Start Walk:"+time+"\n"+ "Day:"+data+"\n"+"Where:"+"\n"
+"http://maps.google.com/?q=http://safesport.site40.net/"+currentFileName);
fbRocket.displayToast("Status Posted Successfully!! ");
return ;
} catch (ServerErrorException e) {
if (e.notLoggedIn()) {
fbRocket.login(R.layout.ciclismo);
} else {
System.out.println(e);
}
}
}
}
I explained the process in detail together with a simple sample code. You can find it here:
http://developer.blog.appxtream.com/?p=34
Download source code from here (https://deepshikhapuri.wordpress.com/2017/04/07/get-location-of-facebook-user-using-graph-api-in-android/)
package facebooklocation.facebooklocation;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.HttpMethod;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import org.json.JSONObject;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
CallbackManager callbackManager;
ImageView iv_image, iv_facebook;
TextView tv_name, tv_email, tv_dob, tv_location, tv_facebook;
LinearLayout ll_facebook;
String str_facebookname, str_facebookemail, str_facebookid, str_birthday, str_location;
boolean boolean_login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
getKeyHash();
listener();
}
private void init() {
iv_image = (ImageView) findViewById(R.id.iv_image);
iv_facebook = (ImageView) findViewById(R.id.iv_facebook);
tv_name = (TextView) findViewById(R.id.tv_name);
tv_email = (TextView) findViewById(R.id.tv_email);
tv_dob = (TextView) findViewById(R.id.tv_dob);
tv_location = (TextView) findViewById(R.id.tv_location);
tv_facebook = (TextView) findViewById(R.id.tv_facebook);
ll_facebook = (LinearLayout) findViewById(R.id.ll_facebook);
FacebookSdk.sdkInitialize(this.getApplicationContext());
}
private void listener() {
tv_facebook.setOnClickListener(this);
ll_facebook.setOnClickListener(this);
iv_facebook.setOnClickListener(this);
}
private void facebookLogin() {
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.e("ONSUCCESS", "User ID: " + loginResult.getAccessToken().getUserId()
+ "\n" + "Auth Token: " + loginResult.getAccessToken().getToken()
);
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
boolean_login = true;
tv_facebook.setText("Logout from Facebook");
Log.e("object", object.toString());
str_facebookname = object.getString("name");
try {
str_facebookemail = object.getString("email");
} catch (Exception e) {
str_facebookemail = "";
e.printStackTrace();
}
try {
str_facebookid = object.getString("id");
} catch (Exception e) {
str_facebookid = "";
e.printStackTrace();
}
try {
str_birthday = object.getString("birthday");
} catch (Exception e) {
str_birthday = "";
e.printStackTrace();
}
try {
JSONObject jsonobject_location = object.getJSONObject("location");
str_location = jsonobject_location.getString("name");
} catch (Exception e) {
str_location = "";
e.printStackTrace();
}
fn_profilepic();
} catch (Exception e) {
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, name, email,gender,birthday,location");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
if (AccessToken.getCurrentAccessToken() == null) {
return; // already logged out
}
new GraphRequest(AccessToken.getCurrentAccessToken(), "/me/permissions/", null, HttpMethod.DELETE, new GraphRequest
.Callback() {
#Override
public void onCompleted(GraphResponse graphResponse) {
LoginManager.getInstance().logOut();
LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile,email"));
facebookLogin();
}
}).executeAsync();
}
#Override
public void onError(FacebookException e) {
Log.e("ON ERROR", "Login attempt failed.");
AccessToken.setCurrentAccessToken(null);
LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile,email,user_birthday"));
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
callbackManager.onActivityResult(requestCode, resultCode, data);
} catch (Exception e) {
}
}
private void getKeyHash() {
// Add code to print out the key hash
try {
PackageInfo info = getPackageManager().getPackageInfo("facebooklocation.facebooklocation", PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}
private void fn_profilepic() {
Bundle params = new Bundle();
params.putBoolean("redirect", false);
params.putString("type", "large");
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"me/picture",
params,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
Log.e("Response 2", response + "");
try {
String str_facebookimage = (String) response.getJSONObject().getJSONObject("data").get("url");
Log.e("Picture", str_facebookimage);
Glide.with(MainActivity.this).load(str_facebookimage).skipMemoryCache(true).into(iv_image);
} catch (Exception e) {
e.printStackTrace();
}
tv_name.setText(str_facebookname);
tv_email.setText(str_facebookemail);
tv_dob.setText(str_birthday);
tv_location.setText(str_location);
}
}
).executeAsync();
}
#Override
public void onClick(View view) {
if (boolean_login) {
boolean_login = false;
LoginManager.getInstance().logOut();
tv_location.setText("");
tv_dob.setText("");
tv_email.setText("");
tv_name.setText("");
Glide.with(MainActivity.this).load(R.drawable.profile).into(iv_image);
tv_facebook.setText("Login with Facebook");
} else {
LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile,email,user_birthday,user_location"));
facebookLogin();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
LoginManager.getInstance().logOut();
}
}

Categories

Resources