i have some trouble with the OAuth signing.
on the point i expect to get the retrieveRequestToken i got the following error:
01-05 17:26:02.775: W/System.err(24358): oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: null
i have no idea why i get this. Any suggestions here?
My Code:
connectionDec = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!connectionDec.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;
}
CommonsHttpOAuthConsumer consumer =
new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
CommonsHttpOAuthProvider provider =
new CommonsHttpOAuthProvider(REQUEST_TOKEN_URL, ACCESS_TOKEN_URL,
AUTHORIZE_URL);
provider.setOAuth10a(true);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String token = sharedPreferences.getString("token", null);
String tokenSecret = sharedPreferences.getString("token_secret", null);
if (token == null || tokenSecret == null)
{
Map requestHeaders = provider.getRequestHeaders();
requestHeaders.put("User-Agent", USER_AGENT);
requestHeaders.put("Accept-Encoding", "gzip");
try
{
String authUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
}
catch (OAuthMessageSignerException e)
{
e.printStackTrace();
}
catch (OAuthNotAuthorizedException e)
{
e.printStackTrace();
}
catch (OAuthExpectationFailedException e)
{
e.printStackTrace();
}
catch (OAuthCommunicationException e)
{
e.printStackTrace();
}
}
else
{
}
any tipps and helps ... thank you
PS: It is Discogs and not Twitter
Greets Mad
OK, i have answered the question myself ... i have implement a asynctask like the following and it works:
public class StartUpActivity extends Activity implements OnClickListener
{
private static String CONSUMER_KEY = "consumerkey";
private static String CONSUMER_SECRET = "yourconsumersecret";
private static String REQUEST_TOKEN_URL = "http://api.discogs.com/oauth/request_token";
private static String AUTHORIZE_URL = "http://www.discogs.com/oauth/authorize";
private static String ACCESS_TOKEN_URL = "http://api.discogs.com/oauth/access_token";
private static String USER_AGENT = "youruseragent";
private static String CALLBACK_URL = "http://www.callback.com";
private ConnectionDetector connectionDec;
private SharedPreferences sharedPreferences;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.start_up_layout);
connectionDec = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!connectionDec.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;
}
}
class ProgressTask extends AsyncTask<Integer, Integer, Void>{
#Override
protected void onPreExecute() {
// initialize the progress bar
// set maximum progress to 100.
}
#Override
protected void onCancelled() {
// stop the progress
}
#Override
protected Void doInBackground(Integer... params) {
// get the initial starting value
int start=params[0];
// increment the progress
try {
CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
CommonsHttpOAuthProvider provider =
new CommonsHttpOAuthProvider(REQUEST_TOKEN_URL, ACCESS_TOKEN_URL, AUTHORIZE_URL);
provider.setOAuth10a(true);
// Check if token and tokensecret are already stored at app preferences
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String token = sharedPreferences.getString("token", null);
String tokenSecret = sharedPreferences.getString("token_secret", null);
if (token == null || tokenSecret == null)
{
Map<String, String> requestHeaders = provider.getRequestHeaders();
requestHeaders.put("User-Agent", USER_AGENT);
requestHeaders.put("Accept-Encoding", "gzip");
try
{
String authUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
}
catch (OAuthMessageSignerException e)
{
e.printStackTrace();
}
catch (OAuthNotAuthorizedException e)
{
e.printStackTrace();
}
catch (OAuthExpectationFailedException e)
{
e.printStackTrace();
}
catch (OAuthCommunicationException e)
{
e.printStackTrace();
}
}
else
{
}
}
catch (Exception e) {
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
// increment progress bar by progress value
}
#Override
protected void onPostExecute(Void result) {
// async task finished
}
}
}
Related
I am integrating Paytm SDK in my Android Application. I have to POST ORDER ID and callbackurl along with other paytm credentials. All values are passing correctly. But OOPS error is displaying.
Code
public class Paytmgateway extends Activity {
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.merchantapp);
context = this;
// initOrderId();
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
// This is to refresh the order id: Only for the Sample App’s purpose.
#Override
protected void onStart() {
super.onStart();
// initOrderId();
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
public void onStartTransaction(View view) throws InterruptedException, ExecutionException {
String myorder = "ORDER7999883";
String mycallback= "https://securegw.paytm.in/theia/paytmCallback?ORDER_ID="+myorder;
PostAsync postAsync= new PostAsync();
postAsync.execute(myorder,mycallback);
}
class PostAsync extends AsyncTask<String, String, JSONObject> {
JSONParser jsonParser = new JSONParser();
private ProgressDialog pDialog;
private static final String LOGIN_URL = "http://192.168.1.4/paytmtest/generateChecksum.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
protected JSONObject doInBackground(String... args) {
try {
HashMap<String, String> para = new HashMap<>();
para.put("myorder", args[0]);
para.put("mycallback", args[1]);
Log.d("request", "starting");
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", para);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONObject json) {
PaytmPGService Service = PaytmPGService.getProductionService();
if (json != null) {
Toast.makeText(Paytmgateway.this,"Server Response"+json.toString(), Toast.LENGTH_LONG).show();
String finalresult=json.toString();
try {
JSONObject mJsonObject=new JSONObject(finalresult);
Map paramMap = new HashMap();
System.out.println("Hi");
paramMap.put("MID", mJsonObject.getString("MID"));
System.out.println(mJsonObject.getString("MID"));
// paramMap.put(“ORDER_ID”, order_id);
paramMap.put("ORDER_ID", mJsonObject.getString("ORDER_ID"));
System.out.println(mJsonObject.getString("ORDER_ID"));
// paramMap.put(“CUST_ID”, cust_id);
paramMap.put("CUST_ID",mJsonObject.getString("CUST_ID"));
System.out.println(mJsonObject.getString("CUST_ID"));
// paramMap.put(“INDUSTRY_TYPE_ID”,industry_type);
paramMap.put("INDUSTRY_TYPE_ID",mJsonObject.getString("INDUSTRY_TYPE_ID"));
System.out.println(mJsonObject.getString("INDUSTRY_TYPE_ID"));
// paramMap.put(“CHANNEL_ID”, “WAP”);
paramMap.put("CHANNEL_ID", mJsonObject.getString("CHANNEL_ID"));
System.out.println(mJsonObject.getString("CHANNEL_ID"));
// paramMap.put(“TXN_AMOUNT”,txn_amount);
paramMap.put("TXN_AMOUNT", "1");
System.out.println(mJsonObject.getString("TXN_AMOUNT"));
// paramMap.put(“WEBSITE”, “APP_STAGING”);
paramMap.put("WEBSITE" , mJsonObject.getString("WEBSITE"));
System.out.println(mJsonObject.getString("WEBSITE"));
// paramMap.put(“CALLBACK_URL”,callback);
paramMap.put("CALLBACK_URL" , mJsonObject.getString("CALLBACK_URL"));
System.out.println(mJsonObject.getString("CALLBACK_URL"));
// paramMap.put(“CHECKSUMHASH”,checksum);
paramMap.put("CHECKSUMHASH",mJsonObject.getString("CHECKSUMHASH"));
System.out.println("MYCHECK"+mJsonObject.getString("CHECKSUMHASH"));
PaytmOrder Order = new PaytmOrder(paramMap);
System.out.println("sumithra"+paramMap);
Service.initialize(Order, null);
Service.startPaymentTransaction(Paytmgateway.this, true, true,
new PaytmPaymentTransactionCallback() {
#Override
public void someUIErrorOccurred(String inErrorMessage) {
Toast.makeText(getApplicationContext(),"UI Error" , Toast.LENGTH_LONG).show();
}
#Override
public void onTransactionResponse(Bundle inResponse) {
// Log.d(“LOG”, “Payment Transaction : ” + inResponse);
Log.d("LOG", "Payment Transaction : "+inResponse);
Toast.makeText(getApplicationContext(),"Payment Transaction Response" + inResponse.toString(), Toast.LENGTH_LONG).show();
}
#Override
public void networkNotAvailable() {
Toast.makeText(getApplicationContext(),"No Network Available" , Toast.LENGTH_LONG).show();
}
#Override
public void clientAuthenticationFailed(String inErrorMessage) {
Toast.makeText(getApplicationContext(),"Client Authentication Failed" , Toast.LENGTH_LONG).show();
}
#Override
public void onErrorLoadingWebPage(int iniErrorCode,
String inErrorMessage, String inFailingUrl) {
Toast.makeText(getApplicationContext(),"Error Loading Webpage" , Toast.LENGTH_LONG).show();
}
// had to be added: NOTE
#Override
public void onBackPressedCancelTransaction() {
// TODO Auto-generated method stub
}
#Override
public void onTransactionCancel(String inErrorMessage,
Bundle inResponse) {
Log.d("LOG", "Payment Transaction Failed" + inErrorMessage);
Toast.makeText(getBaseContext(),"Payment Transaction Failed", Toast.LENGTH_LONG).show();
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
My Android Studio Monitor output of
System.out.println(paramMap);
is
05-22 15:43:33.801 15328-15328/com.example.merchantapp I/System.out: {MID=Bigfix12826731009600, CALLBACK_URL=https://securegw.paytm.in/theia/paytmCallback?ORDER_ID=ORDER7999883, TXN_AMOUNT=1.00, ORDER_ID=ORDER7999883, WEBSITE=BigfixGadgetWAP, INDUSTRY_TYPE_ID=Retail109, CHECKSUMHASH=HxSimAQAYRsDhJ7XX6JXT+cilxFNdSc4Pb3jr5AE5dddSavv6UD3DJffBHtcHVwQbBMYYHc850/OdZretSWIeo3m/uC0/FUA9wpO1Hgs/jY=, CHANNEL_ID=WAP, CUST_ID=25654}
Which means the two parameter values are posting successfully and i can be able to GET them also. But the following error is displaying
enter image description here
But if if i use the below code , It is working successfully
public class Paytm extends Activity {
String callback,website;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.merchantapp);
context = this;
// initOrderId();
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
// This is to refresh the order id: Only for the Sample App’s purpose.
#Override
protected void onStart() {
super.onStart();
// initOrderId();
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
public void onStartTransaction(View view) throws InterruptedException, ExecutionException {
PaytmPGService Service = PaytmPGService.getProductionService();
Map paramMap = new HashMap();
String mid="",order_id="",cust_id="",industry_type="",txn_amount="",checksum="";
Log.d("before request", "some");
JSONObject mJsonObject = null;
// String url="http://paytmtest.azurewebsites.net/APP/generateChecksum.php";
String url="http://192.168.1.4/paytmtest/generateChecksum.php";
MyAsyncTask myAsyncTask=new MyAsyncTask();
// String json = myAsyncTask.execute(url).get();
String json = (String) myAsyncTask.execute(url).get();
try {
mJsonObject=new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
try {
//mid = mJsonObject.getString("MID");
mid="Bigfix12826731009600";
// order_id=mJsonObject.getString(“ORDER_ID”);
order_id=mJsonObject.getString("ORDER_ID");
// cust_id = mJsonObject.getString(“CUST_ID”);
cust_id=mJsonObject.getString("CUST_ID");
//callback = mJsonObject.getString("CALLBACK_URL");
callback= "https://securegw.paytm.in/theia/paytmCallback?ORDER_ID="+order_id;
//website = mJsonObject.getString("WEBSITE");
website="BigfixGadgetWAP";
//industry_type = mJsonObject.getString("INDUSTRY_TYPE_ID");
industry_type="Retail109";
txn_amount = mJsonObject .getString("TXN_AMOUNT");
// checksum = mJsonObject.getString(“CHECKSUMHASH”);
checksum = mJsonObject.getString("CHECKSUMHASH");
} catch (JSONException e) {
e.printStackTrace();
}
// Log.d(“after request”, “some”);
Log.d("after request", "some");
// paramMap.put(“MID”, mid);
paramMap.put("MID", mid);
// paramMap.put(“ORDER_ID”, order_id);
paramMap.put("ORDER_ID", order_id);
// paramMap.put(“CUST_ID”, cust_id);
paramMap.put("CUST_ID",cust_id);
// paramMap.put(“INDUSTRY_TYPE_ID”,industry_type);
paramMap.put("INDUSTRY_TYPE_ID",industry_type);
// paramMap.put(“CHANNEL_ID”, “WAP”);
paramMap.put("CHANNEL_ID", "WAP");
// paramMap.put(“TXN_AMOUNT”,txn_amount);
paramMap.put("TXN_AMOUNT", txn_amount);
// paramMap.put(“WEBSITE”, “APP_STAGING”);
paramMap.put("WEBSITE" , website);
// paramMap.put(“CALLBACK_URL”,callback);
paramMap.put("CALLBACK_URL" , callback);
// paramMap.put(“CHECKSUMHASH”,checksum);
paramMap.put("CHECKSUMHASH",checksum);
System.out.println("sumithra"+paramMap);
PaytmOrder Order = new PaytmOrder(paramMap);
Service.initialize(Order, null);
Service.startPaymentTransaction(this, true, true,
new PaytmPaymentTransactionCallback() {
#Override
public void someUIErrorOccurred(String inErrorMessage) {
}
#Override
public void onTransactionResponse(Bundle inResponse) {
// Log.d(“LOG”, “Payment Transaction : ” + inResponse);
Log.d("LOG", "Payment Transaction : "+inResponse);
Toast.makeText(getApplicationContext(),"Payment Transaction Response" + inResponse.toString(), Toast.LENGTH_LONG).show();
}
#Override
public void networkNotAvailable() {
}
#Override
public void clientAuthenticationFailed(String inErrorMessage) {
}
#Override
public void onErrorLoadingWebPage(int iniErrorCode,
String inErrorMessage, String inFailingUrl) {
}
// had to be added: NOTE
#Override
public void onBackPressedCancelTransaction() {
// TODO Auto-generated method stub
}
#Override
public void onTransactionCancel(String inErrorMessage,
Bundle inResponse) {
Log.d("LOG", "Payment Transaction Failed" + inErrorMessage);
Toast.makeText(getBaseContext(),"Payment Transaction Failed", Toast.LENGTH_LONG).show();
}
});
}
class MyAsyncTask extends AsyncTask {
#Override
protected String doInBackground(Object[] params) {
URL url = null;
try {
url = new URL((String) params[0]);
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection httpConn = null;
try {
httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream is = httpConn.getInputStream();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
} catch (Exception e) {
}
Log.d("Response", result);
}
}
}
[enter image description here][2]
I just used the second code to test the trasaction. But i have to use the first posted code because i have to post the ORDERID and CALLBACKURL from android application to server . Any help would be appreciable.
**Here is the solution for all :**
Be sure to send equal number of parameters to your server (For checksum generator) And then to paytm server for payment.
**For example:**
If you are sending 6 params for checksum generator, then send these 6 same parameters including Checksum to Paytm...
It will resolve your problem.
**CODE EXAMPLE :**
**Generate checksum.php**
$paramList = array();
$paramList["MID"] = 'Provided by Paytm'; //Provided by Paytm
$paramList["ORDER_ID"] = 'hIquwhzvzTG7gvT'; //unique OrderId for every request
$paramList["CUST_ID"] = 'CUST0001453'; // unique customer identifier
$paramList["INDUSTRY_TYPE_ID"] = 'Retail'; //Provided by Paytm
$paramList["CHANNEL_ID"] = 'WAP'; //Provided by Paytm
$paramList["TXN_AMOUNT"] = '10.00'; // transaction amount
$paramList["WEBSITE"] = 'APP_STAGING';//Provided by Paytm
$paramList["CALLBACK_URL"] = 'https://pguat.paytm.com/paytmchecksum/paytmCallback.jsp';
**Android Activity.java**
paramMap.put("MID" , "#########");
paramMap.put( "ORDER_ID" , "hIquwhzvzTG7gvT");
paramMap.put( "CUST_ID" , "CUST0001453");
paramMap.put( "CHANNEL_ID" , "WAP");
paramMap.put( "TXN_AMOUNT" , "10.00");
paramMap.put( "WEBSITE" , "APP_STAGING");
paramMap.put( "CALLBACK_URL" , "https://pguat.paytm.com/paytmchecksum/paytmCallback.jsp");
paramMap.put( "CHECKSUMHASH" , "dR5OtEkuNkgamHTZDCHmF+CF3j9RdG1520mlHEb85oSZP1CaxVUsRY2sYric90HLm/vElaPZKoQ7b5/SyFpi3oBWXf2BQNy+r6iiBwg4AH4=");
paramMap.put("INDUSTRY_TYPE_ID" , "Retail");
**NOTE : Please keep in mind to send paytm server exact parameters plus one checksum.....**
Requesting access to token for second time doesn't work thats why we need to store the token for first time to use it in future reference.Thats what i am trying to do here in Twitter integration using SharedPreference while posting tweet.It works fine for the first time while posting tweet but shows popup in second time showing "You don't have access to appname.Please return to appname to continue signup process".
private class TokenGet extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... args) {
try {
if(requestTokenFirstTime) {
requestToken = twitter.getOAuthRequestToken();
oauth_url = requestToken.getAuthorizationURL();
// requestTokenFirstTime = false;
// }
SharedPreferences.Editor edit = pref.edit();
edit.putString("Request_TOKEN", requestToken.getToken());
edit.putString("Request_TOKEN_SECRET", requestToken.getTokenSecret());
edit.putString("OAUTH_URLT", oauth_url);
edit.commit();
requestTokenFirstTime = false;
}
else {
requestToken = new RequestToken(pref.getString("Request_TOKEN", ""), pref.getString("Request_TOKEN_SECRET", ""));
oauth_url = pref.getString("OAUTH_URLT", "null");
}
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return oauth_url;
}
Below is my complete code for TwitterFragment.java
TwitterFragment.java
public class TwitterFragment extends ListFragment {
final static String ScreenName = "IBL_Official";
final static String LOG_TAG = "rnc";
private FragmentActivity myContext;
private ListFragment activity;
private ListView listView;
public static EditText tx1;
private ProgressBar mDialog;
private QuickReturnFrameLayout searchLayout;
Button login;
boolean requestTokenFirstTime = true;
twitter4j.Twitter twitter;
RequestToken requestToken = null;
//static RequestToken requestToken ;
twitter4j.auth.AccessToken accessToken;
String oauth_url,oauth_verifier,profile_url;
Dialog auth_dialog;
WebView web;
SharedPreferences pref;
ProgressDialog progress;
Bitmap bitmap;
#Override
public void onAttach(Activity activity) {
if (activity instanceof FragmentActivity) {
myContext = (FragmentActivity) activity;
}
super.onAttach(activity);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.activity = this;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
downloadTweets();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.twit_list, container, false);
listView = (ListView) rootView.findViewById(android.R.id.list);
tx1=(EditText)rootView.findViewById(R.id.postcomment);
mDialog = (ProgressBar) rootView.findViewById(R.id.progress_bar);
searchLayout = (QuickReturnFrameLayout) rootView.findViewById(R.id.search_layout);
listView.setVerticalScrollBarEnabled(false);
((QuickReturnFrameLayout) rootView.findViewById(R.id.search_layout)).attach(listView);
rootView.setVerticalScrollBarEnabled(false);
login = (Button)rootView.findViewById(R.id.postbutton);
pref = getActivity().getPreferences(0);
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(pref.getString("CONSUMER_KEY", ""), pref.getString("CONSUMER_SECRET", ""));
login.setOnClickListener(new LoginProcess());
return rootView;
}
public void downloadTweets() {
ConnectivityManager connMgr = (ConnectivityManager) myContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new DownloadTwitterTask().execute(ScreenName);
} else {
Log.v(LOG_TAG, "No network connection available.");
}
}
public class DownloadTwitterTask extends AsyncTask<String, Void, String> {
final static String CONSUMER_KEY = "AuSSA6AHeCv9gskRhGQjSymCO";
final static String CONSUMER_SECRET = "eyRoYBONVh45V185TBYbbb3i9BpWmmaiv4wLbBYXd7UcZGGaDw";
final static String TwitterTokenURL = "https://api.twitter.com/oauth2/token";
final static String TwitterStreamURL = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=";
#Override
public String doInBackground(String... screenNames) {
String result = null;
if (screenNames.length > 0) {
result = getTwitterStream(screenNames[0]);
}
return result;
}
#Override
public void onPreExecute() {
}
#Override
public void onPostExecute(String result) {
mDialog.setVisibility(View.GONE);
searchLayout.setVisibility(View.VISIBLE);
listView.setVisibility(View.VISIBLE);
Twitte twits = jsonToTwitter(result);
System.out.println(result);
ArrayList<String> data = new ArrayList<String>();
ArrayList<String> link = new ArrayList<String>();
ArrayList<String> time = new ArrayList<String>();
String logoimage = "";
String name = "";
String officialname = "";
for (Tweet tweet : twits) {
String[] splitted = tweet.getText().split("http://");
Log.d("splitted", String.valueOf(splitted.length));
data.add(splitted[0]);
if (splitted.length > 1) {
link.add("http://" + splitted[1]);
} else {
link.add("");
}
logoimage = tweet.getUser().getProfileImageUrl();
name = tweet.getUser().getName();
officialname = "# " + tweet.getUser().getScreenName();
time.add(tweet.getDateCreated());
}
//
Bitmap image = null;
try {
URL url = new URL(logoimage);
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
image = getRoundedShape(image);
} catch (Exception e) {
Log.d("error in image", e.toString());
Log.d("image", logoimage);
}
try {
TwitterAdapter adapter = new TwitterAdapter(getActivity(), data, link, image, time, name, officialname);
listView.setAdapter(adapter);
} catch (Exception e) {
System.out.println("error");
}
}
public Twitte jsonToTwitter(String result) {
Twitte twits = null;
if (result != null && result.length() > 0) {
try {
Gson gson = new Gson();
twits = gson.fromJson(result, Twitte.class);
} catch (IllegalStateException ex) {
}
}
return twits;
}
public Authenticated jsonToAuthenticated(String rawAuthorization) {
Authenticated auth = null;
if (rawAuthorization != null && rawAuthorization.length() > 0) {
try {
Gson gson = new Gson();
auth = gson.fromJson(rawAuthorization, Authenticated.class);
} catch (IllegalStateException ex) {
}
}
return auth;
}
public String getResponseBody(HttpRequestBase request) {
StringBuilder sb = new StringBuilder();
try {
DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
HttpResponse response = httpClient.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
String reason = response.getStatusLine().getReasonPhrase();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
String line = null;
while ((line = bReader.readLine()) != null) {
sb.append(line);
}
inputStream.close();
} else {
sb.append(reason);
}
} catch (UnsupportedEncodingException ex) {
} catch (ClientProtocolException ex1) {
} catch (IOException ex2) {
}
return sb.toString();
}
public String getTwitterStream(String screenName) {
String results = null;
try {
String urlApiKey = URLEncoder.encode(CONSUMER_KEY, "UTF-8");
String urlApiSecret = URLEncoder.encode(CONSUMER_SECRET, "UTF-8");
String combined = urlApiKey + ":" + urlApiSecret;
String base64Encoded = Base64.encodeToString(combined.getBytes(), Base64.NO_WRAP);
HttpPost httpPost = new HttpPost(TwitterTokenURL);
httpPost.setHeader("Authorization", "Basic " + base64Encoded);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
httpPost.setEntity(new StringEntity("grant_type=client_credentials"));
String rawAuthorization = getResponseBody(httpPost);
Authenticated auth = jsonToAuthenticated(rawAuthorization);
if (auth != null && auth.token_type.equals("bearer")) {
HttpGet httpGet = new HttpGet(TwitterStreamURL + screenName);
httpGet.setHeader("Authorization", "Bearer " + auth.access_token);
httpGet.setHeader("Content-Type", "application/json");
results = getResponseBody(httpGet);
}
} catch (UnsupportedEncodingException ex) {
} catch (IllegalStateException ex1) {
}
return results;
}
public Bitmap getRoundedShape(Bitmap scaleBitmapImage) {
int targetWidth = 50;
int targetHeight = 50;
Bitmap targetBitmap = Bitmap.createBitmap(targetWidth,
targetHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(targetBitmap);
Path path = new Path();
path.addCircle(((float) targetWidth - 1) / 2,
((float) targetHeight - 1) / 2,
(Math.min(((float) targetWidth),
((float) targetHeight)) / 2),
Path.Direction.CCW
);
canvas.clipPath(path);
Bitmap sourceBitmap = scaleBitmapImage;
canvas.drawBitmap(sourceBitmap,
new Rect(0, 0, sourceBitmap.getWidth(),
sourceBitmap.getHeight()),
new Rect(0, 0, targetWidth, targetHeight), null
);
return targetBitmap;
}
}
private class LoginProcess implements OnClickListener {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new TokenGet().execute();
}}
private class TokenGet extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... args) {
try {
if(requestTokenFirstTime) {
requestToken = twitter.getOAuthRequestToken();
oauth_url = requestToken.getAuthorizationURL();
// requestTokenFirstTime = false;
// }
SharedPreferences.Editor edit = pref.edit();
edit.putString("Request_TOKEN", requestToken.getToken());
edit.putString("Request_TOKEN_SECRET", requestToken.getTokenSecret());
edit.putString("OAUTH_URLT", oauth_url);
edit.commit();
requestTokenFirstTime = false;
}
else {
requestToken = new RequestToken(pref.getString("Request_TOKEN", ""), pref.getString("Request_TOKEN_SECRET", ""));
oauth_url = pref.getString("OAUTH_URLT", "null");
}
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return oauth_url;
}
#Override
protected void onPostExecute(String oauth_url) {
if(oauth_url != null){
Log.e("URL", oauth_url);
auth_dialog = new Dialog(getActivity());
auth_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
auth_dialog.setContentView(R.layout.auth_dialog);
web = (WebView)auth_dialog.findViewById(R.id.webv);
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl(oauth_url);
web.setWebViewClient(new WebViewClient() {
boolean authComplete = false;
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon){
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (url.contains("oauth_verifier") && authComplete == false){
authComplete = true;
Log.e("Url",url);
Uri uri = Uri.parse(url);
oauth_verifier = uri.getQueryParameter("oauth_verifier");
auth_dialog.dismiss();
new AccessTokenGet().execute();
}else if(url.contains("denied")){
auth_dialog.dismiss();
Toast.makeText(getActivity(), "Sorry !, Permission Denied", Toast.LENGTH_SHORT).show();
}
}
});
auth_dialog.show();
auth_dialog.setCancelable(true);
}else{
Toast.makeText(getActivity(), "Sorry !, Network Error or Invalid Credentials", Toast.LENGTH_SHORT).show();
}
}
}
private class AccessTokenGet extends AsyncTask<String, String, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progress = new ProgressDialog(getActivity());
progress.setMessage("Fetching Data ...");
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setIndeterminate(true);
progress.show();
}
#Override
protected Boolean doInBackground(String... args) {
try {
accessToken = twitter.getOAuthAccessToken(requestToken, oauth_verifier);
SharedPreferences.Editor edit = pref.edit();
edit.putString("ACCESS_TOKEN", accessToken.getToken());
edit.putString("ACCESS_TOKEN_SECRET", accessToken.getTokenSecret());
User user = twitter.showUser(accessToken.getUserId());
profile_url = user.getOriginalProfileImageURL();
edit.putString("NAME", user.getName());
edit.putString("IMAGE_URL", user.getOriginalProfileImageURL());
edit.commit();
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
#Override
protected void onPostExecute(Boolean response) {
if(response){
progress.hide();
// progress.dismiss();
Fragment profile = new ProfileFragment();
FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
ft.replace(R.id.frame_container, profile);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
}
else{
auth_dialog.dismiss();
}
}
}
}
I think you may simply want to hang on to the oauth access token after the first attempt (or ask for it by calling twitter.getOAuthAccessToken() ) and reuse it for the second time.
I ran into a similar experience and I found that the twitter4j.Twitter twitter; instance already had an access token associated with this instance from my first attempt. So when I asked for the authentication url from the request token ( oauth_url = requestToken.getAuthorizationURL(); ) and opened it in a webpage I got a message similar to your problem description ( "You don't have access to Please return to to continue the signup process." ).
I think if you wanted to you could also start over by recreating the twitter4j.Twitter instance and the related instance variables (like the RequestToken ). However this would also require you to then do the whole authentication process again with would be repeating the same work you did on the first attempt.
I have an Async task class which gets the name of a web method and run it and I have to wait for the result of that web method, so I used task.execute.get() method which is freezing my UI. the problem is that I want to show a loading dialog when task is executing but when I'm trying to call this method 10 times for 10 web methods, the UI freezes and after executing 10 web methods, loading dialog appears for 1 second.
What can I do to show loading without moving all of my codes into doInBackground? I want to have a class which gets web method info and returns the result. this is my class code:
public class AsyncCallWs extends AsyncTask<String, Void, String> {
private ProgressDialog dialog;
public String methodName="";
private WebService ws;
private ArrayList<ServiceParam> paramsList;
private boolean hasParams;
public AsyncCallWs(Activity activity,String methodName) {
xLog.position();
try {
this.dialog = new ProgressDialog(activity);
this.methodName = methodName;
hasParams = false;
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
public AsyncCallWs(Activity activity,String methodName,ArrayList<ServiceParam> params) {
xLog.position();
try {
this.dialog = new ProgressDialog(activity);
this.methodName = methodName;
this.paramsList = params;
hasParams = true;
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
#Override
protected void onPreExecute() {
this.dialog.setMessage(PersianReshape.reshape("Loading..."));
this.dialog.show();
}
#Override
protected String doInBackground(String... params) {
xLog.position();
String result = "No async task result!";
try {
ws = new WebService(PublicVariable.NAMESPACE, PublicVariable.URL);
if (!hasParams){
result = ws.CallMethod(methodName);
}
else{
xLog.info("THIS METHOD IS: "+ methodName);
result = ws.CallMethod(methodName,paramsList);
xLog.info("THIS RESULT IS: "+ result);
}
} catch (Exception e) {
xLog.error(e.getMessage());
}
return result;
}
#Override
protected void onPostExecute(String result) {
xLog.position();
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
xLog.info("Output of current AsyncTask is:"+ result);
}
}
And this is the way I'm calling web methods using this class:
public void doSync(String method){
xLog.position();
AsyncCallWs t;
ArrayList<ServiceParam> serviceParams = new ArrayList<ServiceParam>();
String result="";
Settings settings = new Settings(activity);
PublicVariable.pGuid = Login(settings.getValue("Username"), settings.getValue("Password"));
xLog.info("pGuid in doSync is:" + PublicVariable.pGuid);
serviceParams.add(new ServiceParam("pGuid", PublicVariable.pGuid, String.class));
if (method=="all" || method=="person"){
try {
t = new AsyncCallWs(activity,"GetPersonInfo",serviceParams);
result = t.execute().get();
xLog.info("Sync Person=>"+ result);
String fields[] = result.split(PublicVariable.FIELD_SPLITTER);
Person person = new Person(activity,fields);
person.empty();
person.insert();
settings.update("PersonId",String.valueOf(person.getId()));
PublicVariable.personId = person.getId();
xLog.info("Person inserted...");
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
}
if (method=="all" || method=="personImage"){
try {
t = new AsyncCallWs(activity,"GetPersonImage",serviceParams);
result = t.execute().get();
if (!result.equals("Nothing")){
settings.update("picture", result);
xLog.info("Picture updatted...");
}
else
xLog.error("NO PERSON IMAGE FOUND!");
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
if (method=="all" || method=="lawyers"){
try {
t = new AsyncCallWs(activity,"GetLawyers",serviceParams);
result = t.execute().get();
xLog.info("Sync Lawyer=>"+ result);
if (!result.equals("Nothing")){
String records[] = result.split(PublicVariable.RECORD_SPLITTER);
String fields[];
Lawyer lawyer= new Lawyer(activity);
lawyer.empty();
for(int i=0;i<records.length;i++){
fields = records[i].split(PublicVariable.FIELD_SPLITTER);
lawyer = new Lawyer(activity, fields);
lawyer.insert();
}
xLog.info("Lawyers inserted...");
}
else
xLog.error("NO LAWYER FOUND!");
}catch (Exception e) {
xLog.error(e.getMessage());
}
}
if (method=="all" || method=="news"){
try {
t = new AsyncCallWs(activity,"GetNews",serviceParams);
result = t.execute().get();
String fields[];
Log.d("Ehsan","Sync News=>"+ result);
if (!result.equals("Nothing")){
String records[] = result.split(PublicVariable.RECORD_SPLITTER);
News news = new News(activity);
news.empty();
for(int i=0;i<records.length;i++){
fields = records[i].split(PublicVariable.FIELD_SPLITTER);
news= new News(activity,fields);
news.insert();
}
xLog.info("News inserted...");
}
else
xLog.error("NO NEWS FOUND!");
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
if (method=="all" || method=="messages"){
try {
t = new AsyncCallWs(activity,"GetMessagesInbox ",serviceParams);
result = t.execute().get();
Log.d("Ehsan","Sync message Inbox=>"+ result);
if (!result.equals("Nothing")){
String records[] = result.split(PublicVariable.RECORD_SPLITTER);
String fields[];
Message message = new Message(activity);
message.empty();
for(int i=0;i<records.length;i++){
fields = records[i].split(PublicVariable.FIELD_SPLITTER);
message= new Message(activity,fields);
message.insert();
}
xLog.info("Inbox messages inserted...");
}
else
xLog.error("NO MESSAGES FOUND!");
} catch (Exception e) {
xLog.error(e.getMessage());
}
try {
t = new AsyncCallWs(activity,"GetMessagesOutbox ",serviceParams);
result = t.execute().get();
Log.d("Ehsan","Sync message Outbox=>"+ result);
if (!result.equals("Nothing")){
String records[] = result.split(PublicVariable.RECORD_SPLITTER);
String fields[];
Message message = new Message(activity);
message.empty();
for(int i=0;i<records.length;i++){
fields = records[i].split(PublicVariable.FIELD_SPLITTER);
message= new Message(activity,fields);
message.insert();
}
xLog.info("Outbox messages inserted...");
}
else
xLog.error("NO MESSAGES FOUND!");
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
if (method=="all" || method=="requests"){
try {
t = new AsyncCallWs(activity,"GetAllRequests",serviceParams);
result = t.execute().get();
Log.d("Ehsan","Sync share buy sell requests=>"+ result);
if (!result.equals("Nothing")){
String records[] = result.split(PublicVariable.RECORD_SPLITTER);
String fields[];
Share share = new Share(activity);
share.empty();
for(int i=0;i<records.length;i++){
fields = records[i].split(PublicVariable.FIELD_SPLITTER);
share= new Share(activity,fields);
share.insert();
}
xLog.info("Shares inserted...");
}
else
xLog.error("NO MESSAGES FOUND!");
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
if (method=="all" || method=="financials"){
try {
t = new AsyncCallWs(activity,"GetFinancials",serviceParams);
result = t.execute().get();
Log.d("Ehsan","Sync Financials=>"+ result);
if (!result.equals("Nothing")){
String records[] = result.split(PublicVariable.RECORD_SPLITTER);
String fields[];
Financial financial = new Financial(activity);
financial.empty();
for(int i=0;i<records.length;i++){
fields = records[i].split(PublicVariable.FIELD_SPLITTER);
financial= new Financial(activity,fields);
financial.insert();
}
xLog.info("Financials inserted...");
}
else{
Log.e("Ehsan", "NOT FINANCIALS FOUND!");
}
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
}
Here
result = t.execute().get(); //<<< calling get method
as in doc AsyncTask.get() :
Waits if necessary for the computation to complete, and then retrieves
its result.
so to avoid freezing of Main UI Thread during execution of doInBackground start AsyncTask without calling get method as|:
t.execute();
I want to have a class which gets web method info and returns the
result
For this you should implement callback with AsyncTask which report to Activity. see following examples :
android asynctask sending callbacks to ui
How to implement callback with AsyncTask
Can anyone tell me what am I doing wrong? I need to get the access token from Google Plus..
I put this in my onConnected() method but I am not getting the access token, instead I am getting error...
Code:
try {
String token = GoogleAuthUtil.getToken(this, mPlusClient.getAccountName() + "", "oauth2:" + Scopes.PLUS_PROFILE +
"https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email");
Log.d("AccessToken", token);
} catch (UserRecoverableAuthException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GoogleAuthException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Error:
08-07 10:10:24.199: E/GoogleAuthUtil(17203): Calling this from your main thread can lead to deadlock and/or ANRs
Can anyone tell me what would be the correct way to get the Google Plus access token from the user?
You need to put the request for a token in a background thread. I've posted some example code showing how to do it in this question:
"Calling this from your main thread can lead to deadlock and/or ANRs while getting accesToken" from GoogleAuthUtil(Google Plus integration in Android)
You can access token in onConnected() method. add this code onConnected() methods scope.
final String SCOPES = "https://www.googleapis.com/auth/userinfo.profile";
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
String ace = "";
try {
ace = GoogleAuthUtil.getToken(getApplicationContext(),
Plus.AccountApi.getAccountName(mGoogleApiClient),
"oauth2:" + SCOPES);
}
catch (IOException e) {
e.printStackTrace();
}
catch (GoogleAuthException e) {
e.printStackTrace();
}
Log.i("", "mustafa olll " + ace);
return null;
}
}.execute();
You need to fetch it using async task.
public void onConnected(Bundle connectionHint) {
// Reaching onConnected means we consider the user signed in.
Log.i(TAG, "onConnected");
// Update the user interface to reflect that the user is signed in.
mSignInButton.setEnabled(false);
mSignOutButton.setEnabled(true);
mRevokeButton.setEnabled(true);
// Retrieve some profile information to personalize our app for the user.
Person currentUser = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
AsyncTask<Void, Void, String > task = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String token = null;
final String SCOPES = "https://www.googleapis.com/auth/plus.login ";
try {
token = GoogleAuthUtil.getToken(
getApplicationContext(),
Plus.AccountApi.getAccountName(mGoogleApiClient),
"oauth2:" + SCOPES);
} catch (IOException e) {
e.printStackTrace();
} catch (GoogleAuthException e) {
e.printStackTrace();
}
return token;
}
#Override
protected void onPostExecute(String token) {
Log.i(TAG, "Access token retrieved:" + token);
}
};
task.execute();
System.out.print("email" + email);
mStatus.setText(String.format(
getResources().getString(R.string.signed_in_as),
currentUser.getDisplayName()));
Plus.PeopleApi.loadVisible(mGoogleApiClient, null)
.setResultCallback(this);
// Indicate that the sign in process is complete.
mSignInProgress = STATE_DEFAULT; }
Your access token will be stored into token variable.
Here is the code you can use. If someone has better suggestion then please post:
/**
* Successfully connected (called by PlusClient)
*/
#Override
public void onConnected(Bundle connectionHint) {
/* First do what ever you wanted to do in onConnected() */
....
....
/* Now get the token using and async call*/
GetGooglePlusToken token = new GetGooglePlusToken(this.getActivity(), mPlusClient);
token.execute();
}
class GetGooglePlusToken extends AsyncTask<Void, Void, String> {
Context context;
private GoogleApiClient mGoogleApiClient;
private String TAG = this.getClass().getSimpleName();
public GetGooglePlusToken(Context context, GoogleApiClient mGoogleApiClient) {
this.context = context;
this.mGoogleApiClient = mGoogleApiClient;
}
#Override
protected String doInBackground(Void... params) {
String accessToken1 = null;
try {
Bundle bundle = new Bundle();
String accountname = Plus.AccountApi.getAccountName(mGoogleApiClient);
String scope = "oauth2:" + Scopes.PLUS_LOGIN + " " + "https://www.googleapis.com/auth/userinfo.email" + " https://www.googleapis.com/auth/plus.profile.agerange.read";
accessToken1 = GoogleAuthUtil.getToken(context,
accountname,
scope);
return accessToken1;
} catch (IOException transientEx) {
// network or server error, the call is expected to succeed if you try again later.
// Don't attempt to call again immediately - the request is likely to
// fail, you'll hit quotas or back-off.
//TODO: HANDLE
Log.e(TAG, "transientEx");
transientEx.printStackTrace();
accessToken1 = null;
} catch (UserRecoverableAuthException e) {
// Recover
Log.e(TAG, "UserRecoverableAuthException");
e.printStackTrace();
accessToken1 = null;
} catch (GoogleAuthException authEx) {
// Failure. The call is not expected to ever succeed so it should not be
// retried.
Log.e(TAG, "GoogleAuthException");
authEx.printStackTrace();
accessToken1 = null;
} catch (Exception e) {
Log.e(TAG, "RuntimeException");
e.printStackTrace();
accessToken1 = null;
throw new RuntimeException(e);
}
Log.wtf(TAG, "Code should not go here");
accessToken1 = null;
return accessToken1;
}
#Override
protected void onPostExecute(String response) {
Log.d(TAG, "Google access token = " + response);
}
}
I have Written the code to Integrate the Twitter in android.In that I am getting the first scrren and when I am writing some message to twitt and click on the twitt button I am getting following Exception as OauthCommunication Exception communication with the service provider failed.I have entered the Consumer key Consumer secrete properly.
Public class MainActivity extends Activity {
private static final String TAG = "TwitterDemo";
private static final String CONSUMER_KEY = "xxx";
private static final String CONSUMER_SECRET = "xxx";
private static final String CALLBACK_SCHEME = "twitter-OAUTH-test-app";
private static final String CALLBACK_URL = CALLBACK_SCHEME + "://callback";
private static final String TWITTER_USER = "androidtestacc1#gmail.com";
private OAuthSignpostClient oauthClient;
private OAuthConsumer mConsumer;
private OAuthProvider mProvider;
private Twitter twitter;
SharedPreferences prefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mConsumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
mProvider = new DefaultOAuthProvider(
"http://api.twitter.com/oauth/request_token",
"http://api.twitter.com/oauth/access_token",
"http://api.twitter.com/oauth/authorize");
prefs = PreferenceManager.getDefaultSharedPreferences(this);
String token = prefs.getString("token", null);
String tokenSecret = prefs.getString("tokenSecret", null);
if (token != null && tokenSecret != null) {
mConsumer.setTokenWithSecret(token, tokenSecret);
oauthClient = new OAuthSignpostClient(CONSUMER_KEY,
CONSUMER_SECRET, token, tokenSecret);
twitter = new Twitter(TWITTER_USER, oauthClient);
} else {
Log.d(TAG, "onCreate. Not Authenticated Yet " );
new OAuthAuthorizeTask().execute();
}
}
class OAuthAuthorizeTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
String authUrl;
String message = null;
Log.d(TAG, "OAuthAuthorizeTask mConsumer: " + mConsumer);
Log.d(TAG, "OAuthAuthorizeTask mProvider: " + mProvider);
try {
authUrl = mProvider.retrieveRequestToken(mConsumer,
CALLBACK_URL);
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(authUrl));
startActivity(intent);
} catch (OAuthMessageSignerException e) {
message = "OAuthMessageSignerException";
e.printStackTrace();
} catch (OAuthNotAuthorizedException e) {
message = "OAuthNotAuthorizedException";
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
message = "OAuthExpectationFailedException";
e.printStackTrace();
} catch (OAuthCommunicationException e) {
message = "OAuthCommunicationException";
e.printStackTrace();
}
return message;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null) {
Toast.makeText(MainActivity.this, result,
Toast.LENGTH_LONG).show();
}
}
}
public void tweet(View view) {
if (twitter == null) {
Toast.makeText(this, "Authenticate first", Toast.LENGTH_LONG)
.show();
return;
}
EditText status = (EditText) findViewById(R.id.editTextTweet);
new PostStatusTask().execute(status.getText().toString());
}
class PostStatusTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
twitter.setStatus(params[0]);
return "Successfully posted: " + params[0];
} catch (TwitterException e) {
e.printStackTrace();
return "Error connecting to server.";
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(MainActivity.this, result,
Toast.LENGTH_LONG).show();
}
}
/* Responsible for retrieving access tokens from twitter */
class RetrieveAccessTokenTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String message = null;
String oauthVerifier = params[0];
try {
// Get the token
Log.d(TAG, " RetrieveAccessTokenTask mConsumer: " + mConsumer);
Log.d(TAG, " RetrieveAccessTokenTask mProvider: " + mProvider);
Log.d(TAG, " RetrieveAccessTokenTask verifier: " + oauthVerifier);
mProvider.retrieveAccessToken(mConsumer, oauthVerifier);
String token = mConsumer.getToken();
String tokenSecret = mConsumer.getTokenSecret();
mConsumer.setTokenWithSecret(token, tokenSecret);
Log.d(TAG, String.format(
"verifier: %s, token: %s, tokenSecret: %s", oauthVerifier,
token, tokenSecret));
// Store token in prefs
prefs.edit().putString("token", token)
.putString("tokenSecret", tokenSecret).commit();
// Make a Twitter object
oauthClient = new OAuthSignpostClient(CONSUMER_KEY,
CONSUMER_SECRET, token, tokenSecret);
twitter = new Twitter(null, oauthClient);
Log.d(TAG, "token: " + token);
} catch (OAuthMessageSignerException e) {
message = "OAuthMessageSignerException";
e.printStackTrace();
} catch (OAuthNotAuthorizedException e) {
message = "OAuthNotAuthorizedException";
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
message = "OAuthExpectationFailedException";
e.printStackTrace();
} catch (OAuthCommunicationException e) {
message = "OAuthCommunicationException";
e.printStackTrace();
}
return message;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null) {
Toast.makeText(MainActivity.this, result,
Toast.LENGTH_LONG).show();
}
}
}
/*
* Callback once we are done with the authorization of this app with
* Twitter.
*/
#Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Log.d(TAG, "intent: " + intent);
// Check if this is a callback from OAuth
Uri uri = intent.getData();
if (uri != null && uri.getScheme().equals(CALLBACK_SCHEME)) {
Log.d(TAG, "callback: " + uri.getPath());
String verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
Log.d(TAG, "verifier: " + verifier);
Log.d(TAG, " xxxxxxxxxxx mConsumer access token: " + mConsumer.getToken());
Log.d(TAG, " xxxxxxxxxxxx mConsumer access token secret: " + mConsumer.getTokenSecret());
Log.d(TAG, " xxxxxxxxxxxxx OAuth.OAUTH_TOKEN: " + OAuth.OAUTH_TOKEN);
Log.d(TAG, " xxxxxxxxxxxxx OAuth.OAUTH_TOKEN_SECRET: " + OAuth.OAUTH_TOKEN_SECRET);
new RetrieveAccessTokenTask().execute(verifier);
}
}
public void logout(View view){
SharedPreferences.Editor editor = prefs.edit();
editor.putString("token", null);
editor.putString("tokenSecret", null);
editor.commit();
finish();
}
}
error
10-19 15:18:55.424: W/System.err(995): oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: http://api.twitter.com/oauth/request_token
10-19 15:18:55.424: W/System.err(995): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:214)
10-19 15:18:55.438: W/System.err(995): at oauth.signpost.AbstractOAuthProvider.retrieveRequestToken(AbstractOAuthProvider.java:69)
10-19 15:18:55.655: W/System.err(995): ... 9 more
try another way to integerate twitter in your app
Using auth & webview(Twitter4j library)
http://davidcrowley.me/?p=410
http://www.mokasocial.com/2011/07/writing-an-android-twitter-client-with-image-upload-using-twitter4j/
code(url open in web view)
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(TwitterConstants.CONSUMER_KEY,
TwitterConstants.CONSUMER_SECRET);
RequestToken requestToken = null;
try {
requestToken = twitter.getOAuthRequestToken();
System.out.println("requesttoken"+requestToken);
} catch (TwitterException e) {
e.printStackTrace();
}
twitterUrl = requestToken.getAuthorizationURL();
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthAccessToken(TwitterConstants.ACCESS_TOKEN);
builder.setOAuthAccessTokenSecret(TwitterConstants.ACCESS_TOKEN_SECRET);
builder.setOAuthConsumerKey(TwitterConstants.CONSUMER_KEY);
builder.setOAuthConsumerSecret(TwitterConstants.CONSUMER_SECRET);
OAuthAuthorization auth = new OAuthAuthorization(builder.build());
twitter = new TwitterFactory().getInstance(auth);
try {
twitter.updateStatus("Hello World!");
} catch (TwitterException e) {
System.err.println("Error occurred while updating the status!");
}
2. On Button Click(Without auth)
String message="";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://twitter.com/?status=" + Uri.encode(message)));
startActivity(i);
Please put following permission in your Manifest file
<uses-permission android:name="android.permission.INTERNET"/>
also check this link....
http://www.android10.org/index.php/articleslibraries/291-twitter-integration-in-your-android-application