Android Question Using Twitter4J Library

somed3v3loper

Well-Known Member
Licensed User
Longtime User
Hi,
I posted this to Picasso Tutorial and now I am posting it as a new thread as per Erel's request.


As I still want a twitter solution I am trying to use Twitter4J but do not know if I am going the right way or not (which is more likely)


Here is the function I am trying to access
http://twitter4j.org/javadoc/twitte...zation.html#setOAuthConsumer(java.lang.String, java.lang.String)


B4X:
Sub GetContext As JavaObject
      Return GetBA.GetField("context")
End Sub

Sub GetBA As JavaObject
      Dim jo As JavaObject
    Dim cls As String = Me
    cls = cls.SubString("class ".Length)
    jo.InitializeStatic(cls)
    Return jo.GetFieldJO("processBA")
End Sub

Sub Twitter As JavaObject
      Dim jo As JavaObject
    Return jo.InitializeStatic("twitter4j.auth")
End Sub
Sub setOAuthConsumer(conskey As String,conscret As String)
      Twitter.RunMethodJO("setOAuthConsumer",Array())
End Sub

For the last SUB I do not know how to pass the two parameters .

Appreciate your help .

I want to use almost all Twitter4J functions but I am just starting to implement it through the new great features of B4A :)
 

somed3v3loper

Well-Known Member
Licensed User
Longtime User
I am not familiar with Java but I think they have some examples like this one :

B4X:
 public static void main(String args[]) throws Exception{
    // The factory instance is re-useable and thread safe.
    TwitterFactory factory = new TwitterFactory();
    AccessToken accessToken = loadAccessToken(Integer.parseInt(args[0]));
    Twitter twitter = factory.getInstance);
    twitter.setOAuthConsumerKey("[consumer key]", "[consumer secret]");
    twitter.setOAuthAccessToken(accessToken);
    Status status = twitter.updateStatus(args[1]);
    System.out.println("Successfully updated the status to [" + status.getText() + "].");
    System.exit(0);
  }
  private static AccessToken loadAccessToken(int useId){
    String token = // load from a persistent store
    String tokenSecret = // load from a persistent store
    return new AccessToken(token, tokenSecret);
  }


Here is the link

http://twitter4j.org/en/code-examples.html
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
Use #AdditionalJar to add a reference to the jar file.

The code should be something like:
B4X:
Dim factory As JavaObject
factory.InitializeNewInstance("twitter4j.TwitterFactory", null)
Dim token As JavaObject = LoadAccessToken(id)
Dim twitter As JavaObject = facroty.RunMethod("getInstance", null)
twitter.RunMethod("setOAuthConsumerKey", Array ("key", "secret"))
twitter.RunMethod("setOAuthAccessToken", Array(token))
Dim status As JavaObject = twitter.RunMethod("updateStatus", Array("status"))
Log(status.RunMethod("getText", null))

Sub LoadAccessToken (Id As Int) As JavaObject
 Dim t As JavaObject
 Return t.InitializeNewInstance("twitter4j.auth.AccessToken", Array ("token", "tokenSecret"))
End Sub
 
Upvote 0

somed3v3loper

Well-Known Member
Licensed User
Longtime User
Hello again ,

I have tried a lot but there seems to be something I could not understand

I am trying to port this code :

