Skip to main content

Twitter integration with upload pic and update status

Twitter integration with upload pic and status

Here is the example of twitter integration with upload pic and status update:



ConnectActivity .java
public class ConnectActivity extends Activity {
    private TwitterApp mTwitter;
    private CheckBox mTwitterBtn;

    private static final String twitter_consumer_key = "YOUR CONSUMER KEY";
    private static final String twitter_secret_key = "YOUR SECRET KEY";
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
        setContentView(R.layout.activity_connect);

        mTwitterBtn    = (CheckBox) findViewById(R.id.twitterCheck);
       
        mTwitterBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onTwitterClick();
            }
        });
       
        mTwitter = new TwitterApp(this, twitter_consumer_key,twitter_secret_key);
       
        mTwitter.setListener(mTwLoginDialogListener);
       
        if (mTwitter.hasAccessToken()) {
            mTwitterBtn.setChecked(true);
           
            String username = mTwitter.getUsername();
            username        = (username.equals("")) ? "Unknown" : username;
           
            mTwitterBtn.setText("  Twitter (" + username + ")");
            mTwitterBtn.setTextColor(Color.WHITE);
        }
       
        Button goBtn = (Button) findViewById(R.id.button1);
       
        goBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mTwitter.hasAccessToken())
                    startActivity(new Intent(ConnectActivity.this, SendImageActivity.class));
                else
                    Toast.makeText(getApplicationContext(), "Please connect your Twitter account first!",
                            Toast.LENGTH_SHORT).show();
            }
        });
    }
   
    private void onTwitterClick() {
        if (mTwitter.hasAccessToken()) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(this);
           
            builder.setMessage("Delete current Twitter connection?")
                   .setCancelable(false)
                   .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int id) {
                           mTwitter.resetAccessToken();
                          
                           mTwitterBtn.setChecked(false);
                           mTwitterBtn.setText("  Twitter (Not connected)");
                           mTwitterBtn.setTextColor(Color.GRAY);
                       }
                   })
                   .setNegativeButton("No", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                           
                            mTwitterBtn.setChecked(true);
                       }
                   });
            final AlertDialog alert = builder.create();
           
            alert.show();
        } else {
            mTwitterBtn.setChecked(false);
           
            mTwitter.authorize();
        }
    }

    private final TwDialogListener mTwLoginDialogListener = new TwDialogListener() {
        @Override
        public void onComplete(String value) {
            String username = mTwitter.getUsername();
            username        = (username.equals("")) ? "No Name" : username;
       
            mTwitterBtn.setText("  Twitter  (" + username + ")");
            mTwitterBtn.setChecked(true);
            mTwitterBtn.setTextColor(Color.WHITE);
           
            Toast.makeText(ConnectActivity.this, "Connected to Twitter as " + username, Toast.LENGTH_LONG).show();
        }
       
        @Override
        public void onError(String value) {
            mTwitterBtn.setChecked(false);
           
            Toast.makeText(ConnectActivity.this, "Twitter connection failed", Toast.LENGTH_LONG).show();
        }
    };
}

SendImageActivity .java
public class SendImageActivity extends Activity {
    private Uri mImageCaptureUri;
    private ImageView mImageView;
    private ProgressDialog mProgressDialog;
   
    private String mPath;
   
    private static final int PICK_FROM_CAMERA = 1;
    private static final int PICK_FROM_FILE = 2;
    //private static final String twitpic_api_key = "337028435-sTix32KP5GPNuIOxg1GCosUYYDkQ0dGRlM9xBv7U";
    private static final String twitpic_api_key = "c2ec92824f6e0ae709e7f8723bed1126";
    private static final String twitter_consumer_key = "VQjQ4TzXGcuJlBDhcQOHlQ";
    private static final String twitter_secret_key = "RYmULjSRfzRvq8w5ApJCxSyqMaRbMIVihcmUEmI0";
   
    private static final String TAG = "AndroidTwitpic";
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
        setContentView(R.layout.activity_send_image);
       
        final String [] items            = new String [] {"From Camera", "From SD Card"};               
        ArrayAdapter<String> adapter    = new ArrayAdapter<String> (this, android.R.layout.select_dialog_item,items);
        AlertDialog.Builder builder        = new AlertDialog.Builder(this);
       
