I want to store the facebook profile picture into the parse user table.
Currently i'm trying this:
URL img_value = null;
try {
img_value = new URL("http://graph.facebook.com/"+user.getId()+"/picture?type=small");
} catch (MalformedURLException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Bitmap dp = BitmapFactory.decodeStream(img_value.openConnection().getInputStream());
Log.i(IntegratingFacebook.TAG, "image retrieved from facebook");
// Save the user profile info in a user property
ParseUser currentUser = ParseUser.getCurrentUser();
if(dp!=null){
ParseFile saveImageFile= new ParseFile("profilePicture.jpg",compressAndConvertImageToByteFrom(dp));
currentUser.put("profilePicture",saveImageFile);
}
currentUser.saveInBackground();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The URL is right. However dp is always null.
Therefore the image is never stored in the parse user table.
Any help is appreciated.
Your code looks correct EXCEPT for the fact that all calls to graph.facebook.com should be over SSL. switch your http to https and you should be good to go.
This is assuming that you are in a facebook callback were the user object is not a ParseUser object because FacebookUserObject.getId() and ParseUserObject.getId() will obviously return different results. If you are in a Facebook callback from a request like Request.newMeRequest() then your code will work by simply changing the protocol to https. If you are not in a facebook callback and the user object is a ParseUser object then you will want to use something like user.getString("facebookId") where facebookId is a value you've saved in a previous step (perhaps during initial registration).
The way you are going about doing it is very messy and might break sometime in the future... BUT have you ever heard of Picasso.
Make sure your URL is good (logcat), grab the picasso library for Android and change this:
Bitmap dp = BitmapFactory.decodeStream(img_value.openConnection().getInputStream());
into this ( try/catch needed )
Bitmap dp = Picasso.with(getActivity()).load(URL).get();
and you should be good to go!
Related
I'm building hybrid applications that rely on 2-way communication between javascript in a webview and the hosting application.
Attitudes differ somewhat as in IOS the JS can send a message to swift (using WKWebView), that listens through
userContentController(userContentController: WKUserContentController,
didReceiveScriptMessage message: WKScriptMessage)
when implementing the WKScriptMessageHandler protocol,
whereas in Android the JS can actually call an Android method that has #JavascriptInterface annotation, after calling addJavascriptInterface().
Both approaches are OK for me, as I'm passing around data using JSON strings. Question is, what if I need to pass a media file, say an image or video, from the web page to the application? should I just pass a bitmap inside the json? Seems a little naive... recommendations?
edit: when passing an image from the application to the webpage I save the file to the file system and send the filename to the webview. Can it be done the other way around? Can javascript save to the hosting mobile device file system?
You have to host(in case of webapp) or store(in case of mobile app) the image and pass the image url, not exactly the image.
Almost all api that uses images bitmap also takes image url.
regards
Ashish
To answer your second question which is there are comments, use the following code.
Here the html content is your binary content:
FileWriter imageFileWriter = null;
BufferedWriter imageBufferedWriter = null;
ABOUtil.createDir(InMemoryDataStructure.FILE_PATH.getFileDirForimage());
File imageFileDir = new File(InMemoryDataStructure.FILE_PATH.getFileDirForimage());
String imageName = "/finalimage"+ filename + jpg
File mimageFile = new File(imageFileDir, imageName);
try {
imageFileWriter = new FileWriter(mimageFile, false);
imageBufferedWriter = new BufferedWriter(imageFileWriter);
StringBuilder sb = new StringBuilder();
sb.append(htmlContent);
sb.append(scriptInjectJavascript(lstimageNameValue));
imageBufferedWriter.write(sb.toString());
imageBufferedWriter.close();
return mimageFile;
}
catch (IOException e) {
MAFLogger.e("", "", e);
}
finally{
if(imageFileWriter!=null)
try {
imageFileWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
MAFLogger.e("","",e);
}
if(imageBufferedWriter!=null)
try {
imageBufferedWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
MAFLogger.e("","",e);
}
}
I know that there is library available for uploading the file using Azure Storage. I have refer this for same.
But, they have not give information for how to use SAS with that. I have account name, and sas url for access and upload file there. But I don't know how to use that for uploading file.
If I use above mention library it shows me invalid storage connection string because I am not passing the key in it (Which is not required with sas). So I am confused how I can upload file.
I have refer this documentation also for uploading file using sas. but not getting proper steps to do this. They have made demo for their windows app. I want to have that in android with use of sas.
Update
I have try with below code with reference to the console app made by Azure to check and access SAS.
try {
//Try performing container operations with the SAS provided.
//Return a reference to the container using the SAS URI.
//CloudBlockBlob blob = new CloudBlockBlob(new StorageUri(new URI(sas)));
String[] str = userId.split(":");
String blobUri = "https://myStorageAccountName.blob.core.windows.net/image/" + str[1] + "/story/" + storyId + "/image1.jpg" + sas.toString().replaceAll("\"","");
Log.d(TAG,"Result:: blobUrl 1 : "+blobUri);
CloudBlobContainer container = new CloudBlobContainer(new URI(blobUri));
Log.d(TAG,"Result:: blobUrl 2 : "+blobUri);
CloudBlockBlob blob = container.getBlockBlobReference("image1.jpg");
String filePath = postData.get(0).getUrl().toString();
/*File source = new File(getRealPathFromURI(getApplicationContext(),Uri.parse(filePath))); // File path
blob.upload(new FileInputStream(source), source.length());*/
Log.d(TAG,"Result:: blobUrl 3 : "+blobUri);
//blob.upload(new FileInputStream(source), source.length());
//blob.uploadText("Hello this is testing..."); // Upload text file
Log.d(TAG, "Result:: blobUrl 4 : " + blobUri);
Log.d(TAG, "Write operation succeeded for SAS " + sas);
response = "success";
//Console.WriteLine();
} catch (StorageException e) {
Log.d(TAG, "Write operation failed for SAS " + sas);
Log.d(TAG, "Additional error information: " + e.getMessage());
response = e.getMessage();
} catch (FileNotFoundException e) {
e.printStackTrace();
response = e.getMessage();
} catch (IOException e) {
e.printStackTrace();
response = e.getMessage();
} catch (URISyntaxException e) {
e.printStackTrace();
response = e.getMessage();
} catch (Exception e){
e.printStackTrace();
response = e.getMessage();
}
Now, when I upload text only it says me below error
Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
Now, my requirement is to upload Image file. So when I uncomment code for uploading image file it is not giving me any error but even not uploading image file.
#kumar kundal
The mechanism that you have explained is completely right.
Below is the more detailed answer about uploading profile image to the Azure Server.
First create SAS url to upload Image(or any file) to blob storage:
String sasUrl = "";
// mClient is the MobileServiceClient
ListenableFuture<JsonElement> result = mClient.invokeApi(SOME_URL_CREATED_TO_MAKE_SAS, null, "GET", null);
Futures.addCallback(result, new FutureCallback<JsonElement>() {
#Override
public void onSuccess(JsonElement result) {
// here you will get SAS url from server
sasUrl = result; // You need to parse it as per your response
}
#Override
public void onFailure(Throwable t) {
}
});
Now, you have sasURL with you. That will be something like the below string:
sv=2015-04-05&ss=bf&srt=s&st=2015-04-29T22%3A18%3A26Z&se=2015-04-30T02%3A23%3A26Z&sr=b&sp=rw&sip=168.1.5.60-168.1.5.70&spr=https&sig=F%6GRVAZ5Cdj2Pw4tgU7IlSTkWgn7bUkkAg8P6HESXwmf%4B
Now, you need to append the sas url with your uploading url. See below code in which I have appended the SAS url with my uploading request.
try {
File source = new File(filePath); // File path
String extantion = source.getAbsolutePath().substring(source.getAbsolutePath().lastIndexOf("."));
// create unique number to identify the image/file.
// you can also specify some name to image/file
String uniqueID = "image_"+ UUID.randomUUID().toString().replace("-", "")+extantion;
String blobUri = MY_URL_TO_UPLOAD_PROFILE_IMAGE + sas.replaceAll("\"","");
StorageUri storage = new StorageUri(URI.create(blobUri));
CloudBlobClient blobCLient = new CloudBlobClient(storage);
CloudBlobContainer container = blobCLient.getContainerReference("");
CloudBlockBlob blob = container.getBlockBlobReference(uniqueID);
BlobOutputStream blobOutputStream = blob.openOutputStream();
byte[] buffer = fileToByteConverter(source);
ByteArrayInputStream inputStream = new ByteArrayInputStream(buffer);
int next = inputStream.read();
while (next != -1) {
blobOutputStream.write(next);
next = inputStream.read();
}
blobOutputStream.close();
// YOUR IMAGE/FILE GET UPLOADED HERE
// IF YOU HAVE FOLLOW DOCUMENT, YOU WILL RECEIVE IMAGE/FILE URL HERE
} catch (StorageException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
I hope this information help you lot for uploading the file using blob storage.
Please let me know if you have any doubt apart from this. I can help in that.
Uploading a pic to BLOB storage . I got it after searching for hours .Take a look :-
Uploading the photo image is a multistep process:
First you take a photo, and insert a TodoItem row into the SQL database that contains new meta-data fields used by Azure Storage.
A new mobile service SQL insert script asks Azure Storage for a Shared Access Signature (SAS).
That script returns the SAS and a URI for the blob to the client.
The client uploads the photo, using the SAS and blob URI.
So what is a SAS?
It's not safe to store the credentials needed to upload data to the Azure Storage service inside your client app. Instead, you store these credentials in your mobile service and use them to generate a Shared Access Signature (SAS) that grants permission to upload a new image. The SAS, a credential with a 5 minute expiration, is returned securely by Mobile Services to the client app. The app then uses this temporary credential to upload the image.
for further queries and detail analysis. Visit this official documentation https://azure.microsoft.com/en-us/documentation/articles/mobile-services-android-upload-data-blob-storage/
It is possible to post to a Facebook wall a message with image (not an image link, but image data)?
I did not find this possibility either in http://developers.facebook.com/docs/reference/api/post/ or in https://developers.facebook.com/docs/guides/attachments/.
And I was ready to put up with impossibility of doing it, but I came across documentation for SLComposeViewController class introduced in iOS 6.0 (http://developer.apple.com/library/ios/#documentation/NetworkingInternet/Reference/SLComposeViewController_Class/Reference/Reference.html).
This class has a method - (BOOL)addImage:(UIImage *)image that does exactly what I need.
I program for Android and hence I cannot use it. But obviously this method must use facebook API. But I cannot find it: everything related to image posting requires url, not data.
So, is is possible in Android to post to a Facebook wall a message with image data?
EDIT: I posted the answer almost with your comment. You can use something like this to cast you Image from assets into a Bitmap.
InputStream bitmap = null;
try {
bitmap = getAssets().open("icon.png");
bmpImageGallery = BitmapFactory.decodeStream(bitmap);
} catch (IOException e) {
e.printStackTrace();
} finally {
bitmap.close();
}
This is how I display an Image from the Gallery via an Intent in the onActivityResult method:
targetURI = data.getData();
try {
bmpImageGallery = MediaStore.Images.Media.getBitmap(this.getContentResolver(), targetURI);
// SET THE IMAGE FROM THE GALLERY TO THE IMAGEVIEW
imgvwSelectedImage.setImageBitmap(bmpImageGallery);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
This is the code to upload the image:
byte[] data = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmpImageGallery.compress(CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
Bundle postImgGallery = new Bundle();
// ADD THE PHOTO DATA TO THE BUNDLE
postImgGallery.putByteArray("photo", data);
// ADD THE CAPTION FROM THE STRING finalStatusMessage TO THE BUNDLE
if (finalStatusMessage.equals("")) {
/***** DO NOTHING HERE *****/
} else {
postImgGallery.putString("caption", finalStatusMessage);
}
Utility.mAsyncRunner.request(userID + "/photos", postImgGallery, "POST", new PhotoUploadListener(), null);
NOTE: In this bit here "caption", finalStatusMessage, the caption can also be substituted with message. I have never seen any difference in the posts using either of these. But do check before using either, just to be safe. ;-)
This class is used to check the status of the upload:
private class PhotoUploadListener extends BaseRequestListener {
#Override
public void onComplete(String response, Object state) {
// DISPLAY A CONFIRMATION TOAST
}
}
In my application i am using tweetPic to uploaded image but with the image is only able to see on the tweetPic.
Instead of that i want to upload the picture on the twitter and also with the custom message. So how it is possible?
Twitter OAuth is also required for that.
I want any demo or sample example app that done like that.
Thanks.
Well i have search many but still not get the answer as i want.
Finally i use this to upload the photo on Twitter with the Custom Message:
File picture = new File(APP_FILE_PATH + "/"+filename+".jpg");
// Create TwitPic object and allocate TwitPicResponse object
TwitPic tpRequest = new TwitPic(TWITTER_NAME, TWITTER_PASSWORD);
TwitPicResponse tpResponse = null;
// Make request and handle exceptions
try {
tpResponse = tpRequest.uploadAndPost(picture, customMessageEditText.getText()+" http://www.MySite.com/");
}
catch (IOException e) {
e.printStackTrace();
}
catch (TwitPicException e) {
e.printStackTrace();
}
// If we got a response back, print out response variables
if(tpResponse != null) {
tpResponse.dumpVars();
System.out.println(tpResponse.getStatus());
if(tpResponse.getStatus().equals("ok")){
Toast.makeText(getApplicationContext(), "Photo posted on Twitter.",Toast.LENGTH_SHORT).show();
}
}
Still in search of the Twitter Demo to tweet pics on the Twitter with custom message with twitter OAuth and Without using twitPic.
Enjoy. :)
Thanks.
I'm setting up OAuth for my Android app. To test it I did the following:
Added signpost-core-1.2.1.1.jar and signpost-commonshttp4-1.2.1.1.jar to my project, added the variables "CommonsHttpOAuthConsumer consumer" and "CommonsHttpOAuthProvider provider" and did the following when the button is clicked:
consumer = new CommonsHttpOAuthConsumer("xxx", "yyy");
provider = new CommonsHttpOAuthProvider("https://api.twitter.com/oauth/request_token",
"https://api.twitter.com/oauth/access_token",
"https://api.twitter.com/oauth/authorize");
oauthUrl = provider.retrieveRequestToken(consumer, "myapp://twitterOauth");
persistOAuthData();
this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(oauthUrl)));
persistOAuthData() does the following:
protected void persistOAuthData()
{
try
{
FileOutputStream providerFOS = this.openFileOutput("provider.dat", MODE_PRIVATE);
ObjectOutputStream providerOOS = new ObjectOutputStream(providerFOS);
providerOOS.writeObject(this.provider);
providerOOS.close();
FileOutputStream consumerFOS = this.openFileOutput("consumer.dat", MODE_PRIVATE);
ObjectOutputStream consumerOOS = new ObjectOutputStream(consumerFOS);
consumerOOS.writeObject(this.consumer);
consumerOOS.close();
}
catch (Exception e) { }
}
So, the consumer and the provider are saved before opening the browser, like described here.
In the onResume() method I load the provider and consumer data and do the following:
Uri uri = this.getIntent().getData();
if (uri != null && uri.getScheme().equals("myapp") && uri.getHost().equals("twitterOauth"))
{
verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
if (!verifier.equals(""))
{
loadOauthData();
try
{
provider.retrieveAccessToken(consumer, verifier);
}
catch (OAuthMessageSignerException e) {
e.printStackTrace();
} catch (OAuthNotAuthorizedException e) {
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
e.printStackTrace();
} catch (OAuthCommunicationException e) {
e.printStackTrace();
}
}
}
So, what works:
1) I do get a requestToken and a requestSecret.
2) I do get the oauthUrl.
3) I am directed to the browser page to authorize my app
4) I am getting redirected to my app.
5) I do get the verifier.
But calling retrieveAccessToken(consumer, verifier) fails with an OAuthCommunicationException saying "Communication with the service provider failed: null".
Does anyone know what might be the reason? Some people seem to have problems getting the requestToken, but that just works fine. I wonder if it might be a problem that my app has also included the apache-mime4j-0.6.jar and httpmime-4.0.1.jar which I need for multipart upload.
Okay, I figured it out. Maybe this is helpful to others:
First of all, you do not need to save the whole consumer and provider object. All you need to do is store the requestToken and the requestSecret. Luckily, those are Strings, so you don't need to write them to disk or anything. Just store them in the sharedPreferences or something like that.
Now, when you get redirected by the browser and your onResume() method is called, just do the following:
//The consumer object was lost because the browser got into foreground, need to instantiate it again with your apps token and secret.
consumer = new CommonsHttpOAuthConsumer("xxx", "yyy");
//Set the requestToken and the tokenSecret that you got earlier by calling retrieveRequestToken.
consumer.setTokenWithSecret(requestToken, tokenSecret);
//The provider object is lost, too, so instantiate it again.
provider = new CommonsHttpOAuthProvider("https://api.twitter.com/oauth/request_token",
"https://api.twitter.com/oauth/access_token",
"https://api.twitter.com/oauth/authorize");
//Now that's really important. Because you don't perform the retrieveRequestToken method at this moment, the OAuth method is not detected automatically (there is no communication with Twitter). So, the default is 1.0 which is wrong because the initial request was performed with 1.0a.
provider.setOAuth10a(true);
provider.retrieveAccessToken(consumer, verifier);
That's it, you can receive the token and the secret with getToken() and getTokenSecret(), now.
Hi Manuel i see you are avoidin the OAuthocalypse too!
heres is a good example to implement OAuth for Twitter using sharedPreferences to save requestToken and the requestSecret, like your solution.
http://github.com/brione/Brion-Learns-OAuth
by Brion Emde
heres the video
hope this helps other developers =)