I am trying to run an OAuth in my android app to get user data from LinkedIn and as i just started on the project i have run into a major bug/issue. After requesting the token from the following code, the token doesn't get received and the app continues to open in the on-phone browser used for the authentication.
Any help would be appreciated as I am really new to android development.
package com.tushar.linkedinauth;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.google.code.linkedinapi.client.LinkedInApiClient;
import com.google.code.linkedinapi.client.LinkedInApiClientFactory;
import com.google.code.linkedinapi.client.oauth.LinkedInAccessToken;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthService;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthServiceFactory;
import com.google.code.linkedinapi.client.oauth.LinkedInRequestToken;
public class MainActivity extends Activity {
public static final String CONSUMER_KEY = "MyConsumerKey";
public static final String CONSUMER_SECRET = "MyConsumerSecret";
public static final String OAUTH_CALLBACK_SCHEME = "x-oauthflow-linkedin";
public static final String OAUTH_CALLBACK_HOST = "callback";
public static final String OAUTH_CALLBACK_URL = OAUTH_CALLBACK_SCHEME + "://" + OAUTH_CALLBACK_HOST;
final LinkedInOAuthService oAuthService = LinkedInOAuthServiceFactory.getInstance().createLinkedInOAuthService(CONSUMER_KEY, CONSUMER_SECRET);
final LinkedInApiClientFactory factory = LinkedInApiClientFactory.newInstance(CONSUMER_KEY, CONSUMER_SECRET);
LinkedInRequestToken liToken;
LinkedInApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new AutheticateLinkedIn().execute();
}
});
Log.d("Token", " Starting Task");
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if(liToken!=null)
{
Log.d("Token", "New Intent Recieved");
String verifier = getIntent().getData().getQueryParameter("oauth_verifier");
LinkedInAccessToken accessToken = oAuthService.getOAuthAccessToken(liToken, verifier);
client = factory.createLinkedInApiClient(accessToken);
Log.d("Token", "Posting update");
client.postNetworkUpdate("LinkedIn Android app test");
Log.d("Token", "Update Posted");
}
}
// #Override
// protected void onNewIntent(Intent intent) {
// // TODO Auto-generated method stub
// super.onNewIntent(intent);
//
// }
public class AutheticateLinkedIn extends AsyncTask<Void, Long, Boolean>
{
#Override
protected Boolean doInBackground(Void... params) {
// TODO Auto-generated method stub
Log.d("Token", " Requested");
liToken = oAuthService.getOAuthRequestToken(OAUTH_CALLBACK_URL);
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(liToken.getAuthorizationUrl()));
startActivity(i);
return true;
}
#Override
protected void onPostExecute(Boolean result){
Log.d("Token", " Recieved");
// mDialog.cancel();
}
}
}
Related
My code receives no crash errors. When I run the App and click the button, a Toast should show, but it doesn't.
Here is my IntentService
package com.example.flas;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.flas.JSONParser;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.util.Log;
import android.widget.Toast;
public class SampleIntentService extends IntentService {
public static final int DOWNLOAD_ERROR = 10;
public static final int DOWNLOAD_SUCCESS = 11;
String latbus;
String lonbus;
String latsta;
String Employernumber;
String lonsta;
String numrout;
String nomsta;
JSONParser jsonParser = new JSONParser();
private static final String url_product_detials = "http://********/get_loc_details2.php";
private static final String TAG_IDLOCBUS = "idlocbus";
private static final String TAG_BUSNUMBER = "BusNumber";
private static final String TAG_BUSLATITUDE = "BusLatitude";
private static final String TAG_BUSLONGITUDE = "Buslongitude";
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
public SampleIntentService() {
super(SampleIntentService.class.getName());
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
String url = intent.getStringExtra("url");
final ResultReceiver receiver = intent.getParcelableExtra("receiver");
Bundle bundle = new Bundle();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", url));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(
url_product_detials, "GET", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
int success = json.getInt(TAG_SUCCESS);
// successfully received product details
JSONArray productObj = json
.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// display product data in EditText
String aa = product.getString(TAG_IDLOCBUS);
String bb = product.getString(TAG_BUSNUMBER);
String latb = product.getString(TAG_BUSLATITUDE);
String lonb = product.getString(TAG_BUSLONGITUDE);
bundle.putString("filePath", lonb + latb);
receiver.send(DOWNLOAD_SUCCESS, bundle);
} catch (Exception e) {
// TODO: handle exception
receiver.send(DOWNLOAD_ERROR, Bundle.EMPTY);
e.printStackTrace();
}
}
}
My MainActivity that calls my IntentService
public class MainActivity extends Activity implements OnClickListener {
ProgressBar pd;
SampleResultReceiver resultReceiever;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resultReceiever = new SampleResultReceiver(new Handler());
pd = (ProgressBar) findViewById(R.id.downloadPD);
}
private class SampleResultReceiver extends ResultReceiver {
public SampleResultReceiver(Handler handler) {
super(handler);
// TODO Auto-generated constructor stub
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
// TODO Auto-generated method stub
switch (resultCode) {
case SampleIntentService.DOWNLOAD_ERROR: {
Toast.makeText(getApplicationContext(), "error in download", Toast.LENGTH_SHORT).show();
pd.setVisibility(View.INVISIBLE);
}
break;
case SampleIntentService.DOWNLOAD_SUCCESS: {
String filePath = resultData.getString("filePath");
Toast.makeText(getApplicationContext(), "image download via IntentService is done", Toast.LENGTH_SHORT).show();
pd.setIndeterminate(false);
pd.setVisibility(View.INVISIBLE);
}
break;
}
super.onReceiveResult(resultCode, resultData);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent startIntent = new Intent(MainActivity.this, SampleIntentService.class);
startIntent.putExtra("receiver", resultReceiever);
String aaa = "5";
startIntent.putExtra("url", aaa);
startService(startIntent);
pd.setVisibility(View.VISIBLE);
pd.setIndeterminate(true);
}
public void onClick2(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "image download via IntentService is done", Toast.LENGTH_SHORT).show();
}
}
My JSON Class works fine, I tried it in another App and I got not error.
In my AndroidManifest.xml ...
I tried this:
<service android:name="com.example.pfecuspart.SampleIntentService"
android:exported="false">
<intent-filter>
<action android:name="org.example.android.myservicedemo.IService" />
</intent-filter>
</service>
I also tried this:
<service android:name="com.example.pfecuspart.SampleIntentService"
android:enabled="true">
</service>
I dont think onClick2 is doing anything, its not overriding the onClick.
do you need to move;
Toast.makeText(getApplicationContext(),
"image download via IntentService is done",
Toast.LENGTH_SHORT).show();
from onClick2, to onClick.
Maybe try replacing getApplicationContext() with MainActivity.this
I have a problem with my Android app when I try to login with Twitter. When I login and Twitter has given permission to my account to access, it shows the next message:
"Wait a moment!
The request form's token for this page isnt being valid. Is possible that it had was used or be expired because is a few old. Please, back to the site or aplicattion which sent to here an try again, probably it only was an error."
This is my code:
AlertManager:
package com.fsvp.manocio;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
public class AlertManager {
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(title);
builder.setMessage(message);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
Connection Manager:
package com.fsvp.manocio;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ConnectionManager {
private Context _context;
public ConnectionManager(Context context){
this._context = context;
}
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
}
Activity Main:
package com.fsvp.manocio;
import com.fsvp.manocio.AlertManager;
import com.fsvp.manocio.ConnectionManager;
import com.fsvp.manocio.MainActivity;
import com.fsvp.manocio.R;
import android.support.v7.app.ActionBarActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
public static final String TAG = MainActivity.class.getSimpleName();
static String TWITTER_CONSUMER_KEY = "****";
static String TWITTER_CONSUMER_SECRET = "*****";
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_ACCESS_TOKEN = "*****";
static final String PREF_KEY_ACCESS_SECRET = "*****";
static final String PREF_KEY_USER_NAME = "user_name";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
static final String TWITTER_CALLBACK_URL = "https://api.twitter.com/oauth/authenticate?oauth_token=*****";
static final String URL_TWITTER_AUTH = "https://api.twitter.com/oauth/authorize";
static final String URL_TWITTER_OAUTH_VERIFIER = "https://api.twitter.com/oauth/access_token";
static final String URL_TWITTER_OAUTH_TOKEN = "https://api.twitter.com/oauth/request_token";
Button loginTwitter;
Button logoutTwitter;
TextView userName;
ImageView twitterLogo;
ProgressDialog pDialog;
private static Twitter twitter;
private static RequestToken requestToken;
private static SharedPreferences mSharedPreferences;
private ConnectionManager cm;
AlertManager alert = new AlertManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
cm = new ConnectionManager(getApplicationContext());
if (!cm.isConnectingToInternet()) {
alert.showAlertDialog(MainActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
return;
}
if(TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0){
alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens", "Please set your twitter oauth tokens first!", false);
return;
}
loginTwitter = (Button) findViewById(R.id.loginTwitter);
twitterLogo = (ImageView) findViewById(R.id.twitterLogo);
logoutTwitter = (Button) findViewById(R.id.logoutTwitter);
userName = (TextView) findViewById(R.id.userName);
mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
loginTwitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
new TwitterLogin().execute();
}
});
logoutTwitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
logoutFromTwitter();
}
});
if (!isTwitterLoggedInAlready()) {
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
new TwitterAccessToken().execute(verifier);
}
}else {
String userName = mSharedPreferences.getString(PREF_KEY_USER_NAME, "");
enableTwitterStatus(userName);
}
}
private class TwitterLogin extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// 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);
MainActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (isTwitterLoggedInAlready()) {
Toast.makeText(MainActivity.this, "Already Logged into Twitter", Toast.LENGTH_LONG).show();
}
}
}
private class TwitterAccessToken extends AsyncTask<String, Void, User> {
#Override
protected User doInBackground(String... params) {
String verifier = params[0];
AccessToken accessToken = null;
User user = null;
try {
accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
Editor e = mSharedPreferences.edit();
e.putString(PREF_KEY_ACCESS_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_ACCESS_SECRET, accessToken.getTokenSecret());
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
Log.d(TAG, "Twitter OAuth Token: " + accessToken.getToken());
long userID = accessToken.getUserId();
user = twitter.showUser(userID);
e.putString(PREF_KEY_USER_NAME, user.getName());
e.commit();
} catch (TwitterException e) {
Log.e(TAG, "Twitter Login Error: " + e.getMessage());
e.printStackTrace();
}
return user;
}
#Override
protected void onPostExecute(User user) {
super.onPostExecute(user);
if (user != null) {
enableTwitterStatus(user.getName());
}
}
}
private void enableTwitterStatus(String user) {
// Hide login button
loginTwitter.setVisibility(View.GONE);
logoutTwitter.setVisibility(View.VISIBLE);
twitterLogo.setVisibility(View.GONE);
userName.setText(Html.fromHtml("<b>Welcome " + userName + "</b>"));
userName.setVisibility(View.GONE);
}
private void logoutFromTwitter() {
// Clear the shared preferences
Editor e = mSharedPreferences.edit();
e.remove(PREF_KEY_ACCESS_TOKEN);
e.remove(PREF_KEY_ACCESS_SECRET);
e.remove(PREF_KEY_TWITTER_LOGIN);
e.commit();
logoutTwitter.setVisibility(View.GONE);
userName.setText("");
userName.setVisibility(View.GONE);
loginTwitter.setVisibility(View.VISIBLE);
twitterLogo.setVisibility(View.VISIBLE);
}
private boolean isTwitterLoggedInAlready() {
// return twitter login status from Shared Preferences
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
}
Finally, this is my manifest:
Anyone knows a solution?
Thanks and cheers!
code for registering using asynctask :
import java.io.IOException;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.gcm.GoogleCloudMessaging;
public class RegisterApp extends AsyncTask<Void, Void, String> {
private static final String TAG = "GCMRelated";
Context ctx;
GoogleCloudMessaging gcm;
String SENDER_ID = "10413";
String regid = null;
private int appVersion;
public RegisterApp(Context ctx, GoogleCloudMessaging gcm, int appVersion){
this.ctx = ctx;
this.gcm = gcm;
this.appVersion = appVersion;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
String msg = "";
try{
if (gcm == null){
gcm = GoogleCloudMessaging.getInstance(ctx);
}
regid = gcm.register(SENDER_ID);
msg = "Device registered, registration ID=" + regid;
Log.i(TAG,msg);
} catch (IOException e){
msg = "Error: " + e.getMessage();
}
return msg;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(ctx,
"Registration Completed. Now you can see the notifications",
Toast.LENGTH_SHORT)
.show();
Log.v(TAG, result);
}
}
Here toast is working in onPostExecute() but Log is not working anywhere.what i am trying to show is result and msg in Logcat.
More to know is where can i define log to place in information in Logcat? Do I have to do it in main UI thread or it can be done from anywhere in android system?
Here is Logcat:
I am trying to call the function "loadUrl" from a service but not achieving it work
The service is:
MyService.java
package com.yournamespace.yourappname;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import com.exam.probando.PROBANDO;
import com.red_folder.phonegap.plugin.backgroundservice.BackgroundService;
public class MyService extends BackgroundService {
private final static String TAG = MyService.class.getSimpleName();
private String mHelloTo = "World";
#Override
protected JSONObject doWork() {
JSONObject result = new JSONObject();
try {
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String now = df.format(new Date(System.currentTimeMillis()));
String msg = "Hello " + this.mHelloTo + " - its currently " + now;
result.put("Message", msg);
//HERE CALL LoadUrl
Log.d(TAG, msg);
} catch (JSONException e) {
}
return result;
}
#Override
protected JSONObject getConfig() {
JSONObject result = new JSONObject();
try {
result.put("HelloTo", this.mHelloTo);
} catch (JSONException e) {
}
return result;
}
#Override
protected void setConfig(JSONObject config) {
try {
if (config.has("HelloTo"))
this.mHelloTo = config.getString("HelloTo");
} catch (JSONException e) {
}
}
#Override
protected JSONObject initialiseLatestResult() {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onTimerEnabled() {
// TODO Auto-generated method stub
}
#Override
protected void onTimerDisabled() {
// TODO Auto-generated method stub
}
}
I try in MainActivity (PROBANDO) this:
package com.exam.probando;
import android.os.Bundle;
import org.apache.cordova.*;
public class PROBANDO extends CordovaActivity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.init();
// Set by <content src="index.html" /> in config.xml
super.loadUrl(Config.getStartUrl());
//super.loadUrl("file:///android_asset/www/index.html");
}
public void mainLoadUrl() {
String url = "file:///android_asset/www/index2.html";
super.loadUrl(url);
}
}
But don't know how make a call for this..
The plugin is: https://github.com/Red-Folder/Cordova-Plugin-BackgroundService/tree/master/3.1.0
Regards!
PS: Sorry for my bad english..
You need to launch the activity via intent
Intent intent = new Intent(this, PROBANDO.class);
startActivity(intent);
The activity needs to be in your manifest file, as well as the service
I'm trying to make a Twitter app which includes posting and retrieving tweets from the user's timeline and setting it in a list view which also updates when someone tweets.
I also wish to allow the user to upload photos to Twitter.
Here's my code:
package com.example.listtweetdemo;
import java.util.ArrayList;
import java.util.List;
import twitter4j.Paging;
import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import twitter4j.internal.org.json.JSONArray;
import twitter4j.internal.org.json.JSONObject;
import twitter4j.json.DataObjectFactory;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
private Button twitt;
private Button read;
private Button login;
private Button logout;
private EditText edt;
private boolean man = true;
private TextView textName;
private ListView list;
List<Status> statuses = new ArrayList<Status>();
static final String consumerKey = "RVVVPnAUa8e1XXXXXXXXX";
static final String consumerSecretKey = "eCh0Bb12n9oDmcomBdfisKZIfJmChC2XXXXXXXXXXXX";
static final String prefName = "twitter_oauth";
static final String prefKeyOauthToken = "oauth_token";
static final String prefKeyOauthSecret = "oauth_token_secret";
static final String prefKeyTwitterLogin = "isTwitterLogedIn";
static final String twitterCallbackUrl = "oauth://t4jsample";
static final String urlTwitterOauth = "auth_url";
static final String urlTwitterVerify = "oauth_verifier";
static final String urlTwitterToken = "oauth_token";
static SharedPreferences pref;
private static Twitter twitter;
private static RequestToken reqToken;
private connectionDetector cd;
AlertDailogManager alert = new AlertDailogManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpIds();
cd = new connectionDetector(getApplicationContext());
if(!cd.isConnectivityToInternet())
{
alert.showAlert(MainActivity.this, "Internet Connection Error", "Please Connect to working Internet connection", false);
return;
}
if(consumerKey.trim().length() == 0 || consumerSecretKey.trim().length() == 0)
{
alert.showAlert(MainActivity.this, "Twitter Oauth Token", "Please set your Twitter oauth token first!", false);
return;
}
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
loginToTwitter();
}
});
logout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
logoutFromTwitter();
}
});
read.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Paging paging = new Paging(200); // MAX 200 IN ONE CALL. SET YOUR OWN NUMBER <= 200
try {
statuses = twitter.getHomeTimeline();
} catch (TwitterException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
String strInitialDataSet = DataObjectFactory.getRawJSON(statuses);
JSONArray JATweets = new JSONArray(strInitialDataSet);
for (int i = 0; i < JATweets.length(); i++) {
JSONObject JOTweets = JATweets.getJSONObject(i);
Log.e("TWEETS", JOTweets.toString());
}
} catch (Exception e) {
// TODO: handle exception
}
/*try {
ResponseList<Status> statii = twitter.getHomeTimeline();
statusListAdapter adapter = new statusListAdapter(getApplicationContext(), statii);
setListAdapter(adapter);
Log.d("HOME TIMELINE", statii.toString());
} catch (TwitterException e) {
e.printStackTrace();
}
//list.setVisibility(View.VISIBLE);
read.setVisibility(View.GONE);*/
}
});
twitt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String status = edt.getText().toString();
if(status.trim().length() > 0)
{
new updateTwitter().execute(status);
}
}
});
if(!isTwitterLogedInAlready())
{
Uri uri = getIntent().getData();
if(uri != null && uri.toString().startsWith(twitterCallbackUrl))
{
String verify = uri.getQueryParameter(urlTwitterVerify);
try
{
AccessToken accessToken = twitter.getOAuthAccessToken(reqToken,verify);
Editor edit = pref.edit();
edit.putString(prefKeyOauthToken, accessToken.getToken());
edit.putString(prefKeyOauthSecret, accessToken.getTokenSecret());
edit.putBoolean(prefKeyTwitterLogin, true);
edit.commit();
Log.d("Twitter oauth Token", ">" + accessToken.getToken());
login.setVisibility(View.INVISIBLE);
twitt.setVisibility(View.VISIBLE);
edt.setVisibility(View.VISIBLE);
read.setVisibility(View.VISIBLE);
textName.setVisibility(View.VISIBLE);
if(man == true)
{
logout.setVisibility(View.VISIBLE);
}
long userId = accessToken.getUserId();
User user = twitter.showUser(userId);
//User user = twitter.getHomeTimeline();
Status n = user.getStatus();
String userName = user.getName();
textName.setText(userName);
}
catch(Exception e)
{
Log.d("Twitter Login Error", ">" + e.getMessage());
}
}
}
}
private void setUpIds() {
twitt = (Button)findViewById(R.id.buttTwitt);
login = (Button)findViewById(R.id.buttLogin);
read = (Button)findViewById(R.id.buttRead);
edt = (EditText)findViewById(R.id.editText1);
logout = (Button)findViewById(R.id.buttLogout);
textName = (TextView)findViewById(R.id.textName);
//list = (ListView)findViewById(R.id.listView1);
pref = getApplicationContext().getSharedPreferences("myPref", 0);
}
protected void logoutFromTwitter() {
Editor e = pref.edit();
e.remove(prefKeyOauthSecret);
e.remove(prefKeyOauthToken);
e.remove(prefKeyTwitterLogin);
e.commit();
login.setVisibility(View.VISIBLE);
logout.setVisibility(View.GONE);
twitt.setVisibility(View.GONE);
edt.setVisibility(View.GONE);
read.setVisibility(View.GONE);
textName.setVisibility(View.GONE);
}
protected void loginToTwitter() {
if(!isTwitterLogedInAlready())
{
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecretKey);
builder.setJSONStoreEnabled(true);
builder.setIncludeEntitiesEnabled(true);
builder.setIncludeMyRetweetEnabled(true);
builder.setIncludeRTsEnabled(true);
Configuration config = builder.build();
TwitterFactory factory = new TwitterFactory(config);
twitter = factory.getInstance();
try{
reqToken = twitter.getOAuthRequestToken(twitterCallbackUrl);
this.startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse(reqToken.getAuthenticationURL())));
}
catch(TwitterException e)
{
e.printStackTrace();
}
}
else
{
Toast.makeText(getApplicationContext(), "Already Logged In", Toast.LENGTH_LONG).show();
logout.setVisibility(View.VISIBLE);
man = false;
}
}
private boolean isTwitterLogedInAlready() {
return pref.getBoolean(prefKeyTwitterLogin, false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class updateTwitter extends AsyncTask<String , String, String>{
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Updating to Twitter status..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
Log.d("Tweet Text", "> " + args[0]);
String status = args[0];
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecretKey);
// Access Token
String access_token = pref.getString(prefKeyOauthToken, "");
// Access Token Secret
String access_token_secret = pref.getString(prefKeyOauthSecret, "");
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;
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Status update successfully", Toast.LENGTH_SHORT).show();
edt.setText("");
}
});
}
}
}
Use the new Twitter Fabric SDK for Android. Requires sign up first. If you don't want to wait to be approved for the sign up, then I recommend using the following link
https://github.com/Rockncoder/TwitterTutorial
The link above explains how to retrieve tweets. You should be able to use the above link COMBINED with the information in the link below to POST tweets!
https://dev.twitter.com/overview/documentation