2

I am using twitter4J to post tweet on twitter

Here i Change the Code according to your suggestion . i do some google search. The problem is When i try to shift from main activity to twitter activity it show force close. Main activity is = "MainActivity" twitter activity is = "twiti_backup" I think there is problem in Manifestfile but i dont know what was it.

public class twiti_backup extends Activity {

private static final String TAG = "Blundell.TweetToTwitterActivity";


private static final String PREF_ACCESS_TOKEN = "";

private static final String PREF_ACCESS_TOKEN_SECRET = "";

private static final String CONSUMER_KEY = "";

private static final String CONSUMER_SECRET = ""; 
private static final String CALLBACK_URL = "android:///";

private SharedPreferences mPrefs;

private Twitter mTwitter;

private RequestToken mReqToken;

private Button mLoginButton;
private Button mTweetButton;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.i(TAG, "Loading TweetToTwitterActivity");
    setContentView(R.layout.twite);


    mPrefs = getSharedPreferences("twitterPrefs", MODE_PRIVATE);

    mTwitter = new TwitterFactory().getInstance();

    mTwitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);


    mLoginButton = (Button) findViewById(R.id.login_button);
    mTweetButton = (Button) findViewById(R.id.tweet_button);
}


public void buttonLogin(View v) {
    Log.i(TAG, "Login Pressed");
    if (mPrefs.contains(PREF_ACCESS_TOKEN)) {
        Log.i(TAG, "Repeat User");
        loginAuthorisedUser();
    } else {
        Log.i(TAG, "New User");
        loginNewUser();
    }
}


public void buttonTweet(View v) {
    Log.i(TAG, "Tweet Pressed");
    tweetMessage();
}


private void loginNewUser() {
    try {
        Log.i(TAG, "Request App Authentication");
        mReqToken = mTwitter.getOAuthRequestToken(CALLBACK_URL);

        Log.i(TAG, "Starting Webview to login to twitter");
        WebView twitterSite = new WebView(this);
        twitterSite.loadUrl(mReqToken.getAuthenticationURL());
        setContentView(twitterSite);

    } catch (TwitterException e) {
        Toast.makeText(this, "Twitter Login error, try again later", Toast.LENGTH_SHORT).show();
    }
}


private void loginAuthorisedUser() {
    String token = mPrefs.getString(PREF_ACCESS_TOKEN, null);
    String secret = mPrefs.getString(PREF_ACCESS_TOKEN_SECRET, null);

    // Create the twitter access token from the credentials we got previously
    AccessToken at = new AccessToken(token, secret);

    mTwitter.setOAuthAccessToken(at);

    Toast.makeText(this, "Welcome back", Toast.LENGTH_SHORT).show();

    enableTweetButton();
}

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    Log.i(TAG, "New Intent Arrived");
    dealWithTwitterResponse(intent);
}

@Override
protected void onResume() {
    super.onResume();
    Log.i(TAG, "Arrived at onResume");
}


private void dealWithTwitterResponse(Intent intent) {
    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 {
        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.twite);

        enableTweetButton();
    } catch (TwitterException e) {
        Toast.makeText(this, "Twitter auth error x01, try again later", Toast.LENGTH_SHORT).show();
    }
}


private void enableTweetButton() {
    Log.i(TAG, "User logged in - allowing to tweet");
    mLoginButton.setEnabled(false);
    mTweetButton.setEnabled(true);
}


private void tweetMessage() {
    try {
        mTwitter.updateStatus("Test - Tweeting with @Blundell_apps #AndroidDev Tutorial using #Twitter4j http://blog.blundell-apps.com/sending-a-tweet/");

        Toast.makeText(this, "Tweet Successful!", Toast.LENGTH_SHORT).show();
    } catch (TwitterException e) {
        Toast.makeText(this, "Tweet error, try again later", Toast.LENGTH_SHORT).show();
    }
}

private void saveAccessToken(AccessToken at) {
    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();
}

}

