Can I override the autotimeout on Android? - java

I am using Twitter4J to post to Twitter but you have to open up the browser and get a pin from Twitter for my app to be able to do this and that works but when I return to my app, the activity times out and closes itself. Is there a way to keep my activity open? The webview does not work as Twitter doesn't let you authorize with a regular path.
public void TwitterSend () {
// The factory instance is re-useable and thread safe.
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(consumer_token, consumer_secret);
//WebView webview = (WebView) findViewById(R.id.webview);
//webview.setVisibility(View.VISIBLE);
//ScrollView sc = (ScrollView) findViewById(R.id.scrollView1);
//sc.setVisibility(View.VISIBLE);
EditText edit = (EditText) findViewById(R.id.editText1);
edit.setVisibility(View.VISIBLE);
RequestToken requestToken = null;
try {
requestToken = twitter.getOAuthRequestToken();
System.out.println(requestToken.toString());
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
AccessToken accessToken = null;
//webview.loadUrl("https://api.twitter.com/oauth/authorize");
Intent browserIntent = new Intent("android.intent.action.VIEW", Uri.parse(requestToken.getAuthorizationURL()));
browserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(browserIntent);
System.out.println("Open the following URL and grant access to your account:");
System.out.print("Enter the PIN(if aviailable) or just hit enter.[PIN]:");
String pin = edit.getText().toString();
CountDownTimer timer = new CountDownTimer(900000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
}
};
timer.start();
while(pin.length()<7)
{
pin = edit.getText().toString();
}
System.out.print(pin);
try{
if(pin.length() > 0){
accessToken = twitter.getOAuthAccessToken(requestToken, pin);
}else{
accessToken = twitter.getOAuthAccessToken();
}
} catch (TwitterException te) {
if(401 == te.getStatusCode()){
System.out.println("Unable to get the access token.");
edit.setVisibility(View.GONE);
}else{
te.printStackTrace();
}
}
//persist to the accessToken for future reference.
Status status = null;
try {
SharedPreferences stats = getSharedPreferences(PREFS_NAME, 0);
String quote = stats.getString("shareQuote", "An error has occured. We are Sorry.");
status = twitter.updateStatus(quote);
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//webview.setVisibility(View.GONE);
//edit.setVisibility(View.GONE);
}
Toast.makeText(getApplicationContext(), "Successfully updated the status to [" + status.getText() + "].", Toast.LENGTH_LONG).show();
System.out.println("Successfully updated the status to [" + status.getText() + "].");
// webview.setVisibility(View.GONE);
edit.setVisibility(View.GONE);
//sc.setVisibility(View.GONE);
/*WebView webview = (WebView) findViewById(R.id.webview);
webview.setVisibility(View.VISIBLE);
Twitter twitter=new TwitterFactory().getInstance();
twitter.setOAuthConsumer(consumer_token, consumer_secret);
AccessToken a = new AccessToken(oauth_token, oauth_token_secret);
twitter.setOAuthAccessToken(a);
try {
RequestToken requestToken = twitter.getOAuthRequestToken("https://api.twitter.com/oauth/request_token");
webview.loadUrl("https://api.twitter.com/oauth/authorize");
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}

It's generally a bad idea in Android to try to force activities to stay open - the best way to deal with activities being destroyed is to make sure that you are handling all of your activities' lifecycle callbacks properly. This page is helpful: http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
If you properly save the state of your activity, you shouldn't have problems with the system stopping it.

Related

How to fetch linkedin connection details(birthday etc) in android

I am unable to fetch linkedin connection details;i am able to fetch only default details like first and last name,id etc.but i want to fetch connections dob,email etc..
share = (Button) findViewById(R.id.share);
name = (TextView) findViewById(R.id.name);
et = (EditText) findViewById(R.id.et_share);
login = (Button) findViewById(R.id.login);
photo = (ImageView) findViewById(R.id.photo);
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
linkedInLogin();
}
});
// share on linkedin
share.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String share = et.getText().toString();
if (null != share && !share.equalsIgnoreCase("")) {
OAuthConsumer consumer = new CommonsHttpOAuthConsumer(Config.LINKEDIN_CONSUMER_KEY, Config.LINKEDIN_CONSUMER_SECRET);
consumer.setTokenWithSecret(accessToken.getToken(), accessToken.getTokenSecret());
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost("https://api.linkedin.com/v1/people/~/shares");
try {
consumer.sign(post);
} catch (OAuthMessageSignerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthCommunicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // here need the consumer for sign in for post the share
post.setHeader("content-type", "text/XML");
String myEntity = "<share><comment>"+ share +"</comment><visibility><code>anyone</code></visibility></share>";
try {
post.setEntity(new StringEntity(myEntity));
org.apache.http.HttpResponse response = httpclient.execute(post);
Toast.makeText(LinkedInSampleActivity.this,
"Shared sucessfully", Toast.LENGTH_SHORT).show();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
Toast.makeText(LinkedInSampleActivity.this,
"Please enter the text to share",
Toast.LENGTH_SHORT).show();
}
}
});
}
private void linkedInLogin() {
ProgressDialog progressDialog = new ProgressDialog(
LinkedInSampleActivity.this);
LinkedinDialog d = new LinkedinDialog(LinkedInSampleActivity.this,
progressDialog);
d.show();
// set call back listener to get oauth_verifier value
d.setVerifierListener(new OnVerifyListener() {
#Override
public void onVerify(String verifier) {
try {
Log.i("LinkedinSample", "verifier: " + verifier);
accessToken = LinkedinDialog.oAuthService
.getOAuthAccessToken(LinkedinDialog.liToken,
verifier);
LinkedinDialog.factory.createLinkedInApiClient(accessToken);
client = factory.createLinkedInApiClient(accessToken);
// client.postNetworkUpdate("Testing by Mukesh!!! LinkedIn wall post from Android app");
Log.i("LinkedinSample",
"ln_access_token: " + accessToken.getToken());
Log.i("LinkedinSample",
"ln_access_token: " + accessToken.getTokenSecret());
Person p = client.getProfileForCurrentUser();
name.setText("Welcome " + p.getFirstName() + " "
+ p.getLastName()+"DOB"+p.getDateOfBirth());
name.setVisibility(0);
login.setVisibility(4);
share.setVisibility(0);
et.setVisibility(0);
userConnections();
} catch (Exception e) {
Log.i("LinkedinSample", "error to get verifier");
e.printStackTrace();
}
}
private void userConnections() {
final Set<ProfileField> connectionFields = EnumSet.of(ProfileField.ID,
ProfileField.FIRST_NAME,
ProfileField.LAST_NAME,
**ProfileField.DATE_OF_BIRTH,**
ProfileField.PHONE_NUMBERS
);
connections = client.getConnectionsForCurrentUser(connectionFields);
for (Person person : connections.getPersonList()) {
System.out.println("connections name"+person.getFirstName()+" "+person.getLastName()+":"+**person.getDateOfBirth()**+person.getId());
itemslist.add(person);
}
System.out.println("person arraylist count of my connections"+itemslist.size());
}
});
// set progress dialog
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(true);
progressDialog.show();
}
I tried to fetch date of birth of my connections,but its showing null in the position..
D.O.B. isn't a field you can get for a connection. Please read the documentation - "For 1st degree connections, you may only retrieve profile fields available with the r_basicprofile member permission"
https://developers.linkedin.com/documents/connections-api

How to Post Tweet on Twiiter Using own application

I want to post a tweet from my application on Twitter. This tweet will show in my application as well as twitter.
I have all detail of the user, and I don't want to log in on Twitter. Here is the format which I am getting from the web service:
<string xmlns="http://tempuri.org/">
{"Id":"cc02cf6c-c143-4921-b5d6-6afec1243c10","TwitterUserId":"123456",
"TwitterScreenName":"abc", "OAuthToken":"xxxxxxxxxxxxxxxxxxxx",
"OAuthSecret":"xxxxxxxxxxxx", "UserId":"zzzzzzzzzz", "FollowersCount":1, "IsActive":true,
"FollowingCount":13, "ProfileUrl":"", "ProfileImageUrl":"http://abs.xxxxxxxxxxxxx.png",
"TwitterName":null}
</string>
Below is my code which posts a tweet on twitter, but here they are using log in with twitter. I don't want to log in.
Please guide me or if possible then provide me some sample code.
I am using twitter4j library.
public class MainActivity extends Activity implements OnClickListener {
// Constants
/**
* Register your here app https://dev.twitter.com/apps/new and get your
* consumer key and secret
* */
static String TWITTER_CONSUMER_KEY = "xxxxxxxxxxxxxxxxxx";
static String TWITTER_CONSUMER_SECRET = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";
// Preference Constants
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";
// Twitter oauth urls
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
Button btnLoginTwitter;
Button btnUpdateStatus; // This is responsible for tweet updation
Button btnLogoutTwitter;
EditText txtUpdate;
ProgressDialog pDialog;
// Twitter
private static Twitter twitter;
private static RequestToken requestToken;
// Shared Preferences
private static SharedPreferences mSharedPreferences;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Check if twitter keys are set
if (TWITTER_CONSUMER_KEY.trim().length() == 0
|| TWITTER_CONSUMER_SECRET.trim().length() == 0) {
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens",
"Please set your twitter oauth tokens first!", false);
// stop executing code by return
return;
}
/*
RequestToken reqToken = (RequestToken) session.getAttribute(REQUEST_TOKEN);
session.removeAttribute(REQUEST_TOKEN);
if (!reqToken.getToken().equals(oauthToken)) {
throw new TwitterException("Wrong oauth_token");
}
AccessToken token = twitter.getOAuthAccessToken(reqToken);
*/
// All UI elements
btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter);
btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus);
btnLogoutTwitter = (Button) findViewById(R.id.btnLogoutTwitter);
txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus);
// Shared Preferences
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
btnLoginTwitter.setOnClickListener(this);
btnUpdateStatus.setOnClickListener(this);
btnLogoutTwitter.setOnClickListener(this);
/**
* This if conditions is tested once is redirected from twitter page.
* Parse the uri to get oAuth Verifier
* */
if (!isTwitterLoggedInAlready()) {
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
// oAuth verifier
String verifier = uri
.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
try {
// Get the access token
AccessToken accessToken = twitter.getOAuthAccessToken(
requestToken, verifier);
// Shared Preferences
Editor e = mSharedPreferences.edit();
// After getting access token, access token secret
// store them in application preferences
e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_SECRET,
accessToken.getTokenSecret());
// Store login status - true
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.commit(); // save changes
// Hide login button
btnLoginTwitter.setVisibility(View.GONE);
// Show Update Twitter
txtUpdate.setVisibility(View.VISIBLE);
btnUpdateStatus.setVisibility(View.VISIBLE);
btnLogoutTwitter.setVisibility(View.VISIBLE);
// Getting user details from twitter
// For now i am getting his name only
long userID = accessToken.getUserId();
System.out.println("--------User Id--------------"+userID);
User user = twitter.showUser(userID);
System.out.println("-------- user --------------"+user);
String username = user.getName();
System.out.println("-------- username --------------"+username);
Toast.makeText(getApplicationContext(),
Html.fromHtml("<b>Benvenuto " + username + "</b>"),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
// Check log for login errors
Log.e("Errore Login", "> " + e.getMessage());
}
}
}
}
/**
* Function to login twitter
* */
private void loginToTwitter() {
// Check if already logged in
if (!isTwitterLoggedInAlready()) {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
try {
requestToken = twitter
.getOAuthRequestToken(TWITTER_CALLBACK_URL);
System.out.println("requestToken"+requestToken);
this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(requestToken.getAuthenticationURL())));
} catch (TwitterException e) {
e.printStackTrace();
}
} else {
// user already logged into twitter
btnLoginTwitter.setVisibility(View.GONE);
// Show Update Twitter
txtUpdate.setVisibility(View.VISIBLE);
btnUpdateStatus.setVisibility(View.VISIBLE);
btnLogoutTwitter.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(),
"Logged in", Toast.LENGTH_LONG).show();
}
}
/**
* Function to update status
* */
class updateTwitterStatus extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Update in corso...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Places JSON
* */
protected String doInBackground(String... args) {
Log.d("Tweet Text", "> " + args[0]);
String status = args[0];
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
// Access Token
String access_token = mSharedPreferences.getString(
PREF_KEY_OAUTH_TOKEN, "xxxxxxxxxxxxxxxxxxxxxxxxxxx");
System.out.println("access_token"+access_token);
// Access Token Secret
String access_token_secret = mSharedPreferences.getString(
PREF_KEY_OAUTH_SECRET, "xxxxxxxxxxxxxxxxxxxxxxxxxxx");
System.out.println("access_token_secret"+access_token_secret);
AccessToken accessToken = new AccessToken(access_token,
access_token_secret);
Twitter twitter = new TwitterFactory(builder.build())
.getInstance(accessToken);
// Update status
twitter4j.Status response = twitter.updateStatus(status);
Log.d("Status", "> " + response.getText());
} catch (TwitterException e) {
// Error in updating status
Log.d("Twitter Update Error", e.getMessage());
}
return null;
}
/**
* After completing background task Dismiss the progress dialog and show
* the data in UI Always use runOnUiThread(new Runnable()) to update UI
* from background thread, otherwise you will get error
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Tweet Send", Toast.LENGTH_SHORT)
.show();
// Clearing EditText field
txtUpdate.setText("");
}
});
}
}
/**
* Function to logout from twitter It will just clear the application shared
* preferences
* */
private void logoutFromTwitter() {
// Clear the shared preferences
Editor e = mSharedPreferences.edit();
e.remove(PREF_KEY_OAUTH_TOKEN);
e.remove(PREF_KEY_OAUTH_SECRET);
e.remove(PREF_KEY_TWITTER_LOGIN);
e.commit();
// After this take the appropriate action
// I am showing the hiding/showing buttons again
// You might not needed this code
btnLogoutTwitter.setVisibility(View.GONE);
btnUpdateStatus.setVisibility(View.GONE);
txtUpdate.setVisibility(View.GONE);
btnLoginTwitter.setVisibility(View.VISIBLE);
}
/**
* Check user already logged in your application using twitter Login flag is
* fetched from Shared Preferences
* */
private boolean isTwitterLoggedInAlready() {
// return twitter login status from Shared Preferences
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
protected void onResume() {
super.onResume();
}
#Override
public void onClick(View view) {
if (view == btnLoginTwitter) {
loginToTwitter();
}
if (view == btnLogoutTwitter) {
logoutFromTwitter();
}
if (view == btnUpdateStatus) {
// Call update status function
// Get the status from EditText
String status = txtUpdate.getText().toString();
System.out.println("----------hiiiiiiii--------------"+status);
// Check for blank text
if (status.trim().length() > 0) {
// update status
new updateTwitterStatus().execute(status);
} else {
// EditText is empty
Toast.makeText(getApplicationContext(),
"Please enter status message", Toast.LENGTH_SHORT)
.show();
}
}
}
}
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.setOAuthConsumerKey(context.getResources().getString(R.string.twitter_consumer_key));
configurationBuilder.setOAuthConsumerSecret(context.getResources().getString(R.string.twitter_consumer_secret));
configurationBuilder.setOAuthAccessToken("HERE ENTER UR ACCESS TOKEN RECEIVED IN YOUR WEB SERVICE"));
configurationBuilder.setOAuthAccessTokenSecret("HERE ENTER UR ACCESS TOKEN SECRET RECEIVED IN YOUR WEB SERVICE"));
Configuration configuration = configurationBuilder.build();
final Twitter twitter = new TwitterFactory(configuration).getInstance();
new Thread(new Runnable() {
private double x;
#Override
public void run() {
boolean success = true;
try {
x = Math.random();
twitter.updateStatus(message +" "+x);
} catch (TwitterException e) {
e.printStackTrace();
success = false;
}
final boolean finalSuccess = success;
callingActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
postResponse.onFinsihed(finalSuccess);
}
});
}
}).start();
The above method will let you post the tweet if you have a valid access token and access token secret.
cheers :)
Here is code to post message on twitter
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.setOAuthConsumerKey(context.getResources().getString(R.string.twitter_consumer_key));
configurationBuilder.setOAuthConsumerSecret(context.getResources().getString(R.string.twitter_consumer_secret));
configurationBuilder.setOAuthAccessToken(LoginActivity.getAccessToken((context)));
configurationBuilder.setOAuthAccessTokenSecret(LoginActivity.getAccessTokenSecret(context));
Configuration configuration = configurationBuilder.build();
final Twitter twitter = new TwitterFactory(configuration).getInstance();
new Thread(new Runnable() {
private double x;
#Override
public void run() {
boolean success = true;
try {
x = Math.random();
twitter.updateStatus(message +" "+x);
} catch (TwitterException e) {
e.printStackTrace();
success = false;
}
final boolean finalSuccess = success;
callingActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
postResponse.onFinsihed(finalSuccess);
}
});
}
}).start();
check this tutorial for more details.

