I am new to integrating Twitter. I have implemented Twitter in my application with this code:
// Create file
File picture = new File(APP_FILE_PATH + "/myAwesomeDrawing.png");
// Create TwitPic object and allocate TwitPicResponse object
TwitPic tpRequest = new TwitPic("username", "password");
TwitPicResponse tpResponse = null;
// Make request and handle exceptions
try {
tpResponse = tpRequest.uploadAndPost(picture, "Image Uploaded from My AndroidDrawing App...");
}
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();
All works fine here. But here I have to add the username and password programmatically. Is there any other way to use the Twitter integration as like Facebook OAuth to integration?
I need to know how Twitter OAuth is checked, and if the User is not login then it will ask for the username and password in its in built window.
If caguilar187's code link's are not enough, then here are few more links for code help:
http://blog.doityourselfandroid.com/2011/08/08/improved-twitter-oauth-android/
http://blog.doityourselfandroid.com/2011/02/13/guide-to-integrating-twitter-android-application/
http://marakana.com/forums/android/examples/312.html
Best suggested: http://android10.org/index.php/articleslibraries/291-twitter-integration-in-your-android-application
One more suggest: http://automateddeveloper.blogspot.com/2011/06/android-twitter-oauth-authentication.html
Post on Twitter: http://www.londatiga.net/it/how-to-post-twitter-status-from-android/
GitHub Link: https://github.com/brione/Brion-Learns-OAuth
Hope below link help you:-
Below link show you how to generate key with Twitter and other social media
http://code.google.com/p/socialauth-android/wiki/Twitter
Now below link is source code where u find out source code
http://code.google.com/p/socialauth-android/downloads/list
here are a few they all use signpost to do it.
Signpost:
http://code.google.com/p/oauth-signpost/
Blogs
http://dev.bostone.us/2009/07/16/android-oauth-twitter-updates/#awp::2009/07/16/android-oauth-twitter-updates/
http://blog.copyninja.info/2010/09/android-oauth-authentication-with.html
http://code.google.com/p/oauth-signpost/wiki/TwitterAndSignpost
Related
I'm trying to post my data through android app on my twitter account so how should i do it.
i have tried a way, below is the code, and in that it is showing the data on my account and i need to click on the tweet button to get it tweeted. So can i know how to post it directly without asking me to tweet. Like Four Square app
public void open(View view){
String text = "Share Your Experiance ....!!!";
String url = "twitter://post?message=";
try {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url + Uri.encode(text)));
startActivity(i);
} catch (android.content.ActivityNotFoundException e) {
Toast.makeText(this, "Can't send tweet! Please install twitter...", 2).show();
}
Thanks in Advance !!!
Firstly you have to check are you logged with twitter or not after as your condition you can apply this snippet code.
I think you follow the all basics for twitter integration in your code.
public void uploadPic(String message, String getImgUrl)
throws Exception {
try {
System.out.println(" ON UPLOAD PIC FUNCTION getImgUrl "+getImgUrl);
// URL url = new URL("http://faveplatewebservice.siplstudio.com/uploads/big_dish/oooo14n7464rO4_thumb.png");
URL url = new URL(getImgUrl);
URLConnection urlConnection = url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
StatusUpdate status = new StatusUpdate("Check Out FavPlates on appstore, which offers you to add and find exciting dishes near you. "+message);
//status.setMedia(file);
status.setMedia("Check Out FavPlates on appstore, which offers you to add and find exciting dishes near you. "+message, in);
mTwitter.updateStatus(status);
} catch (TwitterException e) {
Log.d("TAG", "Pic Upload error" + e.getExceptionCode());
throw e;
}
}
hope it will help you!!
If you stuck anywhere then inform me.
Thankss!!
I'm trying to do an Android app that needs to work with Google spreadsheet API. I'm new in this, so I'm starting with the version 3 of the api: https://developers.google.com/google-apps/spreadsheets/
I followed all the steps, downloaded all the jar files to lib subfolder in my project folder and then I added to the build path in Eclipse as usual. So although there is no Java example to perform Oauth 2.0, I just tried to declare:
SpreadsheetService service = new SpreadsheetService("v1");
but when I emulate this simple line it gives me an error:
java.lang.NoClassDefFoundError: com.google.gdata.client.spreadsheet.SpreadsheetService
I'm using all the jars included in the documentation and I have the import:
import com.google.gdata.client.spreadsheet.SpreadsheetService;
but I am totally lost. I dont know what else to do just to start, connect to Google APIs and work with the spreadsheets.
Sample code for you without OAuth 2.0. But its recommended to perform OAuth as its good for the security purpose. You also have to add below permissions.
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCOUNT_MANAGER"/>
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Sample Code:-
try {
SpreadsheetEntry spreadsheet;
service = new SpreadsheetService("Spreadsheet");
service.setProtocolVersion(SpreadsheetService.Versions.V3);
service.setUserCredentials("username", "password");//permission required to add in Manifest
URL metafeedUrl = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full");
feed = service.getFeed(metafeedUrl, SpreadsheetFeed.class);
List<SpreadsheetEntry> spreadsheets = feed.getEntries();
if (spreadsheets.size() > 0) {
spreadsheet = spreadsheets.get(i);//Get your Spreadsheet
}
} catch (Exception e) {
e.printStackTrace();
}
Thank you so so much Scorpion! It works!! I've been trying this for too long.
Ok here is my solution:
I started a new project and included these jars:
gdata-client-1.0
gdata-client-meta-1.0
gdata-core-1.0
gdata-spreadsheet-3.0
gdata-spreadsheet-meta-3.0
guava-13.0.1
and my code:
SpreadsheetService spreadsheet= new SpreadsheetService("v1");
spreadsheet.setProtocolVersion(SpreadsheetService.Versions.V3);
try {
spreadsheet.setUserCredentials("username", "password");
URL metafeedUrl = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full");
SpreadsheetFeed feed = spreadsheet.getFeed(metafeedUrl, SpreadsheetFeed.class);
List<SpreadsheetEntry> spreadsheets = feed.getEntries();
for (SpreadsheetEntry service : spreadsheets) {
System.out.println(service.getTitle().getPlainText());
}
} catch (AuthenticationException e) {
e.printStackTrace();
}
of course this is executed in a different thread not in the main thread. There is no java documentation for OAuth 2.0 but I will try and if I can't do it I'll ask here.
Again, thank you very much and I hope to help you when I work on this time enough. :)
(Feb 2017) The question (and most answers) are now out-of-date as:
GData APIs are the previous generation of Google APIs. While
not all GData APIs have been deprecated, all modern Google
APIs do not use the Google Data protocol
Google released a new Google Sheets API (v4; not GData) in
2016, and
Android Studio is now the preferred IDE over Eclipse. In order
to use Google APIs, you need to get the Google APIs Client Library
for Android (or for more general Java, the Google APIs Client
Library for Java). Now you're set.
To start, the latest Sheets API is much more powerful than all older versions. The latest API provides features not available in older releases, namely giving developers programmatic access to a Sheet as if you were using the user interface (create frozen rows, perform cell formatting, resize rows/columns, add pivot tables, create charts, etc.).
That said, yeah, it's tough when there aren't enough good (working) examples floating around, right? In the official docs, we try to put "quickstart" examples in as many languages as possible to help get you going. In that spirit, here are the Android quickstart code sample as well as the more general Java Quickstart code sample. For convenience, here's the Sheets API JavaDocs reference.
Another answer suggested using OAuth2 for data authorization, which you can do with this auth snippet from the quickstart above, plus the right scope:
// Sheets RO scope
private static final String[] SCOPES = {SheetsScopes.SPREADSHEETS_READONLY};
:
// Initialize credentials and service object
mCredential = GoogleAccountCredential.usingOAuth2(
getApplicationContext(), Arrays.asList(SCOPES))
.setBackOff(new ExponentialBackOff());
If you're not "allergic" to Python, I've made several videos with more "real-world" examples using the Sheets API (non-mobile though):
Migrating SQL data to a Sheet (code deep dive post)
Formatting text using the Sheets API (code deep dive post)
Generating slides from spreadsheet data (code deep dive post)
Finally, note that the Sheets API performs document-oriented functionality as described above. For file-level access, i.e. import, export etc. you'd use the Google Drive API instead; specifically for mobile, use the Google Drive Android API. Hope this helps!
It's a complex process, but it can be done! I wrote a blog post on getting the basics up and running. And I've also published an open-source project that is actually useful, but still quite minimal. It uses OAuth, and therefore can pull the permission directly from Android's permission model (no hardcoded email/password!).
You need something to start the "Choose account intent":
View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
Intent intent = AccountPicker.newChooseAccountIntent(null, null, new String[]{"com.google"},
false, null, null, null, null);
startActivityForResult(intent, 1);
if (AUTO_HIDE) {
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
return false;
}
};
And then when that intent returns, you can try to use the token that was returned (although note, if it's the first time the user may have to explicitly authorize your program; that's the UserRecoverableAuthException):
protected void onActivityResult(final int requestCode, final int resultCode,
final Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
final String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
System.err.println(accountName);
(new AsyncTask<String, String,String>(){
#Override
protected String doInBackground(String... arg0) {
try {
// Turn account name into a token, which must
// be done in a background task, as it contacts
// the network.
String token =
GoogleAuthUtil.getToken(
FullscreenActivity.this,
accountName,
"oauth2:https://spreadsheets.google.com/feeds https://docs.google.com/feeds");
System.err.println("Token: " + token);
// Now that we have the token, can we actually list
// the spreadsheets or anything...
SpreadsheetService s =
new SpreadsheetService("Megabudget");
s.setAuthSubToken(token);
// Define the URL to request. This should never change.
// (Magic URL good for all users.)
URL SPREADSHEET_FEED_URL = new URL(
"https://spreadsheets.google.com/feeds/spreadsheets/private/full");
// Make a request to the API and get all spreadsheets.
SpreadsheetFeed feed;
try {
feed = s.getFeed(SPREADSHEET_FEED_URL, SpreadsheetFeed.class);
List<SpreadsheetEntry> spreadsheets = feed.getEntries();
// Iterate through all of the spreadsheets returned
for (SpreadsheetEntry spreadsheet : spreadsheets) {
// Print the title of this spreadsheet to the screen
System.err.println(spreadsheet.getTitle().getPlainText());
}
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (UserRecoverableAuthException e) {
// This is NECESSARY so the user can say, "yeah I want
// this app to have permission to read my spreadsheet."
Intent recoveryIntent = e.getIntent();
startActivityForResult(recoveryIntent, 2);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GoogleAuthException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}}).execute();
} else if (requestCode == 2 && resultCode == RESULT_OK) {
// After the user YAYs or NAYs our permission request, we are
// taken here, so if we wanted to grab the token now we could.
}
}
I want to post score points using facebook graph api, from my android application
I create android app in facebook developers page. I set to Native Android App , and I set Mobile Web settings like on image below
In android code I user this permissions for my app:
String[] permissions = {"publish_stream","publish_actions","user_games_activity","friends_games_activity"};
After successful login on facebook, I try to post score points to facebook using this android code
Bundle params = new Bundle();
params.putString("score", "100");
//params.putString("access_token", "token as constant");
String response = "null";
Utility.mFacebook.setAccessToken("token as constant");
try {
response = Utility.mFacebook.request("user_id/scores", params, "POST");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
And I receive this response:
{"error":{"message":"(#15) This method must be called with an app access_token.","type":"OAuthException","code":15}}
I get same error if I use Graph API Explorer:
In facebook settings ->Apps -> AppName -> Advanced->App Type is set to "Web" (I also try with Native/Desktop but I get same error)
Can anyone help me and tell me how to sent score from my android app to fb?
Thanks
"(#15) This method must be called with an app access_token."
Looks like you tried with an user access token.
See https://developers.facebook.com/docs/authentication/applications/ on how to get an app access token.
I need to obtain OAuth2 authentication token to pass it to the server so it can fetch list of Google Reader feeds for the user. Server is .NET - I have no access to it or to it's code but most likely it is using unofficial Reader API
I was able to use Android Account manager to obtain valid token for this purpose with the following code (notice that authTokenType="reader")
Account account = accounts[0];
manager.getAuthToken(account, "reader", null, this, new AccountManagerCallback<Bundle>() {
public void run(AccountManagerFuture<Bundle> future) {
try {
// If the user has authorized your application to use the tasks API
// a token is available.
String token = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
// Now you can send the token to API...
cacheManager.putString(GOOGLE_AUTH, token);
GoogleReaderManager.startAddFeedActivity(AddGoogleReaderSourcesActivity.this);
finish();
} catch (OperationCanceledException e) {
Log.e(TAG, "User cancelled", e);
finish();
} catch (Exception e) {
Log.e(TAG, "Failed to obtain Google reader API_KEY", e);
}
}
}, null);
The code above works fine when I send token to the server side .Net app: the app is able to retrieve the list of Reader feeds.
The problem is that this only works for "Google inside" devices. On Nook I have no such luck since there's no way that I was able to find to add Google account to the account manager. So I'm trying to it using OAuth 2 protocol as described here
It works fine as far as obtaining the token: User approves the app from the mobile page which returns the code token which then mobile app exchanges for the Auth token. However this token will not work with the server process. I have a feeling that perhaps I'm using the wrong scope in this URL:
https://accounts.google.com/o/oauth2/auth?response_type=code&scope=https://www.google.com/reader/api/0/subscription/list&redirect_uri=http://localhost&approval_prompt=force&state=/ok&client_id={apps.client.id}
Scopes that I did try in various combinations:
https://www.google.com/reader/api
https://www.google.com/reader/api/0
https://www.google.com/reader/api/0/subscription/list
https://www.google.com/reader/api+https://www.google.com/reader/atom
Here's example of JSON that is returned from get token POST
{"expires_in":3600,
"token_type":"Bearer",
"access_token":"ya29.AHES6ZSEvuUb6Bvd2DNoMnnN_UnfxirZmf_RQjn7LptFLfI",
"refresh_token":"1\/bUwa5MyOtP6VyWqaIEKgfPh08LNdawJ5Qxz6-qZrHg0"}
Am I messing up scope or token type? Not sure how to change a token type. Any other ideas?
P.S. Google account login page asks: Manage your data in Google Reader, that's why I suspect that the scope is wrong
I got it working for https://www.google.com/reader/api/0/subscription/list. So thought of sharing with you.
I have valid access_token:
This is what i tried to resolve it (partially) :
Google provides OAuth 2.o playgound; where they actually simulate all aspects of OAuth 2.0 as well as final API call to fetch data.
I found this very helpful as it clearly shows what is being sent to request.
Here is the URL : https://developers.google.com/oauthplayground/
Using this, i tweaked my api call below and it works :)
public static String getReaderContent(String accessToken){
String url = "https://www.google.com/reader/api/0/subscription/list" ;
HttpClient client = new HttpClient();
GetMethod method = new GetMethod(url);
String response="";
method.setRequestHeader("Authorization", "OAuth "+accessToken);
try {
int statusCode = client.executeMethod(method);
String response= method.getResponseBodyAsString();
System.out.println("response " + responseStr);
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
So this works properly fine for getting subscription list; but have not been able to make it work for reader api which you have mentioned in your question.
Let me know if you have got way around google reader API.
I am trying to integrate yahoo in my app. I am trying,
private static final String YAHOO_CALLBACK_URI = "MyApp://oauth";
public static final String YAHOO_REQUEST_TOKEN_URL = "http://api.login.yahoo.com/oauth/request_token";//api.login.yahoo.com
public static final String YAHOO_ACCESS_TOKEN_URL = "http://api.login.yahoo.com/oauth/access_token";
public static final String YAHOO_AUTHORIZE_URL = "http://api.login.yahoo.com/authorize";
CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(YAHOO_CONSUMER_KEY, YAHOO_CONSUMER_SERECT_KEY);
OAuthProvider provider = new CommonsHttpOAuthProvider(YAHOO_REQUEST_TOKEN_URL, YAHOO_ACCESS_TOKEN_URL, YAHOO_AUTHORIZE_URL);
provider.setOAuth10a(true);
try {
String authUrl = provider.retrieveRequestToken(consumer, YAHOO_CALLBACK_URI);// Can I pass Null for callback url.
System.out.println("AuthURL = " + authUrl);
} catch (OAuthMessageSignerException e) {
e.printStackTrace();
} catch (OAuthNotAuthorizedException e) {
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
e.printStackTrace();
} catch (OAuthCommunicationException e) {
e.printStackTrace();
}
getting
oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: Service provider responded in error: 404 (Not Found)
Why we are unable to retrieve request token.
Make sure your app on Yahoo is registered as Web-Based. When you register as a Web-Based application, give a valid Application URL and App Domain of your choice (both should be the same domain), but has not been used by anyone else. I, for example, have the url of a website I own. This will also be used as the callback url in your consumer.
Instead of calling "MyApp://oauth", give a valid http callback url (the same one you used to register the app). With that much, your code above should work.
Open a new Webview and call the authUrl. Once your app is authorised, intercept the call to your application url by overriding the "onPageStarted" method. There, make a callback to your app by launching a new intent pointing to "MyApp://oauth".
Please let me know if any of the obove steps confuse you - I am more than happy to help.
I had followed the above mentioned 3#poits and able to do the call back to the application. The whole problem started with YAHOO OAUTH Process. Now Yahoo doesnt take the Custom Call back urls, It has to be a valid http url. n
There are couple of issues i have it which i am solving on my own,like Having a CUSTOMi Dialog box which can be used to call the Web-view YAHOO Auth URL similar to FB Dialog.
Thanks for the