And here is Manifest

  <application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/title_activity_main" 
        android:launchMode="singleInstance"
          android:configChanges="orientation|screenSize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".twiti_backup"
         android:launchMode="singleInstance">     
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />               <data android:scheme="android" android:host="callback_main" />              </activity>
  <activity android:name=".MyTwite"/>
    <activity android:name=".mp3" />
     <activity android:name=".myfbapp" />
</application>

Here is Log cat when i try to launch twiti_backup from main activity

W/dalvikvm(16357): threadid=1: thread exiting with uncaught exception (group=0x4001d5a0) 
E/AndroidRuntime(16357): FATAL EXCEPTION: main E/AndroidRuntime(16357): java.lang.VerifyError: com.example.uitest.twiti_backup
E/AndroidRuntime(16357): at java.lang.Class.newInstanceImpl(Native Method)
E/AndroidRuntime(16357): at java.lang.Class.newInstance(Class.java:1409)
E/AndroidRuntime(16357): at android.app.Instrumentation.newActivity(Instrumentation.java:1040)
E/AndroidRuntime(16357): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1735)
E/AndroidRuntime(16357): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1842)
E/AndroidRuntime(16357): at android.app.ActivityThread.access$1500(ActivityThread.java:132)
E/AndroidRuntime(16357): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1038)
E/AndroidRuntime(16357): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(16357): at android.os.Looper.loop(Looper.java:143)
E/AndroidRuntime(16357): at android.app.ActivityThread.main(ActivityThread.java:4263)
E/AndroidRuntime(16357): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(16357): at java.lang.reflect.Method.invoke(Method.java:507)
E/AndroidRuntime(16357): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
E/AndroidRuntime(16357): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
E/AndroidRuntime(16357): at dalvik.system.NativeStart.main(Native Method)
pahan
  • 2,445
  • 1
  • 28
  • 36
  • give us some more info ... like Exceptions from logcat http://developer.android.com/tools/debugging/index.html http://developer.android.com/tools/debugging/debugging-projects.html – Selvin Sep 06 '12 at 09:59
  • I have edited the main question and added log cat .. still problem in launching twitter acitivity from main activity.. –  Sep 06 '12 at 15:38
  • http://stackoverflow.com/questions/100107/reasons-of-getting-a-java-lang-verifyerror – Selvin Sep 06 '12 at 15:50

2 Answers2

2

First, your CALLBACKURL = "T4J_OAuth://callback_main" is wrong when compare with your manifest, it should be:CALLBACKURL = "T4J_OAuth:///"

Second: android:launchMode="singleTop" should be android:launchMode="singleInstance"

Maybe there are some more bugs, but you should fix it yourseft!

Edited: You should declare Provider and Consumer:

consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRETE);
provider = new DefaultOAuthProvider(
            "http://twitter.com/oauth/request_token",
            "http://twitter.com/oauth/access_token",
            "http://twitter.com/oauth/authorize");
provider.retrieveRequestToken(consumer, CALL_BACK);
startActivity(new Intent(Intent.ACTION_VIEW, Uri
                    .parse(result)));

Also, you should create some AsyncTask to call those statments: rovider.retrieveRequestToken(consumer, CALL_BACK); and provider.retrieveAccessToken(consumer, verifier);

Edited Look at this tutorial, just change the CallBack_Url = "..." to CallBack_URL = "callback:///" and using below code to create Twitter object:

ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true).setOAuthConsumerKey(CONSUMER_KEY)
.setOAuthConsumerSecret(CONSUMER_SECRETE)
// accessTokenKey and accessTokenSecrete are what you get after redirecting
//   back from your oauthentication
.setOAuthAccessToken(accessTokenKey)
.setOAuthAccessTokenSecret(accessTokenSecrete)
.setMediaProviderAPIKey(TWITPIC_API_KEY);
Configuration config = cb.build();
TwitterFactory tf = new TwitterFactory(config);
Twitter twitter = tf.getInstance();

Notice: Don't let the call back url property in your twitter app null, put any dummy link into it! (App of your twitter account!! not your android app!) Sorry if there's any type error!

Edit You got an Verifier error because of your verifier is wrong! I used signpost lib to get verifier: String verifier = data .getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER); I think you should try to use signpost lib!

