Saving JSON Facebook results in SharedPref - java

I'm trying to saves Facebook id and facebook usrname in my SharedPreferences on my android app to use it whenever and wherever i want, but logcat returns me "empty"
here is my "Oncomplete" Facebook method:
public void onSuccess(LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
String result = response.toString();
SharedPreferences pref = getActivity().getPreferences(0);
SharedPreferences.Editor edt = pref.edit();
edt.putString("result", result);
edt.commit();
Log.i("string","PROVAAAAAA");
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link");
request.setParameters(parameters);
request.executeAsync();
}
i noticed that logcat doesn't writes "PROVAAAAAAA"
And here is my callback method:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
CallbackManager callbackManager = CallbackManager.Factory.create();
callbackManager.onActivityResult(requestCode, resultCode, data);
SharedPreferences pref = getActivity().getPreferences(0);
SharedPreferences.Editor edt = pref.edit();
String id = pref.getString("facebook_id", "empty");
Log.i("RESULT", id );
Log.i("RESULT", "***************");
edt.commit();
}

You're using the Activity#getPreferences method when what you really want is PreferenceManager#getDefaultSharedPreferences. The former is described as being "Activity persistent state", which may be why you're having trouble accessing it.
Try replacing all occurrences of getActivity().getPreferences(0) with PreferenceManager.getDefaultSharedPreferences(getActivity()).

Related

Android: Save image from Internal storage in SharedPreferences and display it

I'm trying to load a image from my phone and apply it to an ImageView. I need this image when I re-open the app to be kept in the ImageView.
I'm trying to do something like that with shared preferences. But I get the following log error:
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'android.content.SharedPreferences$Editor android.content.SharedPreferences$Editor.putString(java.lang.String, java.lang.String)' on a null object reference
private static final int PICK_IMAGE = 100;
static SharedPreferences sharedPref;
static SharedPreferences.Editor editor;
private static final String PREFS_NAME = "preferenceName";
Uri imageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
PROFILE_IMG = (ImageView)findViewById(R.id.profile_image);
PHOTObutton = (Button)findViewById(R.id.photo_btn);
// Get from the SharedPreferences
sharedPref = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
String imageUriString = sharedPref.getString("imageURI", null);
Uri imageUri = Uri.parse(imageUriString);
PROFILE_IMG.setImageURI(imageUri);
//open gallery-- select profile photo
PHOTObutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openGallery();
}
});
}
private void openGallery() {
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE){
imageUri = data.getData();
sharedPref = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
editor.putString("imageURI", imageUri.toString());
editor.commit();
PROFILE_IMG.setImageURI(imageUri);
}
}
What am I doing wrong?
This error is because your editor is null. Try this
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE){
imageUri = data.getData();
SharedPreferences.Editor editor = getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("imageURI", imageUri.toString());
editor.commit();
PROFILE_IMG.setImageURI(imageUri);
}
}
you forgot to inizile the editor add this into your onactivity result
editor=sharedPref.edit()
editor.putString("imageURI", imageUri.toString());
editor.commit();

My sharedprefrences not sharing correctly

