[TUT] Sending a Tweet

Tutorials with advanced 'difficulty' and more Lines of Code.

Re: [TUT] Sending a Tweet

Postby darkprincevj » Sat Nov 19, 2011 1:43 am

I have modified your code a bit to make sure i have an app with working button that simply login and move to another intent. I am also discarding the fact if the user credentials are already saved. I am asking user to login everytime. Here is code i have written. But it shows exceptions. The log cat is as below.

Code: Select all
package com.vj;

import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.Toast;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;


public class A1Activity extends Activity {
   
    private static final String PREF_ACCESS_TOKEN = "accessToken"; // Called when the activity is first created.     
    private static final String PREF_ACCESS_TOKEN_SECRET = "accessTokenSecret";// Name to store the users access token secret   
    public final static String CONSUMER_KEY = "LD0YgihZOANueIyGOZcjA"; // "your key here";
    public final static String CONSUMER_SECRET = "VsIRX2LweeyNadgSlsunGYc9liTX51Wao2eBfJCjA"; // "your secret key here";     
    private static final String CALLBACK_URL = "tweet-to-twitter-vasujain-android:///";// The url that Twitter will redirect to after a user log
    private SharedPreferences mPrefs;     // Preferences to store a logged in users credentials
    private Twitter mTwitter;// = new TwitterFactory().getInstance();
    private RequestToken mReqToken;/** The request token signifies the unique ID of the request you are sending to twitter  */
     
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        System.out.println("On Create");
       
        mPrefs = getSharedPreferences("twitterPrefs", MODE_PRIVATE);
        mTwitter = new TwitterFactory().getInstance();       
        mTwitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
        //mLoginButton = (Button) findViewById(R.id.login_button);
        //oAuth();
    }
   
    public void loginNewUser() {       
       try {               
           System.out.println("Login New");   
              mReqToken = mTwitter.getOAuthRequestToken(CALLBACK_URL);
                WebView twitterSite = new WebView(this);
                twitterSite.loadUrl(mReqToken.getAuthenticationURL());
                setContentView(twitterSite);
                System.out.println("login new ");

        } catch (TwitterException e) {
           System.out.println("Twitter Login error, try again later ");
                Toast.makeText(this, "Twitter Login error, try again later", Toast.LENGTH_SHORT).show();
        }
    }
   
    @Override
    protected void onNewIntent(Intent intent) {
   
       System.out.println("Intent New");
       super.onNewIntent(intent);           
            dealWithTwitterResponse(intent);
    }
   
    private void dealWithTwitterResponse(Intent intent) {

       System.out.println("Twi Respose");
       Uri uri = intent.getData();
        if (uri != null && uri.toString().startsWith(CALLBACK_URL)) { // If the user has just logged in
                String oauthVerifier = uri.getQueryParameter("oauth_verifier");
                authoriseNewUser(oauthVerifier);
        }
    }
   
    private void authoriseNewUser(String oauthVerifier) {
        try {
           System.out.println("Auth User");   
           AccessToken at = mTwitter.getOAuthAccessToken(mReqToken, oauthVerifier);
                mTwitter.setOAuthAccessToken(at);
                saveAccessToken(at);
                // Set the content view back after we changed to a webview
                   setContentView(R.layout.main);               
              } catch (TwitterException e) {
                 Toast.makeText(this, "Twitter auth error x01, try again later", Toast.LENGTH_SHORT).show();
              }
          }
   
    private void saveAccessToken(AccessToken at) {
       System.out.println("saveAccessToken ");
        String token = at.getToken();
        String secret = at.getTokenSecret();
        Editor editor = mPrefs.edit();
        editor.putString(PREF_ACCESS_TOKEN, token);
        editor.putString(PREF_ACCESS_TOKEN_SECRET, secret);
        editor.commit();
       }
}



Manifest File
Code: Select all
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.vj"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />
   <uses-permission android:name="android.permission.INTERNET" />
   
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".A1Activity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
           
            <intent-filter>
                           <action android:name="android.intent.action.VIEW" />
                           <category android:name="android.intent.category.DEFAULT" />
                           <category android:name="android.intent.category.BROWSABLE" />
                           <data android:scheme="tweet-to-twitter-vasujain-android" />
            </intent-filter>
        </activity>
    </application>

