Monday, February 18, 2013

jTwitter Authorization in Android with AsyncTask

In this post we ll see how to authorize an android app using jTwitter library for Twitter. We are going to use AsyncTask to achieve this because from Honeycomb you are not allowed to do network operations in the main thread. So we ll create an asynctask which will run in the background to do this. jTwitter is a library which is simple and easy to use. I assume that you know basics of android application development.
Lets get started.

Main_Activity.xml
The layout is pretty simple we just have a button which ll initiate the authorization process.


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >


    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignRight="@+id/textView1"
        android:layout_marginTop="89dp"
        android:text="Authorize" />


</RelativeLayout>


AndroidManifest.xml

In the manifest we just add some permissions required and an intent filter for callback.

<uses-permission android:name="android.permission.INTERNET" />

<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="myapp" android:host="twitt"/>
            </intent-filter>


MainActivity.java

In the java class we just create an onClickListener for our button in which we ask our AsyncTask to start the execution. We also create our AsyncTask which has three methods. They are self explanatory. One important thing that you got to remember is never do any UI related operation in the doInBackground() function. If you need to do some UI operation do it in preExecute() or postExecute(). Doing UI operations in  doInBackground() will throw exceptions.
And about the consumerKey and consumerSecret, you will get them when you register your application with twitter in dev.twitter.com.

import oauth.signpost.OAuth;
import winterwell.jtwitter.OAuthSignpostClient;
import winterwell.jtwitter.Twitter;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class SampleActivity extends Activity {

Twitter twitter = null;
private Button postBtn = null;

private OAuthSignpostClient client = null;
private String CALLBACK_URI = "myapp://twitt";

private String authUrl = null;
String[] accessTokenandSecret=null;
String consumerKey="place consumer key";
String consumerSecret="place consumer secret";
String verifier;
@Override
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
postBtn=(Button)findViewById(R.id.button1);
postBtn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
new MyTask().execute();
}
});

}
private class GetToken extends AsyncTask<Void, Void, Void> {

protected void onPreExecute() {
Toast.makeText(getApplicationContext(), "pre execute get token", Toast.LENGTH_LONG).show();
}

@Override
protected Void doInBackground(Void... arg0) {
try{
client.setAuthorizationCode(verifier);
accessTokenandSecret=client.getAccessToken();
client=new OAuthSignpostClient(consumerKey, consumerSecret, accessTokenandSecret[0], accessTokenandSecret[1]);
}
catch(Exception e)
{
Log.d("Exception token", ""+e.getMessage());
}
return null;
}

@Override
protected void onPostExecute(Void result) {
Toast.makeText(getApplicationContext(), "post execute get token ", Toast.LENGTH_LONG).show();
}
}

private class MyTask extends AsyncTask<Void, Void, Void> {

protected void onPreExecute() {
Toast.makeText(getApplicationContext(), "pre execute", Toast.LENGTH_LONG).show();
}

@Override
protected Void doInBackground(Void... arg0) {
client = new OAuthSignpostClient(consumerKey ,consumerSecret, CALLBACK_URI);

authUrl = client.authorizeUrl().toString();
Intent intent=new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(intent);
return null;
}

@Override
protected void onPostExecute(Void result) {
Toast.makeText(getApplicationContext(), "post execute", Toast.LENGTH_LONG).show();
}
}
protected void onNewIntent(Intent intent) {

super.onNewIntent(intent);
Uri uri = intent.getData();
//Check if you got NewIntent event due to Twitter Call back only
if (uri != null && uri.toString().startsWith(CALLBACK_URI))
{
try
{
verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
Toast.makeText(getApplicationContext(), "inside verfier", Toast.LENGTH_LONG).show();
new GetToken().execute();
}
catch(Exception e){
Log.d("exception", " "+e.getMessage());
}
}}
}




Sunday, January 20, 2013

Function to convert 'mm/dd/yyyy' to 'dd-mon-yy' in c#


string da=datePicker1.SelectedDate.ToString().Split(' ')[0];
                    //MessageBox.Show(da);
                    string dat = da.Split('/')[1];
                    if (dat.Length == 1)
                    {
                        dat = "0" + dat;
                    }

                     string y = da.Split('/')[2];
                    string mont = null;
                    int mon = int.Parse(da.Split('/')[0]);
                    switch (mon)
                    {
                        case 1:
                            mont = "Jan";
                            break;
                        case 2:
                            mont = "Feb";
                            break;
                        case 3:
                            mont = "Mar";
                            break;
                        case 4:
                            mont = "Apr";
                            break;
                        case 5:
                            mont = "May";
                            break;
                        case 6:
                            mont = "Jun";
                            break;
                        case 7:
                            mont = "Jul";
                            break;
                        case 8:
                            mont = "Aug";
                            break;
                        case 9:
                            mont = "Sep";
                            break;
                        case 10:
                            mont = "Oct";
                            break;
                        case 11:
                            mont = "Nov";
                            break;
                        case 12:
                            mont = "Dec";
                            break;
                    }
                    char[] y1 = y.ToCharArray();
                    string y2 = y1[2].ToString() + y1[3].ToString();
                    string daSearch = dat + "-" + mont + "-" + y2;