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

Volley for client and server interaction (Android)

Volley provides client and server interaction with QUEUE basis, each and every request process separately, we can cancel our request from QUEUE. HERE is a code sample for Volley with json request format. GenerateRequest.java -------------------------------------------------------------------- package com.entrata.maintenance.network_communication.networkutils; import android.content.Context; import com.android.volley.AuthFailureError; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.entrata.maintenance.application.ERPUserDefaults; import com.entrata.maintenance.network_communication.networkconstant.NetworkConstant; import com.entrata.maintenance.network_communication.networkexception.Error; import com.entrata.maintenance.network_communication.networkutil.SubdomainChange; import com.entrata.maintenance.utils.Logger; import com.google.gson.Gson; import org.json.JSONException; import org.js...
Java Code Examples for javax.net.ssl.HttpsURLConnection The following code examples are extracted from open source projects. You can click to vote up the examples you like. Your votes will be used in an intelligent system to get more and better code examples. Thanks for your votes! Code Example 1:   9  From project ADFS , under directory /adfs-hdfs-project/adfs-hdfs/src/main/java/org/apache/hadoop/hdfs/ . Source HsftpFileSystem.java @Override protected HttpURLConnection openConnection ( String path , String query ) throws IOException { query = addDelegationTokenParam ( query ); final URL url = new URL ( "https" , nnAddr . getHostName (), nnAddr . getPort (), path + '?' + query ); HttpsURLConnection conn =( HttpsURLConnection ) url . openConnection (); conn . setHostnameVerifier ( new DummyHostnameVerifier ()); return ( HttpURLConnection ) conn ; } Code Example 2:  ...

Improving Layout Performance

Improving Layout Performance Layouts are a key part of Android applications that directly affect the user experience. If implemented poorly, your layout can lead to a memory hungry application with slow UIs. The Android SDK includes tools to help you identify problems in your layout performance, which when combined the lessons here, you will be able to implement smooth scrolling interfaces with a minimum memory footprint. Lessons Optimizing Layout Hierarchies In the same way a complex web page can slow down load time, your layout hierarchy if too complex can also cause performance problems. This lesson shows how you can use SDK tools to inspect your layout and discover performance bottlenecks. Re-using Layouts with <include/> If your application UI repeats certain layout constructs in multiple places, this lesson shows you how to create efficient, re-usable layout constructs, then include them in the appropriate UI layouts. Loading Views On Demand Be...