        builder.setTitle("Select Image");
        builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
            public void onClick( DialogInterface dialog, int item ) {
                if (item == 0) {
                    Intent intent      = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File file         = new File(Environment.getExternalStorageDirectory(),
                                           "tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
                    mImageCaptureUri = Uri.fromFile(file);

                    try {           
                        intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
                        intent.putExtra("return-data", true);
                       
                        startActivityForResult(intent, PICK_FROM_CAMERA);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }           
                   
                    dialog.cancel();
                } else {
                    Intent intent = new Intent();
                   
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                   
                    startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
                }
            }
        } );
       
        final AlertDialog dialog = builder.create();
       
        TwitterApp twitterApp = new TwitterApp(this, twitter_consumer_key,twitter_secret_key);
       
        if (twitterApp.hasAccessToken()) {
            String username     = twitterApp.getUsername();
            username            = (username.equals("")) ? "No Name" : username;
           
            ((TextView) findViewById(R.id.tv_user)).setText("Current Twitter User: "+ username);
        }
       
        mImageView = (ImageView) findViewById(R.id.iv_pic);
       
        ((Button) findViewById(R.id.btn_choose)).setOnClickListener(new View.OnClickListener() {           
            @Override
            public void onClick(View v) {
                dialog.show();
            }
        });
       
        ((Button) findViewById(R.id.btn_send)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               
                long result = 0;
               
                TwitterSession twitterSession    = new TwitterSession(SendImageActivity.this);           
                AccessToken accessToken         = twitterSession.getAccessToken();
               
                Configuration conf = new ConfigurationBuilder()                
                .setOAuthConsumerKey(twitter_consumer_key)
                .setOAuthConsumerSecret(twitter_secret_key)
                .setOAuthAccessToken(accessToken.getToken())
                .setOAuthAccessTokenSecret(accessToken.getTokenSecret())
                .build();
               
                Twitter twitter = new TwitterFactory(conf).getInstance();
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                Bitmap bitmap = BitmapFactory.decodeFile(mPath, options);
               
                Bitmap bmp = BitmapFactory.decodeResource(
                        SendImageActivity.this.getResources(), R.drawable.icon);
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
                byte[] byteArray = stream.toByteArray();
                ByteArrayInputStream bis = new ByteArrayInputStream(byteArray);
                StatusUpdate status = new StatusUpdate("hi");
                status.setMedia("newyear", bis);

                try {
                    twitter.updateStatus(status);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //new ImageSender().execute();
            }
        });       
    }
   
    private class ImageSender extends AsyncTask<URL, Integer, Long> {
        private String url;
       
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(SendImageActivity.this, "", "Sending image...", true);
           
            mProgressDialog.setCancelable(false);
            mProgressDialog.show();
        }
       
        protected Long doInBackground(URL... urls) {         
           
           
           
            long result = 0;
                      
            TwitterSession twitterSession    = new TwitterSession(SendImageActivity.this);           
            AccessToken accessToken         = twitterSession.getAccessToken();
           
            Configuration conf = new ConfigurationBuilder()                
            .setOAuthConsumerKey(twitter_consumer_key)
            .setOAuthConsumerSecret(twitter_secret_key)
            .setOAuthAccessToken(accessToken.getToken())
            .setOAuthAccessTokenSecret(accessToken.getTokenSecret())
            .build();
           
            OAuthAuthorization auth = new OAuthAuthorization (conf);
           
           // ImageUpload upload = ImageUpload.getTwitpicUploader (twitpic_api_key, auth);
            ImageUpload upload = null;
           
            Log.d(TAG, "Start sending image...");
           
            try {
                url = upload.upload(new File(mPath));
                result = 1;
               
                Log.d(TAG, "Image uploaded, Twitpic url is " + url);           
            } catch (Exception e) {          
                Log.e(TAG, "Failed to send image");
               
                e.printStackTrace();
            }
           
            return result;
        }

        protected void onProgressUpdate(Integer... progress) {           
        }

        protected void onPostExecute(Long result) {
            mProgressDialog.cancel();
           
            String text = (result == 1) ? "Image sent successfully.\n Twitpic url is: " + url : "Failed to send image";
           
            Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) return;
      
        Bitmap bitmap     = null;
       
        if (requestCode == PICK_FROM_FILE) {
            mImageCaptureUri = data.getData();
            mPath = getRealPathFromURI(mImageCaptureUri); //from Gallery
       
            if (mPath == null)
                mPath = mImageCaptureUri.getPath(); //from File Manager
           
            if (mPath != null)
                bitmap     = BitmapFactory.decodeFile(mPath);
        } else {
            mPath    = mImageCaptureUri.getPath();
            bitmap  = BitmapFactory.decodeFile(mPath);
        }
           
        mImageView.setImageBitmap(bitmap);       
    }
   
    public String getRealPathFromURI(Uri contentUri) {
        String [] proj         = {MediaStore.Images.Media.DATA};
        Cursor cursor         = managedQuery( contentUri, proj, null, null,null);
       
        if (cursor == null) return null;
       
        int column_index     = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
       
        cursor.moveToFirst();

        return cursor.getString(column_index);
    }
   
}


