Below is my code and I integrated the facebook in my app. I am trying to make the user to be able to post an image on his wall after logging in. But I have been failing to make it for three days. Have seen few posts like this but I don't get any data(just it results in empty data data[]). I am even facing trouble with maintaining sessions too. Can some one please post working code or at least some sources where I can post image on facebook wall? Hope my below code is clear and my explanation is clear on what I have tried with the code below.
Activity's onCreate():-
public class FacebookActivity extends BaseActivity {
private static String APP_ID = "1303786178";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fb_screen);
btnFbLogin = (Button) findViewById(R.id.fbloginbtn);
btnFbLogout = (Button) findViewById(R.id.fblogoutbtn);
btnPostToWall = (Button) findViewById(R.id.fbpostbtn);
msget = (EditText)findViewById(R.id.fbmsget);
mAsyncRunner = new AsyncFacebookRunner(facebook);
mHandler = new Handler();
String passedpath = getIntent().getStringExtra("imagepath").toString();
imageuri = Uri.parse(passedpath);
/**
* Login button Click event
* */
btnFbLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Image Button", "button Clicked");
loginToFacebook();
}
});
btnFbLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Image Button", "button Clicked");
logoutFromFacebook();
}
});
/**
* Posting to Facebook Wall
* */
btnPostToWall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//postToWall(imageuri);
getAlbumId();
}
});
}
Posting on Wall includes two functions in my code one is getAlbumId() and the other is posttowall() which will be called from getAlbumId():-
public void getAlbumId()
{
dialog = ProgressDialog.show(FacebookActivity.this, "","Please Wait...", true, true);
//String wallAlbumID = null;
mAsyncRunner.request("me/albums", new BaseRequestListener(){
#Override
public void onComplete(String response, Object state) {
// TODO Auto-generated method stub
try{
Log.d("response in album"," "+response);
JSONObject json = Util.parseJson(response);
JSONArray albums = json.getJSONArray("data");
for (int i =0; i < albums.length(); i++) {
JSONObject album = albums.getJSONObject(i);
if (album.getString("type").equalsIgnoreCase("wall")) {
final String wallAlbumID = album.getString("id");
globalalbid = wallAlbumID;
Log.d("JSON", wallAlbumID);
break;
}
}
dialog.dismiss();
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "id: " + globalalbid, Toast.LENGTH_LONG).show();
if(globalalbid != "")
postToWall(imageuri, globalalbid);
}
});
}catch (JSONException e) {
e.printStackTrace();
}
}
});
}
function to post on wall:
public void postToWall(Uri locuri, String wallid) {
if (facebook.isSessionValid()) {
Util.showAlert(this, "Warning", "You must first log in.");
} else {
dialog = ProgressDialog.show(FacebookActivity.this, "","Please Wait...", true, true);
// post on user's wall.
Uri photoUri = locuri;
if (photoUri != null) {
Bundle params = new Bundle();
try {
params.putByteArray("photo",
Utility.scaleImage(getApplicationContext(), photoUri));
} catch (IOException e) {
e.printStackTrace();
}
String imagecaption = msget.getText().toString();
if(imagecaption != "")
params.putString("caption", imagecaption);
mAsyncRunner.request(wallid+"/photos", params, "POST", new PhotoUploadListener(), null);
} else {
Toast.makeText(getApplicationContext(),
"Error from the pic", Toast.LENGTH_SHORT)
.show();
}
}
}
}
I always get album id empty. Is there anything wrong in the way that I try to get album id. Because I have seen on some posts those who try to access album id and then posting the image on album. They seem to be keeping wall as common findout in the album name. If it is so, some new ones contain timeline photos name, then how can we findout the album id. Please suggest.
Note: I want the image to be visible on to the wall not to only album.
Instead of uploading the photo to the user's album, post the image to /me/feed instead. Make sure you are asking the user for the publish_stream permission. This will upload the photo straight to the user's wall instead of going to an album.
Related
Login using JSON with shared Preferences When user Enter their Phone Number then user got success from API and go to new activity and after resume app, users state will log in
When user Enter their Phone Number then user got success from API and go to new activity and after resume app, users state will log in
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView3);
usr_number = findViewById(R.id.usr_pass);
go = findViewById(R.id.button);
signup = findViewById(R.id.signup_signup);
go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getjsondata();
String hhh = usr_number.getText().toString();
url = "http://readnow.flatdeal4u.com/Api/Register.aspx?mobile=" + hhh + "&choice=2";
//Toast.makeText(MainActivity.this, ""+hhh, Toast.LENGTH_SHORT).show();
if (usr_number.getText().toString().isEmpty()) {
usr_number.setError("Enter Phone Number");
Toast.makeText(MainActivity.this, "Enter Details", Toast.LENGTH_SHORT).show();
} else {
if (usr_number.getText().toString().equals("" + hhh)) {
Intent intent = new Intent(MainActivity.this, select_your_exams.class);
startActivity(intent);
pref = PreferenceManager
.getDefaultSharedPreferences(MainActivity.this);
pref.getString("mobilenumber", hhh);
pref.getString("nameofuser", "");
}
}
}
});
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Signup.class);
startActivity(intent);
}
});
}
Here are my JSON method codes:
public void get JSON data) {
final StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener < String > () {
#Override
public void onResponse(String response) {
try {
JSONObject jobj = new JSONObject(response);
JSONArray array = jobj.getJSONArray("userInfos");
//Toast.makeText(MainActivity.this, "data found"+array, Toast.LENGTH_LONG).show();
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
final Phn_modal mo = new Phn_modal();
final String mobile = obj.getString("mobileNumber");
final String name = obj.getString("fullName");
final String email = obj.getString("emailId");
Toast.makeText(MainActivity.this, "Welcome You-" + name, Toast.LENGTH_LONG).show();
mo.setMobile(mobile);
mo.setName(name);
mo.setEmailId(email);
mo.getMobile(mobile);
mo.getMobile(name);
editor.putString("mobilenumber", mobile);
editor.putString("nameofuser", name);
editor.apply();
editor.commit();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "" + error.toString(), Toast.LENGTH_SHORT).show();
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request);
}
i think your question is , you login first time, and next time you again visit application that time directly go to the activity withouth asking login,
then you can try this.
public void storeString(SharedPreferences sharedPreferences, String key, String value) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
above function is used to store the specific value in our shared prefrence, with given key.
Now when we hint the login button that time if login is success then store the login success value in our prefrence.
this one is usefull for again visit in your application
storeString(mPreferences, "Login_flag", "true");
-> Now, when we again visit application check the our prefrence is true or false.
if our prefrence is true then user already login, not required to login again
Check like this,
if(mPreferences.getString(PreferenceList.LOGIN_FLAG, "false").equals("true")){
//if alredy login then access this
}else{
//if not login then access this
}
if you want to create a login session in your app then you should create an preference class in your project and save data in that class and match the data where you want to use follow this answer to maintain the login session in your app:- Preventing users to login again after closing the app
I'm trying to make a signUp activity with a profile picture, but i get an error stating: Unable to encode an unsaved parse file. I have the same code in another Class and it doesn't have any problems.
I think that the problem could be using ParseUser instead of ParseObject. Please help me, here's my code.
public class SignUpActivityStep3 extends ActionBarActivity {
public static final String YOUR_APPLICATION_ID = "kuN8ihs88AYhRR1jIWT9psCGUXxSOveJPqVVsBnq";
public static final String YOUR_CLIENT_KEY = "vC4eA9CqulpgkxJ7sTPtoPSANkMxFeiFlYXwODYK";
byte[] Image;
ParseFile photo = null;
String User, Pass, Email, Description;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signupstep3);
Parse.initialize(this, YOUR_APPLICATION_ID, YOUR_CLIENT_KEY);
EditText Desc = (EditText) findViewById(R.id.txtDesc);
Button Finish = (Button) findViewById(R.id.btnFinish);
Intent intent = getIntent();
User = intent.getStringExtra("User");
Pass = intent.getStringExtra("Pass");
Email = intent.getStringExtra("Email");
Image = intent.getByteArrayExtra("Image");
photo = new ParseFile("userpicture.png", Image);
photo.saveInBackground();
savetoParse();
}
private void savetoParse() {
ParseUser user = new ParseUser();
user.setUsername(User.toString());
user.setPassword(Pass.toString());
user.put("Profile", photo);
user.setEmail(Email.toString());
user.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if (e != null) {
Toast.makeText(getApplicationContext(),
"Saving user failed." + e.getMessage(), Toast.LENGTH_SHORT).show();
if (e.getCode() == 202) {
Toast.makeText(
getApplicationContext(),
"Username already taken. \n Please choose another username.",
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext(), "User Saved",
Toast.LENGTH_SHORT).show();
/*Do some things here if you want to.*/
}
}
});
}
}
You need to wait for the Parse file to finish saving before attempting to sign up the user. You need to do something like this:
photo = new ParseFile("userpicture.png", Image);
file.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
// If successful add file to user and signUpInBackground
if(null == e)
savetoParse();
}
});
I was having this same issue but then I figured that for the image to be saved we need to login first, so either login with a user and password using ParseUser.LogInBackGround method or use Parse.enableLocalDatastore(this); to enable automatic user creation and logging in.
I have a file that is supposed to pull a list of products from my MySQL database, encode them into a JSON array then I need to make the Android application display those.
Ideally I want it to display icons but that's something I can tinker with later for now I just want to get it to work
Using the current code below when I click the button it doesn't do anything. My LogCat shows my JSON perfectly fine but the app doesn't display anything, or crash.
public class GetProducts extends Activity {
//Delcare Variables
// JSON Response node names
private static String KEY_SUCCESS = "success";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.view_products);
Functions userFunctions = new Functions();
if(!userFunctions.isConnected(getApplicationContext()))
{
displayDialogue("Connection Error","Your network settings are invalid - please turn on network settings ", "Open Network Settings");
}
if(!userFunctions.isUserLoggedIn(getApplicationContext())){
Intent i = new Intent(GetProducts.this, FirstScreen.class);
startActivity(i);
}
Button btnLogin;
btnLogin = (Button)findViewById(R.id.btnGetProducts);
//When our login button is pressed
btnLogin.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new LoginTask().execute();
}
});
//Assign the variables our layout buttons
}
//We are using an AsyncTask so that this function runs on a seperate thread of the processor
//Since 4.2 + Android requires any web or HTTP activity to be ran seperate thread to the GUI
class LoginTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
//Run the login function
Login();
return null;
}
}
public void displayDialogue(String title, String Message, String Button){
final AlertDialog.Builder myDialogue = new AlertDialog.Builder(this);
myDialogue.setTitle(title);
myDialogue.setMessage(Message);
TextView messageView = new TextView(this);
messageView.setGravity(Gravity.CENTER);
myDialogue.setView(messageView);
myDialogue.setCancelable(false);
myDialogue.setPositiveButton(Button, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = myDialogue.create();
dialog.show();
}
public void Login(){
try{
Functions userFunctions = new Functions();
final JSONObject json = userFunctions.getProducts();
JSONObject json_user = json.getJSONObject("products");
JSONArray jArray;
jArray = json.getJSONArray("products");
if (json.getString("success") != null) {
String res = json.getString("success");
if(Integer.parseInt(res) == 1){
try{
// user successfully logged in
// Store user details in SQLite Database
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
displayDialogue("Error",json.getString("name"), "Try Again");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
// Clear all previous data in database
// Close Login Screen
finish();
}
catch(final Exception e){
runOnUiThread(new Runnable() {
#Override
public void run() {
displayDialogue("Error",e.toString(), "Try Again");
}
});
}
}
else{
runOnUiThread(new Runnable() {
#Override
public void run() {
displayDialogue("Error", "Error. \nWrong username / password combination please re-enter the details", "Try Again");
}
});
}
}else{
runOnUiThread(new Runnable() {
#Override
public void run() {
displayDialogue("Error", "Error. \nGeneric Error", "Try Again");
}
});
}
}
catch(JSONException e){
e.printStackTrace();
}
}
}
JSON result:- (Printed to Logcat)
12-27 16:53:45.011: E/JSON(23028): {"tag":"getProducts","success":1,"error":0,"products":{"name":"Coffee1","price":"4.00","image":"http:\/\/test.com"}}{"tag":"getProducts","success":1,"error":0,"products":{"name":"Coffee2","price":"5.00","image":"http:\/\/test2.com"}}
Any help would be great, thanks!
I have a problem with accessing the graph API through my android application that retrieves a user's friends as JSONObject, extracts their names and displays them on the screen. It is supposed to be a simple and straightforward task but apparently it is not. When I run my application on Android Nexus I, I login to Facebook, then I am asked I click "Allow" button to grant permissions and I am redirected to a blank page. I am expect to see the name of my friends but it does not happen. Could some one assist me.
public class Login extends Activity
{
Facebook mFacebook = new Facebook("201509899926116");
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(mFacebook);
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
View linearLayout;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
linearLayout = findViewById(R.id.main_layout);
/* 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)
{
mFacebook.setAccessToken(access_token);
}
if(expires != 0)
{
mFacebook.setAccessExpires(expires);
}
/* Only call authorize if the access_token has expired. */
if(!mFacebook.isSessionValid())
{
mFacebook.authorize(this, new String[] {"user_birthday","email",
"user_relationships","user_religion_politics","user_hometown",
"user_location","user_relationship_details","user_education_history",
"user_likes","user_interests", "user_activities"},
new DialogListener()
{
#Override
public void onComplete(Bundle values)
{
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", mFacebook.getAccessToken());
editor.putLong("access_expires", mFacebook.getAccessExpires());
editor.commit();
/* access the graph API */
Log.d("Facebook-Example-Friends Request", "Started API request");
mAsyncRunner.request("me/friends", new FriendsRequestListener());
Log.d("Facebook-Example-Friends Request", "Finished API request");
}
#Override
public void onFacebookError(FacebookError error) {}
#Override
public void onError(DialogError e) {}
#Override
public void onCancel() {}
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
mFacebook.authorizeCallback(requestCode, resultCode, data);
}
public class FriendsRequestListener implements com.facebook.android.AsyncFacebookRunner.RequestListener
{
/**
* Called when the request to get friends has been completed.
* Retrieve and parse and display the JSON stream.
*/
public void onComplete(final String response)
{
try
{
// process the response here: executed in background thread
Log.d("Facebook-Example-Friends Request", "response.length(): " + response.length());
Log.d("Facebook-Example-Friends Request", "Response: " + response);
final JSONObject json = new JSONObject(response);
JSONArray d = json.getJSONArray("data");
int l = (d != null ? d.length() : 0);
Log.d("Facebook-Example-Friends Request", "d.length(): " + l);
for (int i=0; i<l; i++)
{
JSONObject o = d.getJSONObject(i);
String n = o.getString("name");
String id = o.getString("id");
TextView tv = new TextView(Login.this);
tv.setText(n);
((LinearLayout) linearLayout).addView(tv);
}
}
catch (JSONException e)
{
Log.w("Facebook-Example", "JSON Error in response");
}
}
}
}
I think i might've found the issue.. According to the documentation on onComplet;
/**
* Called when a request completes with the given response.
*
* Executed by a background thread: do not update the UI in this method.
*/
And you are trying to update your UI, so addViews don't actually get reflected on the UI thread.. You should create a method in your activity that you can call from onComplete with runOnUIThread.. Something like this;
runOnUiThread(new Runnable() {
public void run() {
inserFacebookNames(facebookContactNames);
}
});
Let me know if this actually fixes it.. I'm curious if that was the reason..
I'm trying to retrieve in my android app(in which I have facebook integrated ) the personal information for the logged in user.
For this I have 2 buttons:
Button tweet = (Button) findViewById(R.id.btn_post);
Button information = (Button) findViewById(R.id.btn_information);
The first button when pressed does a login like this:
tweet.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
postMessage();
}
});
where postMessage() looks like:
public void postMessage() {
if (facebookConnector.getFacebook().isSessionValid()) {
postMessageInThread();
} else {
SessionEvents.AuthListener listener = new SessionEvents.AuthListener() {
#Override
public void onAuthSucceed() {
postMessageInThread();
}
#Override
public void onAuthFail(String error) {
}
};
SessionEvents.addAuthListener(listener);
facebookConnector.login();
}
}
After logging I have the second button-information
information.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Bundle params = new Bundle();
String accessToken = mFacebook.getAccessToken();
try
{
params.putString("format", "json");
params.putString("access_token", accessToken);
String url = "https://graph.facebook.com/me";
String response = Util.openUrl(url, "GET", params);
try{
JSONObject json = Util.parseJson(response);
String name = json.getString("name");
String fname = json.getString("first_name");
}
catch(FacebookError e){
e.printStackTrace();
}
}
catch(Exception e)
{
}
}
});
When pressed the button information I wanna retrieve the personal user information like name and first_name.
I tried to retrieve the user's personal information by using this:
"https://graph.facebook.com/me".
But when I press the second button nothing happens.Can someone tell me where I'm going wrong?
Make sure you have downloaded the latest version. And when you have logged in and stored AuthenticationToken to your SharedPreferences.
Then make a call to the "me" using request() function of Facebook class something like this.
String resp = facebookConnector.getFacebook().request("me");
JSONObject me = Util.parseJson(resp);
String name = json.getString("name");
String fname = json.getString("first_name");
You have to just put "me" String to the request, The remaining URL will be automatically added by their Util class.