Pages

Friday 28 December 2012

android get image of contact

use code something like below to get contact id and use contact id to get image

Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);

while (phones.moveToNext()) {
String name = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String ContactId = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));

}

phones.close();
-------------------------------------------------
use below code to get contact image
                                ImageView  imgPeople = new ImageView();
                                Uri my_contact_Uri = Uri.withAppendedPath(
ContactsContract.Contacts.CONTENT_URI,
String.valueOf(ContactId);
InputStream photo_stream = ContactsContract.Contacts
.openContactPhotoInputStream(
mContext.getContentResolver(), my_contact_Uri);
if (photo_stream != null) {
BufferedInputStream buf = new BufferedInputStream(
photo_stream);
Bitmap my_btmp = BitmapFactory.decodeStream(buf);

imgPeople.setImageBitmap(my_btmp);
}

Tuesday 25 December 2012

Android - How to get Height and width of Layout??


You can add a tree observer to the layout. This should return the correct width and height. onCreate is called before the layout of the child views are done. So the width and height is not calculated yet. To get the height and width. Put this on the onCreate method
LinearLayout layout = (LinearLayout)findViewById(R.id.YOUD VIEW ID);
ViewTreeObserver vto = layout.getViewTreeObserver(); 
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
    @Override 
    public void onGlobalLayout() { 
        this.layout.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
        int width  = layout.getMeasuredWidth();
        int height = layout.getMeasuredHeight(); 
    } 
});

Monday 24 December 2012

android move view horizontally on touch in android 2.2

in this project we have to use following animation library.
this library can be downloaded from http://nineoldandroids.com/

please make following layout named activity_main.xml


<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"
    tools:context=".MainActivity"
    android:id="@+id/container" >

    <LinearLayout
        android:id="@+id/llMotion"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:color/darker_gray"
        android:padding="10dp" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:text="@string/hello_world" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="button" />
    </LinearLayout>

</RelativeLayout>


then use following code to move view vertically on touch


package com.example.viewgesture;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.nineoldandroids.view.ViewPropertyAnimator;

public class MainActivity extends Activity  {
private LinearLayout llMotion;
private RelativeLayout llContainer;
private float default_y = 0;
private Boolean moveable = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
llMotion = (LinearLayout) findViewById(R.id.llMotion);
llContainer = (RelativeLayout) findViewById(R.id.container);

llContainer.setOnTouchListener(new OnTouchListener() {

@Override
public boolean onTouch(View v, MotionEvent event) {

float y = event.getY();
int action = event.getAction();
if (action == MotionEvent.ACTION_DOWN && y >= default_y
&& y < (default_y + llMotion.getHeight())) {
moveable = true;
} else if (action == MotionEvent.ACTION_UP && moveable) {
moveable = false;
default_y = y;
} else if (action == MotionEvent.ACTION_MOVE && moveable) {
ViewPropertyAnimator.animate(llMotion).y(y);

}

return true;

}
});

}


}

Thursday 20 December 2012

android textview scrollable without using scrollbar

please use following code for textview without using scrollbar

let me take text view like following


<TextView
        android:id="@+id/txtLandingText"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10dp"
        android:text="@string/description"
        android:scrollbars="vertical"
         />

now in your activity just put following code so your text view will become scroll able


txtDescription = (TextView) findViewById(R.id.txtLandingText);
txtDescription.setMovementMethod(new ScrollingMovementMethod());


Wednesday 19 December 2012

android twitter login using twitter4j

please use following code to login using twitter4j.
it is working fine
 


public class TweetToTwitterActivity extends Activity {
 
        private static final String TAG = "Blundell.TweetToTwitterActivity";
 
        /** Name to store the users access token */
        private static final String PREF_ACCESS_TOKEN = "accessToken";
        /** Name to store the users access token secret */
        private static final String PREF_ACCESS_TOKEN_SECRET = "accessTokenSecret";
        /** Consumer Key generated when you registered your app at https://dev.twitter.com/apps/ */
        private static final String CONSUMER_KEY = "yourConsumerKey";
        /** Consumer Secret generated when you registered your app at https://dev.twitter.com/apps/  */
        private static final String CONSUMER_SECRET = "yourConsumerSecret"; // XXX Encode in your app
        /** The url that Twitter will redirect to after a user log's in - this will be picked up by your app manifest and redirected into this activity */
        private static final String CALLBACK_URL = "tweet-to-twitter-blundell-01-android:///";
        /** Preferences to store a logged in users credentials */
        private SharedPreferences mPrefs;
        /** Twitter4j object */
        private Twitter mTwitter;
        /** The request token signifies the unique ID of the request you are sending to twitter  */
        private RequestToken mReqToken;
 
        private Button mLoginButton;
        private Button mTweetButton;
 
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                Log.i(TAG, "Loading TweetToTwitterActivity");
                setContentView(R.layout.main);
               
                // Create a new shared preference object to remember if the user has
                // already given us permission
                mPrefs = getSharedPreferences("twitterPrefs", MODE_PRIVATE);
                Log.i(TAG, "Got Preferences");
               
                // Load the twitter4j helper
                mTwitter = new TwitterFactory().getInstance();
                Log.i(TAG, "Got Twitter4j");
               
                // Tell twitter4j that we want to use it with our app
                mTwitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
                Log.i(TAG, "Inflated Twitter4j");
               
