i am trying to embed twitter posting feature in my application.
i am using twitter api_me-1.8
i am able to reach the login screen(though most of the text is displayed as boxes- i am guessing that the text is in hindi/tamil as i am in india...), but as soon as i enter my credentials,i get taken to another page with some text in the top in boxes...
and more text in english below that(you can revoke access to any application...) ...then i get an illeagalArguementException after a minute...
i tried to debug the application,
public TwitterUiScreen(String wallMsg) {
System.out.println("Twitter UI BEGINS!");
setTitle("Twitter");
this.wallMsg = wallMsg;
BrowserContentManager browserMngr = new BrowserContentManager(0);
RenderingOptions rendOptions = browserMngr.getRenderingSession()
.getRenderingOptions();
rendOptions.setProperty(RenderingOptions.CORE_OPTIONS_GUID,
RenderingOptions.SHOW_IMAGES_IN_HTML, false);
rendOptions.setProperty(RenderingOptions.CORE_OPTIONS_GUID,
RenderingOptions.ENABLE_EMBEDDED_RICH_CONTENT, true);
rendOptions.setProperty(RenderingOptions.CORE_OPTIONS_GUID,
RenderingOptions.DEFAULT_FONT_FACE, true);
rendOptions.setProperty(RenderingOptions.CORE_OPTIONS_GUID,
RenderingOptions.DEFAULT_CHARSET_VALUE, true);
rendOptions.setProperty(RenderingOptions.CORE_OPTIONS_GUID,
RenderingOptions.JAVASCRIPT_ENABLED, true);
/*
* browserMngr.getRenderingSession().getRenderingOptions().setProperty(
* RenderingOptions.CORE_OPTIONS_GUID,
* RenderingOptions.DEFAULT_FONT_FACE, Font.getDefaultFont());
*/
add(browserMngr);
OAuthDialogWrapper pageWrapper = new BrowserContentManagerOAuthDialogWrapper(browserMngr);
pageWrapper.setConsumerKey(CONSUMER_KEY);
pageWrapper.setConsumerSecret(CONSUMER_SECRET);
pageWrapper.setCallbackUrl(CALLBACK_URL);
pageWrapper.setOAuthListener(this);
pageWrapper.login();
}
i had breakpoints upto the last line, and all of them were hit, with no problems...
but as soon as i logged in, i hit the exception.( i think it was in this page:-
BrowserContentManagerOAuthDialogWrapper.java (version 1.1 : 45.3, super bit)
after which i get to a third screen.
the comment was barely legible- so i thought i might as well add the code over here:
public static final String OAUTH_CALLBACK_SCHEME = "x-oauthflow-twitter";
public static final String OAUTH_CALLBACK_HOST = "callback";
public static final String OAUTH_CALLBACK_URL = OAUTH_CALLBACK_SCHEME+ "://" + OAUTH_CALLBACK_HOST;
private final String CALLBACK_URL = OAUTH_CALLBACK_URL;
i managed to get the source and attach it to the jar file. the exception that the BrowserContentManagerOAuthDialogWrapper.java throws is:: Protocol not found: net.rim.device.cldc.io.x-oauthflow-twitter.Protocol
in this method::
protected void loadUrl(final String url, final byte[] postData,
final Event event) {
new Thread() {
public void run() {
try {
HttpConnection conn = getConnection(url);
//
if (postData != null) {
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty(
"Content-Type",
"application/x-www-form-urlencoded");
conn.setRequestProperty(
"Content-Length", String.valueOf(postData.length));
//
OutputStream out = conn.openOutputStream();
out.write(postData);
out.close();
}
//
browserManager.setContent(
conn, renderingListenerOAuth, event);
} catch (IOException e) {
throw new IllegalArgumentException(e.getMessage());
}
}
}.start();
}
feel like hitting myself.
my clients had told us that the twitter posting was not working...
so i assumed that it did not work.
for some reason, it does not work in the simulator- but seems to work fine on the device.
the clients have assumed that it does not work, as after we try logging in, it takes too long to post, and displays the third screen for about 20 seconds, and they seem to have clicked back early, deciding that posting did not work.
now i need to figure out a way to post a message on the third screen asking the user to wait for the post to be successful.
Related
I am working on an Android App using Xamarin, in which server sends an OTP and the user needs to enter this OTP in the App, to SignUp for my App. What I want is, that my App should be able to automatically read the OTP sent by the server and to be filled in edit text field of OTP.
I'm almost done to read the message but unable to set the otp in edit text field.
SMS broadcast receiver class:
[BroadcastReceiver(Enabled = true, Label = "SMS Receiver")]
[IntentFilter(new string[] { "android.provider.Telephony.SMS_RECEIVED" })]
public class SMSBroadcastReceiver : BroadcastReceiver
{
private const string IntentAction = "android.provider.Telephony.SMS_RECEIVED";
public override void OnReceive(Context context, Intent intent)
{
try
{
if (intent.Action != IntentAction) return;
var bundle = intent.Extras;
if (bundle == null) return;
var pdus = bundle.Get("pdus");
// var castedPdus = JNIEnv.GetArray(pdus.Handle);
var castedPdus = JNIEnv.GetArray<Java.Lang.Object>(pdus.Handle);
var msgs = new SmsMessage[castedPdus.Length];
var sb = new StringBuilder();
string sender = null;
for (var i = 0; i < msgs.Length; i++)
{
var bytes = new byte[JNIEnv.GetArrayLength(castedPdus[i].Handle)];
JNIEnv.CopyArray(castedPdus[i].Handle, bytes);
string format = bundle.GetString("format");
msgs[i] = SmsMessage.CreateFromPdu(bytes,format);
if (sender == null)
sender = msgs[i].OriginatingAddress;
sb.Append(string.Format("SMS From: {0}{1}Body: {2}{1}", msgs[i].OriginatingAddress,System.Environment.NewLine, msgs[i].MessageBody));
Toast.MakeText(context, sb.ToString(), ToastLength.Long).Show();
}
}
catch (System.Exception ex)
{
Toast.MakeText(context, ex.Message, ToastLength.Long).Show();
}
}
}
Here is my main activity:
[Activity(Label = "UserSms", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
SMSBroadcastReceiver smsReceiver = new SMSBroadcastReceiver();
TextView msg = FindViewById<TextView>(Resource.Id.editTextOtp);
Button btn = FindViewById<Button>(Resource.Id.button3);
RegisterReceiver(smsReceiver, new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));
}
}
How can I achieve this? Any help or guidance in this regard would be highly appreciated.
Update
public void onSMSReceived(string msgs)
{
EditText OtpNumber = (EditText)FindViewById(Resource.Id.editTextOtp);
try
{
OtpNumber.SetText(msgs.ToString(),null);
}
catch (System.Exception ex)
{
}
}
Your are on the finishing line. You only need to do these thing:
Create an interface which will have public method onSMSReceived(String smsMsg)
Instantiate that interface.
Implement that interface in MainActivity activity.
Override onSMSReceived(String smsMsg) in your MainActivity
Notify MainActivity using above created interface from your SMS Broadcast Receiver.
Populate message received in onSMSReceived(String smsMsg) in your MainActivity.
You are done.
I didn't get exactly how you're doing it, but i did in two ways,
1.User has to enter it manually,
2.We have to read automatically through the programming,
But i faced one problem in reading sms automatically, like sending sms and reading sms are calling at the same time may be like register click event, I found one more way to detect automatically like sending otps two times and storing generated otps in a list of string and comparing with message.body
Here the problem is we have to send otp two times, still i'm figuring out how to call reading sms part after sometime,,,!
If you want that solution plz mail me at sailokeshgoud#gmail.com
My lwuit application is working fine on Blackberry Simulator while on device the application installs successfully, starts normally, but where am having issues is on network connection. Trying to access network I get 400 Bad Request message. I don't no what am doing wrong, my network connection code is as below:
public ConnectionRequest prepareConnection(String page, String progressMsg, final int request)
{
final ConnectionRequest conR = new ConnectionRequest()
{
public void readResponse(InputStream input) throws IOException {
StringBuffer sb = new StringBuffer();
int ch;
while((ch=input.read()) != -1)
sb.append((char)ch);
httpResponse(sb.toString().trim(), request);
}
};
conR.setUrl(NetworkHandler.getURL()+page);
conR.setDuplicateSupported(true);
Progress progress = new Progress(progressMsg, conR)
{
public void actionCommand(Command command)
{
if(command.getCommandName().equals("Cancel"))
conR.kill();
}
};
conR.setDisposeOnCompletion(progress);
return conR;
}
private void login(String code)
{
Container container = Display.getInstance().getCurrent();
if(!validateLogin(container))
{
showDialogMessage("Alert", "Please enter your user name and password!");
return;
}
NetworkManager.getInstance().start();
ConnectionRequest conR = prepareConnection(NetworkHandler.LOGIN_PAGE, "Authenticating...", RequestType.LOGIN);
Dialog dialog = conR.getDisposeOnCompletion();
conR.setPost(true);
conR.addArgument("u", getFieldValue(findTxtUserName(container)));
conR.addArgument("p", getFieldValue(findTxtPassword(container)));
conR.addArgument("c", code);
NetworkManager.getInstance().addToQueue(conR);
dialog.show();
}
public void onLoginForm_BtnLoginAction(Component c, ActionEvent event) {
login("");
}
Please I want you guys to help me out.
Thanks in Advance.
The login me
This usually indicates a problem in APN configuration on the device. Normally Blackberry app's workaround incorrect APN configurations automatically which is a pretty difficult thing to do. CodenameOne does that seamlessly but LWUIT does not.
There is php page, let's call it http://www.aaaa.org/login.php which has two textboxes (name="username" and name="password") and a button.
And there is my .aspx page from which I want to login to that .php page. Once logged in I want to retrieve and parse some content of a subpage http://www.aaaa.org/details.php?id=1234.
I tried some code but it always retrieves the content of the login.php page so I assume I can't login at all.
Can you show me the exact code how to do this?
The language is C#.
To do this, you can use an HTTPClient library. Something like this:
http://www.codescales.com/
This will enable you to login and access the client application. Note that your application will be fragile and subjected to the web app and it's changes. So if they change the field names, your app will have to change as well. But it will work for what you are trying to achieve.
I would also suggest writing this as a separate library and not directly in your ASPX code.
protected void Page_Load(object sender, EventArgs e)
{
WebClient req = new WebClient();
CredentialCache myCache = new CredentialCache();
//myCache.Add(new Uri("http://www.aaaa.org/login.php"), "Basic", new NetworkCredential("login", "passw"));
myCache.Add(new Uri("http://www.aaaa.org/login.php"), "Digest", new NetworkCredential("login", "passw"));
req.Credentials = myCache;
string results;
results = System.Text.Encoding.UTF8.GetString(req.DownloadData("http://www.aaaa.org/login.php"));
}
protected void Button1_Click(object sender, EventArgs e)
{
string TheUrl = "http://www.aaaa.org/details.php?id=2923";
string response = GetHtmlPage(TheUrl);
TextBox2.Text = response;
}
---------------- updated: -----------------
protected void Page_Load(object sender, EventArgs e)
{
WebClient req = new WebClient();
CredentialCache myCache = new CredentialCache();
myCache.Add(new Uri("http://www.aaaa.org/login.php"), "Basic", new NetworkCredential("login", "passw"));
NameValueCollection postData = new NameValueCollection();
postData.Add("username", "login");
postData.Add("password", "passw");
req.UploadValues("http://www.aaaa.org/login.php", postData);
req.Credentials = myCache;
string results;
results = System.Text.Encoding.UTF8.GetString(req.DownloadData("http://www.aaaa.org/login.php"));
I am implementing an embedded browser in my app, and because it has to be compatible with OS 4.0, BrowserContent is my only choice.
When opening a HTTPS page the screen is blank, but this problem doesn't occur when a BrowserSession is used. So I put a println after the BrowserContent part, and it doesn't show up in the console output. So I think this is something wrong with that.
class BrowserScreen extends MainScreen {
private RenderingSession _renderingSession;
private HttpsConnection _connection;
public BrowserScreen(String url) {
_renderingSession = RenderingSession.getNewInstance();
final String _url = url;
new Thread() {
public void run() {
try {
_connection =
(HttpsConnection)Connector.open(_url, Connector.READ, true);
BrowserContent content =
_renderingSession.getBrowserContent(_connection, null, 0);
content.finishLoading();
Field field = content.getDisplayableContent();
synchronized (UiApplication.getEventLock()) {
add(field);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
}
There is a bug in the sample, and the BB people have done nothing in this regards for years.. You will never know that your page is not rendered and you will be redirected to the calling page all by itself. When they are unable to render the page they insert a redirection code in the HTTP response instead of giving a render exception (check it out in the inputstream and convert it into string and you shall know), and the intended page is never shown. They have resolved this in 5.0 and higher using BrowserField, but we need solution for the low end mobiles.
How do I create a link that will automatically make a user follow a certain Twitter user if they're logged in or send them to Twitter to login first if they're not? I had found how to do this about month or 2 ago but can't find it again. I think it was something basic like a link or a form post to something like twitter.com/[user]/follow.
I've looked at the API, but I'd need the user to authenticate themselves on my site, and I don't want to deal with that. I just want them to authenticate directly on Twitter and not worry about it. The way I had found was nice and simple and I just want to find that again.
Use Twitter's web intents.
While you can use the follow button, you can also send users directly to the Intent URL, like so:
https://twitter.com/intent/user?screen_name=NASA
how to use twitter api in my android application to implement follow button only
Android
http://code.google.com/p/android-hackathon-in-fukuoka/source/browse/trunk/sodefuri/src/jp/jagfukuoka/sodefuri/TimeLineActivity.java?spec=svn167&r=167
Code Snip: (I have converted chines string into standard English)
public class TimeLineActivity extends ListActivity {
private TwitterPreferenceManager tpm = new TwitterPreferenceManager(this);
private static final int FOLLOW = 1;
private static final CharSequence FOLLOW_LABEL = "Follow";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// timeline Obtaining process
String screenName = getIntent().getStringExtra("screen_name");
List<String> list = this.getTimeLine(screenName);
setListAdapter(new ArrayAdapter<String>(this, R.layout.timeline_item,list));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, FOLLOW, 0, FOLLOW_LABEL);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case FOLLOW:
ConfigurationBuilder builder = new ConfigurationBuilder();
Configuration conf = builder.setOAuthAccessToken(tpm.getAccessToken())
.setOAuthAccessTokenSecret(tpm.getAccessTokenSercret())
.setOAuthConsumerKey(TwitterPreferenceManager.CONSUMER_KEY)
.setOAuthConsumerSecret(TwitterPreferenceManager.CONSUMER_SERCRET)
.setDebugEnabled(true)
.build();
Twitter twitter = new TwitterFactory(conf).getInstance();
try {
String screen_name = getIntent().getStringExtra("screen_name");
twitter.createFriendship(screen_name);
Toast.makeText(getApplicationContext(), "Was to follow.", Toast.LENGTH_LONG).show();
} catch (TwitterException e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
/**
* Get the time line for the specified user
*
* #param screenName
* #return
*/
private List<String> getTimeLine(String screenName) {
List<String> result = new ArrayList<String>();
Twitter twitter = new TwitterFactory().getInstance();
ResponseList<Status> userTimeline;
try {
userTimeline = twitter.getUserTimeline(screenName);
for (Status status : userTimeline) {
result.add(status.getText());
}
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
iPhone
http://www.chrismaddern.com/twitter-follow-button-for-ios-iphone-code/
Here is the way, How todo
The FollowMeButton can be created in Interface Builder by adding a UIButton and changing it's class to FollowMeButton or in code using the custom initialiser:
[self.view addSubview:[[FollowMeButton alloc] initWithTwitterAccount:#"chrismaddern" atOrigin:CGPointMake(205, 248) isSmallButton:YES]];
Two size modes are available controlled by setting isSmallButton in the initialiser or by later change the isSmall property of the object.