I have an app where you upload images to my company server
So The user enters their login details, Email, Password and clientID(4 digit code)(in LoginActivity.java) and then this information must be passed to all the other activities, this passed information is then used to build a URL. Now the issue I am having is the Sharedprefrences doesn't share correctly...they either come up as NULL on the url or as just "email" or "password"
The Information is saved correctly in login activity but when i try to pass it to other activities it fails
Login activity here I save the prefrences
public class LoginActivity extends AppCompatActivity implements TextWatcher {
SharedPreferences MyPrefs;
Intent intent;
SharedPreferences.Editor editor;
public static final String PREF_NAME= "MYPREFS";
public static final String ID = "ClientID" ;
public static final String EMAIL = "username" ;
public static final String PASS = "password";
EditText email, password, id;
#SuppressLint("CommitPrefEdits")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button buttonOne=findViewById(R.id.button);
buttonOne.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent activity2Intent=new Intent(getApplicationContext(), MainActivity.class);
startActivity(activity2Intent);
}
});
MyPrefs= getSharedPreferences(PREF_NAME, 0);
editor = MyPrefs.edit();
email=findViewById(R.id.emailtext);
password=findViewById(R.id.pwdtext);
id=findViewById(R.id.clientid);
email.setText(MyPrefs.getString(EMAIL,"username"));
password.setText(MyPrefs.getString(PASS,"password"));
id.setText(MyPrefs.getString(ID, "id"));
email.addTextChangedListener(this);
password.addTextChangedListener(this);
id.addTextChangedListener(this);
MyPrefs =getSharedPreferences(EMAIL,0);
MyPrefs =getSharedPreferences(ID,0);
MyPrefs =getSharedPreferences(PASS,0);
intent = new Intent(LoginActivity.this,CameraActivity.class);
}
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
managePrefs();
}
#Override
public void afterTextChanged(Editable editable) {
managePrefs();
}
private void managePrefs(){
SharedPreferences.Editor editor =MyPrefs.edit();
editor.putString(EMAIL, email.getText().toString().trim());
editor.putString(PASS, password.getText().toString().trim());
editor.putString(ID, id.getText().toString().trim());
editor.apply();
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
}
Camera Activity this is where the shared prefrences must be passed to
public class CameraActivity extends AppCompatActivity implements View.OnClickListener {
private final int PICK_IMAGE=12345;
private final int REQUEST_CAMERA=6352;
private static final int REQUEST_CAMERA_ACCESS_PERMISSION=5674;
private Bitmap bitmap;
String myURL;
String email;
String clientId;
String pwd;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
My code for calling sharedprefrences
SharedPreferences sharedPreferences = getSharedPreferences(LoginActivity.PREF_NAME, 0);
email = sharedPreferences.getString(LoginActivity.EMAIL, "username");
clientId = sharedPreferences.getString(LoginActivity.ID, "id");
pwd = sharedPreferences.getString(LoginActivity.PASS, "password");
imageView=findViewById(R.id.imageView);
Button fromCamera=findViewById(R.id.fromCamera);
Button fromGallery=findViewById(R.id.fromGallery);
Button upload=findViewById(R.id.upload);
upload.setOnClickListener(this);
fromCamera.setOnClickListener(this);
fromGallery.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.fromCamera:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA_ACCESS_PERMISSION);
} else {
getImageFromCamera();
}
break;
case R.id.fromGallery:
getImageFromGallery();
break;
case R.id.upload:
if (bitmap != null)
uploadImageToServer();
break;
}
}
private void uploadImageToServer() {
#SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HH_mm_ss");
String currentTimeStamp = dateFormat.format(new Date());
final ProgressDialog pd=new ProgressDialog(CameraActivity.this);
pd.setMessage("Uploading, Please Wait....");
pd.show();
Intent intent = getIntent();
String Item= intent.getStringExtra("Spinner");
String Item2= intent.getStringExtra("Spinner2");
Uri.Builder builder=new Uri.Builder();
builder.scheme("https")
.authority("www.smartpractice.co.za")
.appendPath("files-upload-ruben.asp")
.appendQueryParameter("MyForm", "Yes")
.appendQueryParameter("ClientID",clientId)
.appendQueryParameter("Username", email)
.appendQueryParameter("Pwd", pwd)
.appendQueryParameter("category",Item )
.appendQueryParameter("client",Item2 );
myURL=builder.build().toString();
Toast toast = Toast.makeText(CameraActivity.this, myURL , Toast.LENGTH_LONG);
toast.show();
File imageFile=persistImage(bitmap,currentTimeStamp);
Ion.with(this)
.load(myURL)
.uploadProgressDialog(pd)
.setMultipartFile("SP-LOG", "image/jpeg", imageFile)
.asString()
.setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
pd.cancel();
Toast.makeText(getApplicationContext(),"Uploaded",Toast.LENGTH_SHORT).show();
}
});
}
private File persistImage(Bitmap bitmap, String name) {
File filesDir=getApplicationContext().getFilesDir();
File imageFile=new File(filesDir, name + ".jpg");
OutputStream os;
try {
os=new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
os.flush();
os.close();
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
}
return imageFile;
}
private void getImageFromCamera() {
Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
private void getImageFromGallery() {
Intent intent=new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE) {
if (resultCode == Activity.RESULT_OK) {
try {
InputStream inputStream=getContentResolver().openInputStream(data.getData());
bitmap=BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
} else if (requestCode == REQUEST_CAMERA) {
if (resultCode == Activity.RESULT_OK) {
Bundle extras=data.getExtras();
bitmap=(Bitmap) extras.get("data");
imageView.setImageBitmap(bitmap);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == REQUEST_CAMERA_ACCESS_PERMISSION) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getImageFromCamera();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
To store data in shared preference do something like this:
private SharedPreferences.Editor editor = getSharedPreferences(PREF_NAME, MODE_PRIVATE).edit();
editor.putString("email", email);
editor.putString("ID", id);
editor.putString("Pass", password);
editor.apply();
so I'll give you bit of explanation, when you write editor.putString("email", email); it tells editor to put your email against key "email".
Now, if you want to read these values back do it like this:
String email = getSharedPreferences(PREF_NAME, MODE_PRIVATE).getString("email", "");
String ID= getSharedPreferences(PREF_NAME, MODE_PRIVATE).getString("ID", "");
String password= getSharedPreferences(PREF_NAME, MODE_PRIVATE).getString("Pass", "");
Leme know if you don't understand anything.
getSharedPrerencences(String name, int mode) returns a reference to a shared preferences file name. That is, after the lines
MyPrefs =getSharedPreferences(EMAIL,0);
MyPrefs =getSharedPreferences(ID,0);
MyPrefs =getSharedPreferences(PASS,0);
your variable MyPrefs points to shared preferences file named password, which is probably not what you intended, since later you read from a file named MYPREFS.
Also, you don't need to call editor = MyPrefs.edit(); if you are just reading from the preferences, like you are doing in onCreate. That is why you get the warning that you have suppressed using #SuppressLint("CommitPrefEdits")

Having Trouble Checking If User Already Logged In With Their Facebook Account

I have been able to successfully implement the Facebook login button. My only problem now is I'm having trouble checking if the user already logged in.
This is code for when the user clicks the login button:
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
getFacebookData(object);
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "name, email, picture");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
getFacebookData has this code:
private void getFacebookData(JSONObject object) {
try {
Intent intent = new Intent(MainActivity.this, Profile.class);
String fb_name = object.getString("name");
String fb_email = object.getString("email");
URL profile_picture = new URL("http://graph.facebook.com/" + object.getString("id") + "/picture?type=large");
intent.putExtra("name", fb_name);
intent.putExtra("email", fb_email);
intent.putExtra("profile_picture", profile_picture.toString());
intent.putExtra("userOption", 2);
startActivityForResult(intent, 1);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
Basically, when the user logs in successfully, it sends the user's name, email, and profile picture data to the Profile activity.
Now, what I have in my onCreate method inside my MainActivity class is:
AccessToken accessToken = AccessToken.getCurrentAccessToken();
boolean isLoggedIn = accessToken != null && !accessToken.isExpired();
if (isLoggedIn) {
}
This above code checks to see if the user has already logged in with their Facebook account. What I want to put inside the if statement is getFacebookData() because this will send data to the Profile activity and start the Profile activity immediately instead of going to the MainActivity. My problem is, I have to pass in a JSONObject.
What should I do to fix this as I don't know what JSONObject to pass into the getFacebookData() function?
First, you can store the user name, email and id permanently in you application (e.g. shared preferences).
To insert:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("fbId", fbId);
editor.putString("fbEmail", fbEmail);
editor.putString("fbName", fbName);
editor.commit();
To retrieve:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
String fbId= sharedPref.getString("fbId");
String fbEmail = sharedPref.getString("fbEmail");
String fbName= sharedPref.getString("fbName");
If you really want to request those again, you can use following method:
AccessToken accessToken = AccessToken.getCurrentAccessToken();
boolean isLoggedIn = accessToken != null && !accessToken.isExpired();
if (isLoggedIn) {
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
getFacebookData(object);
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "name, email, picture");
request.setParameters(parameters);
request.executeAsync();
}

How to get the result from onActivityResult method for sharedpreferences

In qr scanner reader, after clicking a button it will open the camera and it will scan result. Then it will display result using onactivityresult method.
How to get that result from onActivityResult method, and use it in sharedpreferences? Below is my code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
String scanContent = result.getContents();
customerSno.setText(" " + scanContent);
} else {
Toast.makeText(getApplicationContext(),"Cancelled", Toast.LENGTH_LONG).show();
To save the result in SharedPreference
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("result", scanContent);
editor.commit();
To retrieve from SharedPreference
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String result = prefs.getString("result", "No saved result");
context is your activity context. If this code is in any activity just use this
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==IntentIntegrator.REQUEST_CODE){
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
String scanContent = result.getContents();
customerSno.setText(" " + scanContent);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("result", scanContent);
editor.commit();
} else {
Toast.makeText(getApplicationContext(),"Cancelled", Toast.LENGTH_LONG).show();
}
}
}

Android Facebook Dialog

I have integrated Facebook into my app. However, instead of bringing it up in a dialog, it opens full screen. I was wondering if anyone would know of a way to change this to dialog.
FaceBook Handler Class:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/*
* Get existing access_token if any
*/
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if(access_token != null)
facebook.setAccessToken(access_token);
if(expires != 0)
facebook.setAccessExpires(expires);
if (facebook.isSessionValid())
postFacebookMessage();
else {
facebook.authorize(this, new String[] {"publish_stream"}, new Facebook.DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
Toast.makeText(FacebookConnector.this, "Facebook error: " + e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
#Override
public void onError(DialogError e) {
Toast.makeText(FacebookConnector.this, "Facebook dialog error: " + e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
#Override
public void onComplete(Bundle values) {
postFacebookMessage();
Toast.makeText(FacebookConnector.this, "Thank You For Sharing!", Toast.LENGTH_SHORT).show(); }
#Override
public void onCancel() {Toast.makeText(FacebookConnector.this, "Facebook authorization cancelled.", Toast.LENGTH_LONG).show();
}
});
}
}
private void postFacebookMessage() {
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
Bundle params = new Bundle();
params.putString("message", MSG);
params.putString("picture", "http://meanwhileinwv.com/meanwhile.png");
mAsyncRunner.request("me/feed", params, "POST", new FacebookPostListener(), null); }
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
}
The code above produces the following result:
I would like it to be a dialog that the facebook window opens into. I have achieved this with my Twitter code:
Call authorization with additional parameter Facebook.FORCE_DIALOG_AUTH, like this:
facebook.authorize(this, new String[] {"publish_stream"}, Facebook.FORCE_DIALOG_AUTH, new Facebook.DialogListener() { ... });

Categories

Resources