Kingfisher Phuoc
  • 8,052
  • 9
  • 46
  • 86
  • I made change as you said now when i click on twitter button it redirect me to login page with my app name and photo bla bla but when i login it redirect me to twitter mobile page and again show me login and password windows on that page.. I want to redirect back to my app and i want to make tweet from my app .. any help for that –  Sep 06 '12 at 10:17
  • I have made changes in my code but still there is force close while shifting from main activity to twitter activity .. i have edited the main question with logcat ..please help me –  Sep 06 '12 at 15:37
  • If I use "T4J_OAuth:///", then all it does is take me to the Twitter homepage – IgorGanapolsky Nov 29 '12 at 23:03
2

Add below two line code into your main activity's onCreate method after setcontentview() line, it will solve your problem.

if (android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
}
Dipak Keshariya
  • 22,193
  • 18
  • 76
  • 128
  • Thanks it works with jellybean and ICS.... can you suggests some code for made tweet from your app .. my code having many issues i want to make it work to post tweet from my app . do you have any sample code for that?..thank you again –  Sep 06 '12 at 10:37
  • see this link for complete information but the above code is add into this link's example http://androidcodeexamples.blogspot.in/2011/12/how-to-integrate-twitter-in-android.html – Dipak Keshariya Sep 06 '12 at 10:56
  • dude can you please share your XML file .. i copied your code , added jar files , set permission , i have added activity for class , but still it show force close ... –  Sep 06 '12 at 14:23
  • 4
    this is not the proper way to resolve `NetworkOnMainThreadException` – Selvin Sep 06 '12 at 15:52
  • 2
    @Selvin: Right! It's only a trick! You should implements `AsyncTask` to solve this problem! – Kingfisher Phuoc Sep 06 '12 at 16:44
  • @Selvin,@Kingfisher Please Give me example link of AsyncTask Implementation. – Dipak Keshariya Sep 07 '12 at 04:32
  • You should visit vogella tutorial! His tutorial contains many basic thing! Here is the link: http://www.vogella.com/articles/AndroidPerformance/article.html – Kingfisher Phuoc Sep 07 '12 at 07:03
  • @Kingfisher but tell me how to implement Async task in above link's code. – Dipak Keshariya Sep 07 '12 at 07:12
  • @dipak keshariya please share your tutorial source code .. so i can get better idea –  Sep 07 '12 at 07:53
  • look [here](http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception) (you have enough points to check that solutions with disabling strictmode have lots of downvotes) there are few links like [this](http://android-developers.blogspot.com/2009/05/painless-threading.html) check it ... disabling StrictMode will and with ends [ANR](http://developer.android.com/guide/practices/responsiveness.html#anr) sooner or later – Selvin Sep 07 '12 at 08:19
  • @DipakKeshariya dude If i create new project with importing your code than it works fine ... but when i copy paste same java , xml and some modification on manifest than it wont work..in my app i have created twitter button when you press twitter button it suppose to redirect into "TwitterActivity"class by intent..but it shows force close –  Sep 07 '12 at 10:38
  • @swapniladsure Are you adding required jar files? – Dipak Keshariya Sep 07 '12 at 10:45
  • any ways i am fed up with these things...i just want to ask you that is there any simple way to pass string to twitter app (if twitter app is not install than we can redirect to web browser to post tweet)..i don't want more headache..or Is there any way to integrate another project with your project (so i can call your TwitterActivity class ) I mean Is there any other way to add two project into one apk like we add dependancies of facebook . –  Sep 07 '12 at 11:33
  • @swapniladsure sorry i don't know about this. – Dipak Keshariya Sep 07 '12 at 11:37
  • @DipakKeshariya thank you for help and support..i got this error 09-07 11:57:32.511: E/AndroidRuntime(6410): java.lang.VerifyError: com.android.twitter.MainActivity –  Sep 07 '12 at 12:05
  • i tried to delete all the jar files , i clean project , i also try to create new folder copy all jar into it and set it as build path.. but no luck with it –  Sep 07 '12 at 12:10
  • @swapniladsure In my code above two line is not added so please add above two lines in my code and then check. – Dipak Keshariya Sep 07 '12 at 12:33