B4X:
  public static void main(String args[]) throws Exception{
    // The factory instance is re-useable and thread safe.
    Twitter twitter = TwitterFactory.getSingleton();
    twitter.setOAuthConsumer("[consumer key]", "[consumer secret]");
    RequestToken requestToken = twitter.getOAuthRequestToken();
    AccessToken accessToken = null;
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    while (null == accessToken) {
      System.out.println("Open the following URL and grant access to your account:");
      System.out.println(requestToken.getAuthorizationURL());
      System.out.print("Enter the PIN(if aviailable) or just hit enter.[PIN]:");
      String pin = br.readLine();
      try{
        if(pin.length() > 0){
          accessToken = twitter.getOAuthAccessToken(requestToken, pin);
        }else{
          accessToken = twitter.getOAuthAccessToken();
        }
      } catch (TwitterException te) {
        if(401 == te.getStatusCode()){
          System.out.println("Unable to get the access token.");
        }else{
          te.printStackTrace();
        }
      }
    }

Here is my attempt

B4X:
    Dim factory As JavaObject
    factory.InitializeNewInstance("twitter4j.TwitterFactory",Null)
    Dim twitter As JavaObject =factory.RunMethod("getSingleton",Null)
    twitter.RunMethodjo("setOAuthConsumer",Array (conKey,conSecret))
    Dim requesttoken As JavaObject
    requesttoken.InitializeStatic("twitter4j.auth.RequestToken")
    requesttoken.RunMethod("getAuthorizationURL",Null)
conKey,conSecret are my Consumer Key and Consumer Secret .

but I get this error

B4X:
java.lang.IllegalArgumentException: expected receiver of type twitter4j.auth.RequestToken, but got java.lang.Class<twitter4j.auth.RequestToken>


Can you please help me ?
 
Upvote 0

somed3v3loper

Well-Known Member
Licensed User
Longtime User
This line is wrong:
requesttoken.InitializeStatic("twitter4j.auth.RequestToken")

It should be:
B4X:
requesttoken = twitter.RunMethod("getOAuthRequestToken", null)

Now it raises
B4X:
java.lang.reflect.InvocationTargetException
 
Upvote 0

somed3v3loper

Well-Known Member
Licensed User
Longtime User
Can you post the full error message?

Here it is


B4X:
Installing file.
PackageAdded: package:test.twitter
** Activity (main) Create, isFirst = true **
java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at anywheresoftware.b4j.object.JavaObject.RunMethod(JavaObject.java:109)
    at test.twitter.main._newtwitter(main.java:643)
    at test.twitter.main._activity_create(main.java:303)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at anywheresoftware.b4a.BA.raiseEvent2(BA.java:174)
    at test.twitter.main.afterFirstLayout(main.java:98)
    at test.twitter.main.access$100(main.java:16)
    at test.twitter.main$WaitForLayout.run(main.java:76)
    at android.os.Handler.handleCallback(Handler.java:725)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:213)
    at android.app.ActivityThread.main(ActivityThread.java:5092)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:564)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: android.os.NetworkOnMainThreadException
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1126)
    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
    at java.net.InetAddress.getAllByName(InetAddress.java:214)
    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
    at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
    at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
    at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
    at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)
    at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:461)
    at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:433)
    at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
    at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
    at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:81)
    at libcore.net.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:197)
    at libcore.net.http.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:281)
    at twitter4j.HttpClientImpl.handleRequest(HttpClientImpl.java:137)
    at twitter4j.HttpClientBase.request(HttpClientBase.java:53)
    at twitter4j.HttpClientBase.post(HttpClientBase.java:82)
    at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:116)
    at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:98)
    at twitter4j.TwitterBaseImpl.getOAuthRequestToken(TwitterBaseImpl.java:287)
    at twitter4j.TwitterBaseImpl.getOAuthRequestToken(TwitterBaseImpl.java:279)
    ... 20 more
 
Upvote 0

somed3v3loper

Well-Known Member
Licensed User
Longtime User
This error means that this library sends the requests on the main thread. You can use the Threading library to create a secondary thread however I recommend you to use a different library instead.

Can you please give me an example of using Threading with it?

And why do you recommend using other library ?
 
Upvote 0

somed3v3loper

Well-Known Member
Licensed User
Longtime User
Coming back to Twitter4J , I am stuck at getting the access token :

At web_OverrideUrl sub I am checking URL and if it contains oauth_token and oauth_verifier like the following :

B4X:
http://mycallback.com/?oauth_token=AAxVd0avtmFMghe4wpQRta2DpVT7BTY8P3nbuuEwmFqk&oauth_verifier=5wzW9Ybj5vvsXb0AgeEFwLR9bZGfEaqQugfh5Scc

I try getting access token by the following :

B4X:
twitter.RunMethod("getOAuthAccessToken",Array (toke,tokesec))

then I get this error
B4X:
java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at anywheresoftware.b4j.object.JavaObject.RunMethod(JavaObject.java:109)
    at test.twitter.main._web_overrideurl(main.java:906)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at anywheresoftware.b4a.BA.raiseEvent2(BA.java:175)
    at anywheresoftware.b4a.BA.raiseEvent2(BA.java:163)
    at anywheresoftware.b4a.BA.raiseEvent(BA.java:159)
    at anywheresoftware.b4a.objects.WebViewWrapper$1.shouldOverrideUrlLoading(WebViewWrapper.java:64)
    at android.webkit.CallbackProxy.uiOverrideUrlLoading(CallbackProxy.java:274)
    at android.webkit.CallbackProxy.handleMessage(CallbackProxy.java:381)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:213)
    at android.app.ActivityThread.main(ActivityThread.java:5092)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:564)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: android.os.NetworkOnMainThreadException
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1126)
    at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl$SSLOutputStream.write(OpenSSLSocketImpl.java:699)
    at java.io.BufferedOutputStream.flushInternal(BufferedOutputStream.java:185)
    at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:85)
    at libcore.net.http.HttpEngine.readResponse(HttpEngine.java:818)
    at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:283)
    at libcore.net.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:495)
    at libcore.net.http.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:134)

and if running that in a thread I got this one :