Wait till get my id and my friends id facebook

I want to wait till i get my user name and my id, and also to wait until I get the user names and users id of my friends in facebook. how can I implement it?
I wrote a code after these two Request however sometimes one Request didn't finish and I get null in one of the variables (for example the userName variable)
therefor I want to wait till these two requests finish.
Or maybe there is another better implementation?
this is my code:
final CountDownLatch isForFinish = new CountDownLatch(1);
private class SessionStatusCallback implements Session.StatusCallback {
#Override
public void call(Session session, SessionState state, Exception exception) {
if( session.isOpened() ){
Request.executeMyFriendsRequestAsync(session, new Request.GraphUserListCallback() {
#Override
public void onCompleted(List<GraphUser> users, Response response) {
for (int i=0;i<users.size();i++){
friendsId+= (users.get(i).getId()+",");
friendsName+=(users.get(i).getName()+",");
}
isForFinish.countDown();
}
});
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
String userName = user.getName();
String userId = user.getId();
Intent i = new Intent(getApplicationContext(), TabMainActivity.class);
String email=null;
try {
email = (String) user.getInnerJSONObject().getString("email");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(email!=null){
String newemail=new String(email);
newemail = email.replace("#", "_");
newemail = newemail.replace(".", "_");
TelephonyManager mTelephonyMgr;
mTelephonyMgr = (TelephonyManager) getSystemService
(Context.TELEPHONY_SERVICE);
String phoneNumber = mTelephonyMgr.getLine1Number();
String password = "facebook";
ParseUser Puser = new ParseUser();
Puser.setUsername(userId);
Puser.setPassword("facebook");
Puser.setEmail(email);
Puser.put("Name", userName);
try {
isForFinish.await();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Puser.put("friendsId",friendsId );
Puser.put("friendsName",friendsName );
try {
Puser.signUp();
ParseObject saleObj =new ParseObject("sale_"+idOfUser);
saleObj.saveInBackground();
ParseObject deliverObj =new ParseObject("deliver_"+idOfUser);
deliverObj.saveInBackground();
ParseObject group =new ParseObject("group_"+idOfUser);
group.saveInBackground();
ParseObject freind =new ParseObject("freind"+idOfUser);
freind.saveInBackground();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
i.putExtra("friendsId", friendsId);
i.putExtra("emailOwner", newemail);
i.putExtra("phone", phoneNumber);
i.putExtra("email",email );
i.putExtra("password",password );
i.putExtra("id",userId );
i.putExtra("name",userName );
startActivity(i);
}
}
});
}
For dependent threads, you can use a countdown latch :
http://developer.android.com/reference/java/util/concurrent/CountDownLatch.html
Here is an example:
http://www.javacodegeeks.com/2011/09/java-concurrency-tutorial.html
Using Android Facebook 3.0 setup the Fragment to manage the states using this tutorial
https://developers.facebook.com/docs/tutorials/androidsdk/3.0/scrumptious/authenticate/
You can use the prebuilt facebook login button to also login using the xml
<com.facebook.widget.LoginButton
android:id="#+id/authButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="51dp" />
Then either using the Session StatusCallback
https://developers.facebook.com/docs/reference/android/3.0/Session.StatusCallback
or the overrides you created in the fragment in the previous tutorial you can initiate a call to retrieve your friends which would look like this
void getFriendsWithApp(final Intent intent){
final ProgressDialog mDialog = new ProgressDialog(this);
mDialog.setMessage("Loading...");
mDialog.setCancelable(false);
mDialog.show();
String fqlQuery = "SELECT uid, name, pic_square FROM user WHERE uid IN " +
"(SELECT uid2 FROM friend WHERE uid1 = me())";
Bundle params = new Bundle();
params.putString("q", fqlQuery);
Session session = Session.getActiveSession();
Request request = new Request(session,
"/fql",
params,
HttpMethod.GET,
new Request.Callback(){
public void onCompleted(Response response) {
try {
mDialog.dismiss();
Type listType = new TypeToken<ArrayList<Friend>>(){}.getType();
Utils.friends = new Gson().fromJson(response.getGraphObject().getInnerJSONObject().getJSONArray("data").toString(), listType);
startActivity(intent);
//This is where you would do what you want after you retrieve your json with friends
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Request.executeBatchAsync(request);
}

I want to access twitter api in my android application,My code is not performing well,either its not showing any error also [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 10 years ago.
I followed this tutorial fully for accesing twitter api in my android application, http://www.androidhive.info/2012/09/android-twitter-oauth-connect-tutorial/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Check if twitter keys are set
if(TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0){
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens", "Please set your twitter oauth tokens first!", false);
// stop executing code by return
return;
}
// All UI elements
btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter);
btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus);
btnLogoutTwitter = (Button) findViewById(R.id.btnLogoutTwitter);
txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus);
lblUpdate = (TextView) findViewById(R.id.lblUpdate);
lblUserName = (TextView) findViewById(R.id.lblUserName);
// Shared Preferences
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
/**
* Twitter login button click event will call loginToTwitter() function
* */
btnLoginTwitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String tweet = txtUpdate.getText().toString();
new LoginTask().execute(tweet);
}
});
/**
* Button click event to Update Status, will call updateTwitterStatus()
* function
* */
btnUpdateStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Call update status function
// Get the status from EditText
String status = txtUpdate.getText().toString();
// Check for blank text
if (status.trim().length() > 0) {
// update status
new updateTwitterStatus().execute(status);
} else {
// EditText is empty
Toast.makeText(getApplicationContext(),
"Please enter status message", Toast.LENGTH_SHORT)
.show();
}
}
});
/**
* Button click event for logout from twitter
* */
btnLogoutTwitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Call logout twitter function
logoutFromTwitter();
}
});
/** This if conditions is tested once is
* redirected from twitter page. Parse the uri to get oAuth
* Verifier
* */
if (!isTwitterLoggedInAlready()) {
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
// oAuth verifier
String verifier = uri
.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
try {
// Get the access token
AccessToken accessToken = twitter.getOAuthAccessToken(
requestToken, verifier);
// Shared Preferences
Editor e = mSharedPreferences.edit();
// After getting access token, access token secret
// store them in application preferences
e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_SECRET,
accessToken.getTokenSecret());
// Store login status - true
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.commit(); // save changes
Log.e("Twitter OAuth Token", "> " + accessToken.getToken());
// Hide login button
btnLoginTwitter.setVisibility(View.GONE);
// Show Update Twitter
lblUpdate.setVisibility(View.VISIBLE);
txtUpdate.setVisibility(View.VISIBLE);
btnUpdateStatus.setVisibility(View.VISIBLE);
btnLogoutTwitter.setVisibility(View.VISIBLE);
// Getting user details from twitter
// For now i am getting his name only
long userID = accessToken.getUserId();
User user = twitter.showUser(userID);
String username = user.getName();
// Displaying in xml ui
lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>"));
} catch (Exception e) {
// Check log for login errors
Log.e("Twitter Login Error", "> " + e.getMessage());
}
}
}
}
/**
* Function to login twitter
* */
public class LoginTask extends AsyncTask<String, String, String> {
protected void onPostExecute(Bitmap result) {
boolean everythingGood = false;
if (everythingGood) {
showToast("Success!");
startActivity(new Intent());
} else {
showAlert("Error!");
}
}
private void showToast(String string) {
// TODO Auto-generated method stub
}
private void showAlert(String string) {
// TODO Auto-generated method stub
}
#Override
protected String doInBackground(String... args) {
String tweet = args[0];
loginToTwitter();
return null;
}
private void startActivity(Intent intent) {
// TODO Auto-generated method stub
}
}
private void loginToTwitter() {
// Check if already logged in
if (!isTwitterLoggedInAlready()) {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
twitter4j.conf.Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
try {
requestToken = twitter
.getOAuthRequestToken(TWITTER_CALLBACK_URL);
this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(requestToken.getAuthenticationURL())));
} catch (TwitterException e) {
e.printStackTrace();
}
} else {
// user already logged into twitter
Toast.makeText(getApplicationContext(),
"Already Logged into twitter", Toast.LENGTH_LONG).show();
}
}
public void showToast(String string) {
// TODO Auto-generated method stub
}
/**
* Function to update status
* */
class updateTwitterStatus extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Updating to twitter...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Places JSON
* */
protected String doInBackground(String... args) {
Log.d("Tweet Text", "> " + args[0]);
String status = args[0];
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
// Access Token
String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
// Access Token Secret
String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
// Update status
twitter4j.Status response = twitter.updateStatus(status);
Log.d("Status", "> " + response.getText());
} catch (TwitterException e) {
// Error in updating status
Log.d("Twitter Update Error", e.getMessage());
}
return null;
}
/**
* After completing background task Dismiss the progress dialog and show
* the data in UI Always use runOnUiThread(new Runnable()) to update UI
* from background thread, otherwise you will get error
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Status tweeted successfully", Toast.LENGTH_SHORT)
.show();
// Clearing EditText field
txtUpdate.setText("");
}
});
}
}
/**
* Function to logout from twitter
* It will just clear the application shared preferences
* */
private void logoutFromTwitter() {
// Clear the shared preferences
Editor e = mSharedPreferences.edit();
e.remove(PREF_KEY_OAUTH_TOKEN);
e.remove(PREF_KEY_OAUTH_SECRET);
e.remove(PREF_KEY_TWITTER_LOGIN);
e.commit();
// After this take the appropriate action
// I am showing the hiding/showing buttons again
// You might not needed this code
btnLogoutTwitter.setVisibility(View.GONE);
btnUpdateStatus.setVisibility(View.GONE);
txtUpdate.setVisibility(View.GONE);
lblUpdate.setVisibility(View.GONE);
lblUserName.setText("");
lblUserName.setVisibility(View.GONE);
btnLoginTwitter.setVisibility(View.VISIBLE);
}
/**
* Check user already logged in your application using twitter Login flag is
* fetched from Shared Preferences
* */
private boolean isTwitterLoggedInAlready() {
// return twitter login status from Shared Preferences
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
protected void onResume() {
super.onResume();
}
}
**Is this code is correct or not?after logged in it has to show my tweet column like update status,like that,but its not going to next stage
Android 4 throws such an exception when you do network operations in main thread.
Consider using AsyncTasks or Handlers or any other way of threading.
You can start from here:
http://android-developers.blogspot.com/2009/05/painless-threading.html
Sample:
#Override
public void onClick(View arg0) {
new LoginTask.execute();
});
class LoginTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPostExecute(Bitmap result) {
if (everythingGood) {
showToast("Success!");
startActivity(new Intent());
} else {
showAlert("Error!");
}
}
#Override
protected Void doInBackground(Void... params) {
loginToTwitter();
}
}
Use the async task to do this in separate thread.
http://developer.android.com/reference/android/os/AsyncTask.html
You can define another class which extends the async task and do your work in that class.
Find the below working code
public class LoginTask extends AsyncTask<Void, Void, RequestToken> {
private ProgressDialog progressDialog;
public LoginTask() {
progressDialog = ProgressDialog.show(MainActivity.this, "", "Loading. Please wait...", false);
}
#Override
protected RequestToken doInBackground(Void... params) {
// TODO Auto-generated method stub
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
try {
return requestToken = twitter
.getOAuthRequestToken(TWITTER_CALLBACK_URL);
} catch (TwitterException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
MainActivity.this.setProgressBarIndeterminateVisibility(true);
}
#Override
protected void onPostExecute(RequestToken result) {
// TODO Auto-generated method stub
MainActivity.this.setProgressBarIndeterminateVisibility(false);
progressDialog.dismiss();
try {
requestToken = result;
MainActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(requestToken.getAuthenticationURL())));
} catch(Exception e) {
e.printStackTrace();
alert.showAlertDialog(MainActivity.this, "Internet Connection Timeout Error",
"Please try later.", false);
}
}
}
Can you put your logcat error. So that it will easy to find why you are getting null pointer exception.