                mLoginButton = (Button) findViewById(R.id.login_button);
                mTweetButton = (Button) findViewById(R.id.tweet_button);
        }
 
        /**
         * Button clickables are declared in XML as this projects min SDK is 1.6</br> </br>
         * Checks if the user has given this app permission to use twitter
         * before</br> If so login and enable tweeting</br>
         * Otherwise redirect to Twitter for permission
         *
         * @param v the clicked button
         */
        public void buttonLogin(View v) {
                Log.i(TAG, "Login Pressed");
                if (mPrefs.contains(PREF_ACCESS_TOKEN)) {
                        Log.i(TAG, "Repeat User");
                        loginAuthorisedUser();
                } else {
                        Log.i(TAG, "New User");
                        loginNewUser();
                }
        }
 
        /**
         * Button clickables are declared in XML as this projects min SDK is 1.6</br> </br>
         *
         * @param v the clicked button
         */
        public void buttonTweet(View v) {
                Log.i(TAG, "Tweet Pressed");
                tweetMessage();
        }
 
        /**
         * Create a request that is sent to Twitter asking 'can our app have permission to use Twitter for this user'</br>
         * We are given back the {@link mReqToken}
         * that is a unique indetifier to this request</br>
         * The browser then pops up on the twitter website and the user logins in ( we never see this informaton
         * )</br> Twitter then redirects us to {@link CALLBACK_URL} if the login was a success</br>
         *
         */
        private void loginNewUser() {
                try {
                        Log.i(TAG, "Request App Authentication");
                        mReqToken = mTwitter.getOAuthRequestToken(CALLBACK_URL);
 
                        Log.i(TAG, "Starting Webview to login to twitter");
                        WebView twitterSite = new WebView(this);
                        twitterSite.loadUrl(mReqToken.getAuthenticationURL());
                        setContentView(twitterSite);
 
                } catch (TwitterException e) {
                        Toast.makeText(this, "Twitter Login error, try again later", Toast.LENGTH_SHORT).show();
                }
        }
 
        /**
         * The user had previously given our app permission to use Twitter</br>
         * Therefore we retrieve these credentials and fill out the Twitter4j helper
         */
        private void loginAuthorisedUser() {
                String token = mPrefs.getString(PREF_ACCESS_TOKEN, null);
                String secret = mPrefs.getString(PREF_ACCESS_TOKEN_SECRET, null);
 
                // Create the twitter access token from the credentials we got previously
                AccessToken at = new AccessToken(token, secret);
 
                mTwitter.setOAuthAccessToken(at);
               
                Toast.makeText(this, "Welcome back", Toast.LENGTH_SHORT).show();
               
                enableTweetButton();
        }
 
        /**
         * Catch when Twitter redirects back to our {@link CALLBACK_URL}</br>
         * We use onNewIntent as in our manifest we have singleInstance="true" if we did not the
         * getOAuthAccessToken() call would fail
         */
        @Override
        protected void onNewIntent(Intent intent) {
                super.onNewIntent(intent);
                Log.i(TAG, "New Intent Arrived");
                dealWithTwitterResponse(intent);
        }
 
        @Override
        protected void onResume() {
                super.onResume();
                Log.i(TAG, "Arrived at onResume");
        }
       
        /**
         * Twitter has sent us back into our app</br>
         * Within the intent it set back we have a 'key' we can use to authenticate the user
         *
         * @param intent
         */
        private void dealWithTwitterResponse(Intent intent) {
                Uri uri = intent.getData();
                if (uri != null && uri.toString().startsWith(CALLBACK_URL)) { // If the user has just logged in
                        String oauthVerifier = uri.getQueryParameter("oauth_verifier");
 
                        authoriseNewUser(oauthVerifier);
                }
        }
 
        /**
         * Create an access token for this new user</br>
         * Fill out the Twitter4j helper</br>
         * And save these credentials so we can log the user straight in next time
         *
         * @param oauthVerifier
         */
        private void authoriseNewUser(String oauthVerifier) {
                try {
                        AccessToken at = mTwitter.getOAuthAccessToken(mReqToken, oauthVerifier);
                        mTwitter.setOAuthAccessToken(at);
 
                        saveAccessToken(at);
 
                        // Set the content view back after we changed to a webview
                        setContentView(R.layout.main);
                       
                        enableTweetButton();
                } catch (TwitterException e) {
                        Toast.makeText(this, "Twitter auth error x01, try again later", Toast.LENGTH_SHORT).show();
                }
        }
 
        /**
         * Allow the user to Tweet
         */
        private void enableTweetButton() {
                Log.i(TAG, "User logged in - allowing to tweet");
                mLoginButton.setEnabled(false);
                mTweetButton.setEnabled(true);
        }
 
        /**
         * Send a tweet on your timeline, with a Toast msg for success or failure
         */
        private void tweetMessage() {
                try {
                        mTwitter.updateStatus("Test - Tweeting with @Blundell_apps #AndroidDev Tutorial using #Twitter4j http://blog.blundell-apps.com/sending-a-tweet");
 
                        Toast.makeText(this, "Tweet Successful!", Toast.LENGTH_SHORT).show();
                } catch (TwitterException e) {
                        Toast.makeText(this, "Tweet error, try again later", Toast.LENGTH_SHORT).show();
                }
        }
 
        private void saveAccessToken(AccessToken at) {
                String token = at.getToken();
                String secret = at.getTokenSecret();
                Editor editor = mPrefs.edit();
                editor.putString(PREF_ACCESS_TOKEN, token);
                editor.putString(PREF_ACCESS_TOKEN_SECRET, secret);
                editor.commit();
        }
}

Sorting arraylist in Android in alphabetical order

suppose we have array list of User
User class have following params
param : 
 uid
 name
 address 

suppose ArrayList<User> users  has many values and we want it to sory by name then use following code.

Collections.sort(users, new Comparator<User>() {
        @Override
        public int compare(User u1, User u2) {
            return u1.name.compareToIgnoreCase(u2.name);           
        }
    });

above code will sort users array by name.