twitter_check.xml

<?xml version="1.0" encoding="UTF-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_checked="true"
        android:state_window_focused="true"
         android:state_enabled="true"
         android:drawable="@drawable/twitter_check_on" />

    <item
        android:state_checked="false"
        android:state_window_focused="true"
         android:state_enabled="true"
         android:drawable="@drawable/twitter_check_off" />
</selector>



activity_connect.xml


<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp">

      <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="32sp"
        android:textStyle="bold"
        android:text="TWITTER ACCOUNT"/>
       
    <CheckBox
        android:id="@+id/twitterCheck"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="5dp"
        android:text="  Twitter (Not connected) "
        android:textSize="14sp"
        android:textStyle="bold"
        android:textColor="#ccc"
        android:clickable="true"
        android:focusable="true"
        android:button="@drawable/twitter_check"/>
   
    <Button
        android:id="@+id/button1"
        android:layout_marginTop="20dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text=" Send Image to Twitpic" />

</LinearLayout>


activity_send_image.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"   
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp">
   
    <TextView 
        android:id="@+id/tv_title"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:textSize="35sp"
        android:text="SEND TO TWITPIC"/>
   
    <TextView
        android:id="@+id/tv_user" 
        android:layout_below="@id/tv_title"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Current Twitter User:"
        android:layout_marginTop="10dp"/>
           
    <Button
        android:id="@+id/btn_choose"
        android:layout_below="@id/tv_user"
        android:text="Choose Image"        
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"/>
       
    <Button
        android:id="@+id/btn_send"
        android:layout_below="@id/tv_user"
        android:layout_toRightOf="@id/btn_choose"
        android:text="Send to Twitpic"        
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"/>
       
    <ImageView
        android:id="@+id/iv_pic"
        android:background="@drawable/icon"
        android:layout_below="@id/btn_choose"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"       
        android:layout_marginTop="10dp"/>
       
</RelativeLayout>

you have to add two jar files in libs folder.
you can download the jars from the following links:
http://www.4shared.com/rar/_EVk23_e/jars_twitter.html

Comments

Popular posts from this blog

Custom camera using SurfaceView android with autofocus & auto lights & more

Custom camera using SurfaceView android with autofocus & auto lights & much more /**  * @author Tatyabhau Chavan  *  */ public class Preview extends SurfaceView implements SurfaceHolder.Callback {     private SurfaceHolder mHolder;     private Camera mCamera;     public Camera.Parameters mParameters;     private byte[] mBuffer;     private Activity mActivity;     // this constructor used when requested as an XML resource     public Preview(Context context, AttributeSet attrs) {         super(context, attrs);         init();     }     public Preview(Context context) {         super(context);         init();     }     public Camera getCamera() {         return this.mCamera;     }     public void init() {         // Install a SurfaceHolder.Callback so we get notified when the         // underlying surface is created and destroyed.         mHolder = getHolder();         mHolder.addCallback(this);         mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);     }     public

Get Android phone call history/log programmatically

Get Android phone call history/log programmatically To get call history programmatically first add read conact permission in Manifest file : <uses-permission android:name="android.permission.READ_CONTACTS" /> Create xml file. Add the below code in xml file : <Linearlayout android:layout_height="fill_parent"  android:layout_width="fill_parent" android:orientation="vertical"> <Textview android:id="@+id/call" android:layout_height="fill_parent" android:layout_width="fill_parent"> </Textview> </Linearlayout> Now call the getCallDetails() method in java class : private void getCallDetails() { StringBuffer sb = new StringBuffer(); Cursor managedCursor = managedQuery( CallLog.Calls.CONTENT_URI,null, null,null, null); int number = managedCursor.getColumnIndex( CallLog.Calls.NUMBER ); int type = managedCursor.getColumnIndex( CallLog.Calls.TYPE ); int date = managedCur

Bitmap scalling and cropping from center

How to Bitmap scalling and cropping from center? public class ScalingUtilities {     /**      * Utility function for decoding an image resource. The decoded bitmap will      * be optimized for further scaling to the requested destination dimensions      * and scaling logic.      *      * @param res      *            The resources object containing the image data      * @param resId      *            The resource id of the image data      * @param dstWidth      *            Width of destination area      * @param dstHeight      *            Height of destination area      * @param scalingLogic      *            Logic to use to avoid image stretching      * @return Decoded bitmap      */     public static Bitmap decodeResource(Resources res, int resId, int dstWidth,             int dstHeight, ScalingLogic scalingLogic) {         Options options = new Options();         options.inJustDecodeBounds = true;         BitmapFactory.decodeResource(res, resId, options);