</manifest>


Main.xml
Code: Select all
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
   
    <Button
      android:id="@+id/login_button"
      android:onClick="loginNewUser"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="Login" />
   
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

</LinearLayout>

   
   


The output for Error Log is :

11-18 16:30:55.044: I/Process(392): Sending signal. PID: 392 SIG: 9
11-18 16:33:32.024: I/System.out(422): On Create
11-18 16:42:32.664: D/AndroidRuntime(422): Shutting down VM
11-18 16:42:32.664: W/dalvikvm(422): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
11-18 16:42:32.864: E/AndroidRuntime(422): FATAL EXCEPTION: main
11-18 16:42:32.864: E/AndroidRuntime(422): java.lang.IllegalStateException: Could not find a method loginNewUser(View) in the activity class com.vj.A1Activity for onClick handler on view class android.widget.Button with id 'login_button'
11-18 16:42:32.864: E/AndroidRuntime(422): at android.view.View$1.onClick(View.java:2059)
11-18 16:42:32.864: E/AndroidRuntime(422): at android.view.View.performClick(View.java:2408)
11-18 16:42:32.864: E/AndroidRuntime(422): at android.view.View$PerformClick.run(View.java:8816)
11-18 16:42:32.864: E/AndroidRuntime(422): at android.os.Handler.handleCallback(Handler.java:587)
11-18 16:42:32.864: E/AndroidRuntime(422): at android.os.Handler.dispatchMessage(Handler.java:92)
11-18 16:42:32.864: E/AndroidRuntime(422): at android.os.Looper.loop(Looper.java:123)
11-18 16:42:32.864: E/AndroidRuntime(422): at android.app.ActivityThread.main(ActivityThread.java:4627)
11-18 16:42:32.864: E/AndroidRuntime(422): at java.lang.reflect.Method.invokeNative(Native Method)
11-18 16:42:32.864: E/AndroidRuntime(422): at java.lang.reflect.Method.invoke(Method.java:521)
11-18 16:42:32.864: E/AndroidRuntime(422): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
11-18 16:42:32.864: E/AndroidRuntime(422): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
11-18 16:42:32.864: E/AndroidRuntime(422): at dalvik.system.NativeStart.main(Native Method)
11-18 16:42:32.864: E/AndroidRuntime(422): Caused by: java.lang.NoSuchMethodException: loginNewUser
11-18 16:42:32.864: E/AndroidRuntime(422): at java.lang.ClassCache.findMethodByName(ClassCache.java:308)
11-18 16:42:32.864: E/AndroidRuntime(422): at java.lang.Class.getMethod(Class.java:985)
11-18 16:42:32.864: E/AndroidRuntime(422): at android.view.View$1.onClick(View.java:2052)
11-18 16:42:32.864: E/AndroidRuntime(422): ... 11 more
11-18 16:42:37.404: I/Process(422): Sending signal. PID: 422 SIG: 9


could you tell me where are the things going wrong over here?
darkprincevj
Freshman
Freshman
 
Posts: 4
Joined: Sat Nov 19, 2011 1:38 am

Top

Re: [TUT] Sending a Tweet

Postby blundell » Mon Nov 21, 2011 9:24 am

Sure.

The method you have created to be used as the onClick listener for the XML button is not taking a view parameter, therefore your Logcat is saying it cannot find a method with this signature (which is correct!).

i.e. you have this:

Code: Select all
public void loginNewUser() {


but need this:

Code: Select all
public void loginNewUser(View v) {
User avatar
blundell
Master Developer
Master Developer
 
Posts: 1610
Joined: Tue Nov 18, 2008 12:58 pm
Location: UK

Re: [TUT] Sending a Tweet

Postby darkprincevj » Mon Nov 21, 2011 10:36 am

Thanks .. However I have some problems in implementing a list view with 3 items, one text, one image and on radio button. Could you please let me know how can we perform that.

I have
String[] MovieName=new String[MovieNum]; //Has Movie Name Text
String[] MovieCover=new String[MovieNum]; // Has Movie Iamge URL

Can you help me with this with a probable sample code ?
darkprincevj
Freshman
Freshman
 
Posts: 4
Joined: Sat Nov 19, 2011 1:38 am

Re: [TUT] Sending a Tweet

Postby blundell » Mon Nov 21, 2011 12:21 pm

Sorry that's off topic. Start a new thread, or look on StackOverflow (link in my sig)
User avatar
blundell
Master Developer
Master Developer
 
Posts: 1610
Joined: Tue Nov 18, 2008 12:58 pm
Location: UK

Re: [TUT] Sending a Tweet

Postby tzCoder » Mon Nov 21, 2011 5:58 pm

I can confirm the keyboard not showing up problem, it is a bug in Android. More info here
http://code.google.com/p/android/issues/detail?id=7189
and
http://stackoverflow.com/questions/4200 ... t-keyboard

I have not tried the solution yet to see if it solves the problem.
tzCoder
Freshman
Freshman
 
Posts: 4
Joined: Sun Jan 30, 2011 4:02 pm

Re: [TUT] Sending a Tweet

Postby maxivis » Mon Dec 05, 2011 4:30 pm

Hi blundell, I think your code is great, it really helps, but I'm having a problem when I try to send a tweet. I've copied entirely your code, the only modification that I've made is that after logs in, I automatically send the tweet (just removed the Tweet button and call the functionality to tweet inside the "authoriseNewUser" method); the authentication seems to be working fine, but instead of go back to my app code, I'm redirected to the callback url, I'm never returned to the "onNewIntent" method. In the log, the last I can see is "Arrived at onResume", below that "Displayed activity xxx.xxx.TweetToTwitterActivity", there is no error...
Please, do you have any idea about what is going on, or at least some tip you could give me? Thanks in advance
maxivis
Freshman
Freshman
 
Posts: 3
Joined: Mon Dec 05, 2011 4:09 pm

Top

Re: [TUT] Sending a Tweet

Postby jigneshpandya » Mon Dec 05, 2011 4:56 pm

Hello,

I tried using your code exactly as you had mentioned, I got the success viewing the Login Screen, and then it just shows me Error "Web page not available".

Could you please assist me as this is very first time am trying to integrate Twitter in my application.

Thanks in advance.

Regards,
Jignesh
jigneshpandya
Once Poster
Once Poster
 
Posts: 1
Joined: Mon Dec 05, 2011 4:52 pm

Re: [TUT] Sending a Tweet

Postby maxivis » Thu Dec 08, 2011 10:28 pm

Hi blundell, I finally got it working, but using a different sample code. jigneshpandya, if you still need the code, you can check this example https://github.com/ddewaele/AndroidTwit ... /downloads
You only need to modify Constants.java. I hope it can help you.
maxivis
Freshman
Freshman
 
Posts: 3
Joined: Mon Dec 05, 2011 4:09 pm

Re: [TUT] Sending a Tweet

Postby savvy » Mon Dec 26, 2011 10:31 am

Hi,

I am running your code on Eclipse (Indigo) and android 2.2 SDK, the signing-in part is perfect but after that whenever I try to post a tweet , it gives me the failure error "Tweet error, try again later". Can you please help me out? I have downloaded and am running your code. Thanks in advance.
savvy
Once Poster
Once Poster
 
Posts: 1
Joined: Mon Dec 26, 2011 10:27 am

Re: [TUT] Sending a Tweet

Postby blundell » Mon Jan 02, 2012 2:18 pm

@Savvy Hmm, does your emulator have an internet connection? It sound's like something on twitters side.
User avatar
blundell
Master Developer
Master Developer
 
Posts: 1610
Joined: Tue Nov 18, 2008 12:58 pm
Location: UK

Top
Previous

Return to Advanced Tutorials

Who is online

Users browsing this forum: No registered users and 3 guests