twitter4j no authentication challenges found

Been trying to use twitter4j to post a tweet for couple days now without luck, what i want to do is for a person to post their new top score on their timeline from the app at the end of a round. Here is my code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tweetr);
Button tweetr = (Button)findViewById(R.id.tweetr);
//create a new twitter configuration using user details
tweetTwitter = new TwitterFactory().getInstance();
tweetTwitter.setOAuthConsumer(TWIT_KEY, TWIT_SECRET);
//create a twitter instance
// tweetTwitter = new TwitterFactory(twitConf).getInstance();
tweetr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dt.execute();
}
});
}
public class TweetTask extends AsyncTask<Object, Void, String> {
#Override
protected String doInBackground(Object... values) {
/* try {
//requestToken = tweetTwitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));
*/
try {
requestToken = tweetTwitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
String authUrl = requestToken.getAuthenticationURL();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
Log.d("URI", "DONE");
super.onPostExecute(result);
}
}
#Override
protected void onResume() {
super.onResume();
final Uri uri = getIntent().getData();
if(uri != null ){
Log.d("URI", uri.toString());
Thread th = new Thread(){
public void run(){
try {
String verifier = uri.getQueryParameter("oauth_verifier");
String oauthToken = uri.getQueryParameter("oauth_token");
RequestToken reqToken = tweetTwitter.getOAuthRequestToken(oauthToken,verifier);
AccessToken accessToken = tweetTwitter.getOAuthAccessToken(reqToken);
String token = accessToken.getToken(), secret = accessToken.getTokenSecret();
} catch (TwitterException ex) {
Log.e("Main.onNewIntent", "" + ex.getMessage());
}
}};
th.start();
}else
Log.d("URI", "FAILED");
}
}
This is my error print out
10-23 15:35:18.661: D/TWIT ER(2392): No authentication challenges foundRelevant discussions can be found on the Internet at:
refer to the javadoc of Twitter4J
In order to get access acquire AccessToken using xAuth, you must apply by sending an email to api#twitter.com — all other applications will receive an HTTP 401 error.

Categories