B4X:
java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at anywheresoftware.b4j.object.JavaObject.RunMethod(JavaObject.java:109)
    at test.twitter.main._gettimeline(main.java:536)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at anywheresoftware.b4a.agraham.threading.Threading$1.run(Threading.java:216)
    at java.lang.Thread.run(Thread.java:856)
Caused by: The screen name / password combination seems to be invalid.
Relevant discussions can be found on the Internet at:
    http://www.google.co.jp/search?q=96430884 or
    http://www.google.co.jp/search?q=0000298b
TwitterException{exceptionCode=[96430884-0000298b 17bf128c-12e072eb 86ebfb14-492de63c], statusCode=-1, message=null, code=-1, retryAfter=-1, rateLimitStatus=null, version=4.0.2}
    at twitter4j.auth.OAuthAuthorization.getOAuthAccessToken(OAuthAuthorization.java:157)
    at twitter4j.TwitterBaseImpl.getOAuthAccessToken(TwitterBaseImpl.java:338)
    ... 8 more
Caused by: No authentication challenges found
Relevant discussions can be found on the Internet at:
    http://www.google.co.jp/search?q=17bf128c or
    http://www.google.co.jp/search?q=12e072eb
TwitterException{exceptionCode=[17bf128c-12e072eb 86ebfb14-492de63c], statusCode=-1, message=null, code=-1, retryAfter=-1, rateLimitStatus=null, version=4.0.2}
    at twitter4j.HttpClientImpl.handleRequest(HttpClientImpl.java:178)
    at twitter4j.HttpClientBase.request(HttpClientBase.java:53)
    at twitter4j.HttpClientBase.post(HttpClientBase.java:82)
    at twitter4j.auth.OAuthAuthorization.getOAuthAccessToken(OAuthAuthorization.java:150)
    ... 9 more
Caused by: java.io.IOException: No authentication challenges found
    at libcore.net.http.HttpURLConnectionImpl.getAuthorizationCredentials(HttpURLConnectionImpl.java:436)
    at libcore.net.http.HttpURLConnectionImpl.processAuthHeader(HttpURLConnectionImpl.java:416)
 
Upvote 0

somed3v3loper

Well-Known Member
Licensed User
Longtime User
I moved my project to B4J to edit and test faster.

Here when trying to get AccessToken I get the error :


B4X:
Error occurred on line: 87 (main).
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at anywheresoftware.b4j.object.JavaObject.RunMethod(JavaObject.java:109)
    at b4j.example.main._getaccesstok(main.java:149)
    at b4j.example.main._web_pagefinished(main.java:181)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at anywheresoftware.b4a.shell.Shell.runMethod(Shell.java:563)
    at anywheresoftware.b4a.shell.Shell.raiseEventImpl(Shell.java:221)
    at anywheresoftware.b4a.shell.Shell.raiseEvent(Shell.java:156)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at anywheresoftware.b4a.BA.raiseEvent2(BA.java:93)
    at anywheresoftware.b4a.ShellBA.raiseEvent2(ShellBA.java:82)
    at anywheresoftware.b4a.BA$2.run(BA.java:165)
    at com.sun.javafx.application.PlatformImpl$4.run(PlatformImpl.java:173)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.access$100(WinApplication.java:29)
    at com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:73)
    at java.lang.Thread.run(Thread.java:722)
Caused by: 401:Authentication credentials (https://dev.twitter.com/pages/auth) were missing or incorrect. Ensure that you have set valid consumer key/secret, access token/secret, and the system clock is in sync.
<?xml version="1.0" encoding="UTF-8"?>
<hash>
  <error>Invalid oauth_verifier parameter</error>
  <request>/oauth/access_token</request>
</hash>
Relevant discussions can be found on the Internet at:
    http://www.google.co.jp/search?q=1aec76dd or
    http://www.google.co.jp/search?q=3787d026
TwitterException{exceptionCode=[1aec76dd-3787d026], statusCode=401, message=null, code=-1, retryAfter=-1, rateLimitStatus=null, version=4.0.2}
    at twitter4j.HttpClientImpl.handleRequest(HttpClientImpl.java:163)
    at twitter4j.HttpClientBase.request(HttpClientBase.java:53)
    at twitter4j.HttpClientBase.post(HttpClientBase.java:82)
    at twitter4j.auth.OAuthAuthorization.getOAuthAccessToken(OAuthAuthorization.java:124)
    at twitter4j.auth.OAuthAuthorization.getOAuthAccessToken(OAuthAuthorization.java:138)
    at twitter4j.TwitterBaseImpl.getOAuthAccessToken(TwitterBaseImpl.java:328)
    ... 26 more


and why does it seem to be asking for access token/secret while I have not gotten them yet?
Please help
 
Upvote 0
Top