Friday 9 March 2012

twitter integration

need to use to call when click on twitter button
TestPost.java
package your package name;


import yourpackagename.TwitterApp.TwDialogListener;
import android.app.Activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import android.text.InputFilter;
import android.text.Spanned;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;

import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.Button;

public class TestPost extends Activity {
    private TwitterApp mTwitter;
    private CheckBox mTwitterBtn;
    private String username = "";
    private boolean postToTwitter = false;
    Button postBtn;
    EditText reviewEdit;
    String review;
    public String title1,desc1,imagurl1,fburl1;
    private static final String twitter_consumer_key = "your consumer key";
    private static final String twitter_secret_key = "consumer secret";
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
        setContentView(R.layout.post);
        Bundle b=new Bundle();
        b=this.getIntent().getExtras();
        title1=b.getString("title");
        desc1=b.getString("desc");
        fburl1=b.getString("fb_url");
        Button back=(Button)findViewById(R.id.back);
        back.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                finish();
            }});
        postBtn = (Button) findViewById(R.id.button1);
        postBtn.setGravity(Gravity.CENTER_HORIZONTAL);
        reviewEdit   = (EditText) findViewById(R.id.revieew);
        postBtn.setVisibility(View.GONE);
        review="";
        reviewEdit.setVisibility(View.GONE);
    /*    reviewEdit.setFilters(new InputFilter[] {
                new InputFilter() {
                    @Override
                    public CharSequence filter(CharSequence source, int start,
                            int end, Spanned dest, int dstart, int dend) {
                        // TODO Auto-generated method stub
                        return source.length() < 1 ? dest.subSequence(dstart, dend) : "";
                    }
                }
            });*/
        postBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                review = reviewEdit.getText().toString();
               
                if (review.equals(""))
                    return;
                else{
                    mTwitterBtn.setChecked(true);
                    //mTwitterBtn.setVisibility(View.INVISIBLE);
                postToTwitter=true;
                }
                //postReview(review);
                System.out.println("++"+postToTwitter);
                if (postToTwitter) postToTwitter(review);
            }
        });

        mTwitter = new TwitterApp(this, twitter_consumer_key,twitter_secret_key);
       
        mTwitter.setListener(mTwLoginDialogListener);

        mTwitterBtn    = (CheckBox) findViewById(R.id.twitterCheck);

        mTwitterBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mTwitter.hasAccessToken()) {
                    postToTwitter = mTwitterBtn.isChecked();
                    postBtn.setVisibility(View.GONE);
                    reviewEdit.setText("Check out this deal from on"+"\n"+"http://"+fburl1);
                                   } else {
                    mTwitterBtn.setChecked(false);
                   
                    mTwitter.authorize();
                }
            }
        });
       
        if (mTwitter.hasAccessToken()) {
            username     = mTwitter.getUsername();
            username    = (username.equals("")) ? "No Name" : username;
            postBtn.setVisibility(View.VISIBLE);
            reviewEdit.setText("Check out this deal from on "+"\n"+"http://"+fburl1);
            mTwitterBtn.setVisibility(View.GONE);
            reviewEdit.setVisibility(View.VISIBLE);
            //mTwitterBtn.setText("  Twitter  (" + username + ")");
        }
    }
   
    private void postReview(String review) {
        //post to server
       
        Toast.makeText(this, "Review posted", Toast.LENGTH_SHORT).show();
    }
   
    private void postToTwitter(final String review) {
        new Thread() {
            @Override
            public void run() {
                int what = 0;
               
                try {
                    mTwitter.updateStatus(review);
                } catch (Exception e) {
                    what = 1;
                }
               
                mHandler.sendMessage(mHandler.obtainMessage(what));
            }
        }.start();
    }
   
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String text = (msg.what == 0) ? "Blitz posted successfully..." : "Tweet has been already posted...";
            Toast.makeText(TestPost.this, text, Toast.LENGTH_SHORT).show();
        }
    };
    private final TwDialogListener mTwLoginDialogListener = new TwDialogListener() {
        @Override
        public void onComplete(String value) {
            reviewEdit.setVisibility(View.VISIBLE);
            username     = mTwitter.getUsername();
            username    = (username.equals("")) ? "No Name" : username;
            postBtn.setVisibility(View.GONE);
            mTwitterBtn.setText("  (" + username + ")");
            reviewEdit.setText("Check out this deal from on !"+"\n"+"http://"+fburl1);
            postBtn.setVisibility(View.VISIBLE);
            mTwitterBtn.setChecked(true);
           
            postToTwitter = true;
           
            Toast.makeText(TestPost.this, "Connected to Twitter as " + username, Toast.LENGTH_LONG).show();
        }
       
        @Override
        public void onError(String value) {
            mTwitterBtn.setChecked(false);
           
            Toast.makeText(TestPost.this, "Twitter connection failed", Toast.LENGTH_LONG).show();
        }
    };

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
       
    }
   
}
///////////////////////////

TwitterApp.java

/**
 * @author Lorensius W. L. T <lorenz@londatiga.net>
 *
 * Website: http://www.londatiga.net
 */

package blizit.app;

import java.net.MalformedURLException;
import java.net.URLDecoder;

import oauth.signpost.OAuthProvider;
import oauth.signpost.basic.DefaultOAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.http.AccessToken;
import twitter4j.User;

import android.os.Handler;
import android.os.Message;

import android.app.ProgressDialog;
import android.content.Context;
import android.util.Log;
import android.view.Window;

import java.net.URL;

public class TwitterApp {
    private Twitter mTwitter;
    private TwitterSession mSession;
    private AccessToken mAccessToken;
    private CommonsHttpOAuthConsumer mHttpOauthConsumer;
    private OAuthProvider mHttpOauthprovider;
    private String mConsumerKey;
    private String mSecretKey;
    private ProgressDialog mProgressDlg;
    private TwDialogListener mListener;
    private Context context;
   
    public static final String CALLBACK_URL = "twitterapp://connect";
    private static final String TAG = "TwitterApp";
   
    public TwitterApp(Context context, String consumerKey, String secretKey) {
        this.context    = context;
      
        mTwitter         = new TwitterFactory().getInstance();
        mSession        = new TwitterSession(context);
        mProgressDlg    = new ProgressDialog(context);
      
        mProgressDlg.requestWindowFeature(Window.FEATURE_NO_TITLE);
      
        mConsumerKey     = consumerKey;
        mSecretKey         = secretKey;
   
        mHttpOauthConsumer = new CommonsHttpOAuthConsumer(mConsumerKey, mSecretKey);
        mHttpOauthprovider = new DefaultOAuthProvider("http://twitter.com/oauth/request_token",
                                                     "http://twitter.com/oauth/access_token",
                                                     "http://twitter.com/oauth/authorize");
      
        mAccessToken    = mSession.getAccessToken();
      
        configureToken();
    }
   
    public void setListener(TwDialogListener listener) {
        mListener = listener;
    }
   
    @SuppressWarnings("deprecation")
    private void configureToken() {
        if (mAccessToken != null) {
            mTwitter.setOAuthConsumer(mConsumerKey, mSecretKey);
          
            mTwitter.setOAuthAccessToken(mAccessToken);
        }
    }
   
    public boolean hasAccessToken() {
        return (mAccessToken == null) ? false : true;
    }
   
    public void resetAccessToken() {
        if (mAccessToken != null) {
            mSession.resetAccessToken();
      
            mAccessToken = null;
        }
    }
   
    public String getUsername() {
        return mSession.getUsername();
    }
   
    public void updateStatus(String status) throws Exception {
        try {
            mTwitter.updateStatus(status);
        } catch (TwitterException e) {
            throw e;
        }
    }
   
    public void authorize() {
        mProgressDlg.setMessage("Initializing ...");
        mProgressDlg.show();
      
        new Thread() {
            @Override
            public void run() {
                String authUrl = "";
                int what = 1;
              
                try {
                    authUrl = mHttpOauthprovider.retrieveRequestToken(mHttpOauthConsumer, CALLBACK_URL);  
                  
                    what = 0;
                  
                    Log.d(TAG, "Request token url " + authUrl);
                } catch (Exception e) {
                    Log.d(TAG, "Failed to get request token");
                  
                    e.printStackTrace();
                }
              
                mHandler.sendMessage(mHandler.obtainMessage(what, 1, 0, authUrl));
            }
        }.start();
    }
   
    public void processToken(String callbackUrl)  {
        mProgressDlg.setMessage("Finalizing ...");
        mProgressDlg.show();
      
        final String verifier = getVerifier(callbackUrl);

        new Thread() {
            @Override
            public void run() {
                int what = 1;
              
                try {
                    mHttpOauthprovider.retrieveAccessToken(mHttpOauthConsumer, verifier);
      
                    mAccessToken = new AccessToken(mHttpOauthConsumer.getToken(), mHttpOauthConsumer.getTokenSecret());
              
                    configureToken();
              
                    User user = mTwitter.verifyCredentials();
              
                    mSession.storeAccessToken(mAccessToken, user.getName());
                  
                    what = 0;
                } catch (Exception e){
                    Log.d(TAG, "Error getting access token");
                  
                    e.printStackTrace();
                }
              
                mHandler.sendMessage(mHandler.obtainMessage(what, 2, 0));
            }
        }.start();
    }
   
    private String getVerifier(String callbackUrl) {
        String verifier     = "";
      
        try {
            callbackUrl = callbackUrl.replace("twitterapp", "http");
          
            URL url         = new URL(callbackUrl);
            String query     = url.getQuery();
      
            String array[]    = query.split("&");

            for (String parameter : array) {
                 String v[] = parameter.split("=");
               
                 if (URLDecoder.decode(v[0]).equals(oauth.signpost.OAuth.OAUTH_VERIFIER)) {
                     verifier = URLDecoder.decode(v[1]);
                     break;
                 }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
      
        return verifier;
    }
   
    private void showLoginDialog(String url) {
        final TwDialogListener listener = new TwDialogListener() {
            @Override
            public void onComplete(String value) {
                processToken(value);
            }
          
            @Override
            public void onError(String value) {
                mListener.onError("Failed opening authorization page");
            }
        };
      
        new TwitterDialog(context, url, listener).show();
    }
   
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            mProgressDlg.dismiss();
          
            if (msg.what == 1) {
                if (msg.arg1 == 1)
                    mListener.onError("Error getting request token");
                else
                    mListener.onError("Error getting access token");
            } else {
                if (msg.arg1 == 1)
                    showLoginDialog((String) msg.obj);
                else
                    mListener.onComplete("");
            }
        }
    };
   
    public interface TwDialogListener {
        public void onComplete(String value);      
      
        public void onError(String value);
    }
}

/////////////////
TwitterDialog.java

package blizit.app;

import android.app.Dialog;
import android.app.ProgressDialog;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;

import android.os.Bundle;
import android.util.Log;
import android.content.Context;

import android.view.Display;
import android.view.ViewGroup;
import android.view.Window;

import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import blizit.app.TwitterApp.TwDialogListener;
public class TwitterDialog extends Dialog {

    static final float[] DIMENSIONS_LANDSCAPE = {460, 260};
    static final float[] DIMENSIONS_PORTRAIT = {280, 420};
    static final FrameLayout.LayoutParams FILL = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                                                 ViewGroup.LayoutParams.FILL_PARENT);
    static final int MARGIN = 4;
    static final int PADDING = 2;

    private String mUrl;
    private TwDialogListener mListener;
    private ProgressDialog mSpinner;
    private WebView mWebView;
    private LinearLayout mContent;
    private TextView mTitle;

    private static final String TAG = "Twitter-WebView";
   
    public TwitterDialog(Context context, String url, TwDialogListener listener) {
        super(context);
       
        mUrl         = url;
        mListener     = listener;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mSpinner = new ProgressDialog(getContext());
       
        mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
        mSpinner.setMessage("Loading...");

        mContent = new LinearLayout(getContext());
       
        mContent.setOrientation(LinearLayout.VERTICAL);
       
        setUpTitle();
        setUpWebView();
       
        Display display     = getWindow().getWindowManager().getDefaultDisplay();
        final float scale     = getContext().getResources().getDisplayMetrics().density;
        float[] dimensions     = (display.getWidth() < display.getHeight()) ? DIMENSIONS_PORTRAIT : DIMENSIONS_LANDSCAPE;
       
        addContentView(mContent, new FrameLayout.LayoutParams((int) (dimensions[0] * scale + 0.5f),
                                    (int) (dimensions[1] * scale + 0.5f)));
    }

    private void setUpTitle() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
       
        Drawable icon = getContext().getResources().getDrawable(R.drawable.twitter_icon);
       
        mTitle = new TextView(getContext());
       
        mTitle.setText("Twitter");
        mTitle.setTextColor(Color.WHITE);
        mTitle.setTypeface(Typeface.DEFAULT_BOLD);
        mTitle.setBackgroundColor(0xFFbbd7e9);
        mTitle.setPadding(MARGIN + PADDING, MARGIN, MARGIN, MARGIN);
        mTitle.setCompoundDrawablePadding(MARGIN + PADDING);
        mTitle.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);
       
        mContent.addView(mTitle);
    }

    private void setUpWebView() {
        mWebView = new WebView(getContext());
       
        mWebView.setVerticalScrollBarEnabled(false);
        mWebView.setHorizontalScrollBarEnabled(false);
        mWebView.setWebViewClient(new TwitterWebViewClient());
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.loadUrl(mUrl);
        mWebView.setLayoutParams(FILL);
       
        mContent.addView(mWebView);
    }

    private class TwitterWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.d(TAG, "Redirecting URL " + url);
           
            if (url.startsWith(TwitterApp.CALLBACK_URL)) {
                mListener.onComplete(url);
               
                TwitterDialog.this.dismiss();
               
                return true;
            }  else if (url.startsWith("authorize")) {
                return false;
            }
           
            return true;
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            Log.d(TAG, "Page error: " + description);
           
            super.onReceivedError(view, errorCode, description, failingUrl);
     
            mListener.onError(description);
           
            TwitterDialog.this.dismiss();
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            Log.d(TAG, "Loading URL: " + url);
            super.onPageStarted(view, url, favicon);
            mSpinner.show();
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            String title = mWebView.getTitle();
            if (title != null && title.length() > 0) {
                mTitle.setText(title);
            }
            mSpinner.dismiss();
        }

    }
}

//////////////////
TwitterSession.java


package blizit.app;

import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.Context;

import twitter4j.http.AccessToken;

public class TwitterSession {
    private SharedPreferences sharedPref;
    private Editor editor;
   
    private static final String TWEET_AUTH_KEY = "auth_key";
    private static final String TWEET_AUTH_SECRET_KEY = "auth_secret_key";
    private static final String TWEET_USER_NAME = "user_name";
    private static final String SHARED = "Twitter_Preferences";
   
    public TwitterSession(Context context) {
        sharedPref       = context.getSharedPreferences(SHARED, Context.MODE_PRIVATE);
       
        editor           = sharedPref.edit();
    }
   
    public void storeAccessToken(AccessToken accessToken, String username) {
        editor.putString(TWEET_AUTH_KEY, accessToken.getToken());
        editor.putString(TWEET_AUTH_SECRET_KEY, accessToken.getTokenSecret());
        editor.putString(TWEET_USER_NAME, username);
       
        editor.commit();
    }
   
    public void resetAccessToken() {
        editor.putString(TWEET_AUTH_KEY, null);
        editor.putString(TWEET_AUTH_SECRET_KEY, null);
        editor.putString(TWEET_USER_NAME, null);
       
        editor.commit();
    }
   
    public String getUsername() {
        return sharedPref.getString(TWEET_USER_NAME, "");
    }
   
    public AccessToken getAccessToken() {
        String token         = sharedPref.getString(TWEET_AUTH_KEY, null);
        String tokenSecret     = sharedPref.getString(TWEET_AUTH_SECRET_KEY, null);
       
        if (token != null && tokenSecret != null)
            return new AccessToken(token, tokenSecret);
        else
            return null;
    }
}

/////////////
post.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:background="@drawable/background">
    <LinearLayout android:name="LinearLayout" android:layout_width="fill_parent"
    android:background="@drawable/navigation_bar" android:layout_height="wrap_content" android:id="@+id/linear1">
    <Button android:layout_height="wrap_content" android:id="@+id/back" android:background="@layout/backselector" android:layout_width="wrap_content" android:textStyle="bold" android:textSize="16dip" android:layout_marginLeft="5dip" android:textColor="#ffffff" android:layout_gravity="center_vertical"></Button>
</LinearLayout>
      
    <EditText
        android:id="@+id/revieew"
        android:layout_marginTop="15dp"
        android:layout_width="250dp"
        android:layout_height="90dip" android:layout_gravity="center_horizontal"/>
      
    <CheckBox
        android:id="@+id/twitterCheck"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:textSize="14sp"
        android:clickable="true"
        android:focusable="true"
        android:button="@drawable/twitter_check" android:layout_width="fill_parent" android:layout_marginLeft="15dip" android:layout_gravity="center_horizontal" android:text="bbbb"/>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:text="Tweet" android:layout_height="45dip" android:background="@drawable/button_blue" android:textStyle="bold" android:textColor="#ffffff" android:layout_marginTop="25dip" android:paddingTop="5dip" android:layout_marginLeft="40dip"/>
    <ImageView android:id="@+id/imageView1" android:layout_marginTop="20dip" android:background="@drawable/twitter1" android:layout_height="100dip" android:layout_width="120dip" android:layout_marginLeft="40dip"></ImageView>
</LinearLayout>




Monday 27 February 2012

Finding lan,lat using network & passive in android

  LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                List<String> providers = lm.getProviders(true);
                System.out.println("providers size"+providers.size());
                for(int i=0;i<providers.size();i++){
                     System.out.println("providers "+providers.get(i));
                }
                Location l = null;
                for (int i=providers.size()-1; i>=0; i--) {
                l = lm.getLastKnownLocation(providers.get(i));
            
                if (l != null) break;
                }

                double[] gps = new double[2];
                if (l != null) {
                gps[0] = l.getLatitude();
                gps[1] = l.getLongitude();
                lat2=gps[0];
                lng2=gps[1];

Wednesday 22 February 2012

Displaying map in web view using google service in android


we can display the maps in web view using this service

http://maps.google.com/maps?q=address,city,state,zipcode

Sample code for using this service is

setContentView(R.layout.webview);
getWindow().setFeatureInt(Window.FEATURE_PROGRESS,Window.PROGRESS_VISIBILITY_ON);
final ProgressBar pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(pb.VISIBLE);
mWebView = (WebView) findViewById(R.id.webView1);
mWebView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
pb.setProgress(progress);
if (progress == 100) {
pb.setVisibility(pb.GONE);
}
}
});

WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.setWebViewClient(new HelloWebViewClient());
String addressText = address + "," + city + "," + state + ","+ zip;
addressText = addressText.replaceAll(" ", "%20");
addressText = addressText.replaceAll("#", "%23");
mWebView.loadUrl("http://maps.google.com/maps?q="+ addressText);

----
public class HelloWebViewClient extends WebViewClient {

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);

return true;
}
}

and we need to provide some background for the progressbar
use the progress bar code in our display xml

    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" android:soundEffectsEnabled="true" android:indeterminateDrawable="@drawable/progress_bar_states"/>

use the progress bar background by using xml like progress_bar_states.xml. wee
need to place this xml file in drawable folder

code for progress_bar_states.xml is

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:pivotX="50%" android:pivotY="50%" android:fromDegrees="0"
    android:toDegrees="360">

    <shape android:shape="ring" android:innerRadiusRatio="3"
        android:thicknessRatio="8" android:useLevel="false">

        <size android:width="48dip" android:height="48dip" />

        <gradient android:type="sweep" android:useLevel="false"
            android:startColor="#4c737373" android:centerColor="#00FF00"
            android:centerY="0.50" android:endColor="#ffffd300" />

    </shape>

</rotate>


Finding distance between two locations using google service in android

To find the disatnce we need to call the google service by passing present , destination location lan,lat's
we need to use the service like this

http://maps.google.com/maps/api/directions/json?origin=ourLat,ourLan&destination=destLat,destLan&sensor=true&units=metric

we need to replace ourLat,ourLan, destLat,destLan values in that service.While calling this service it is giving Json object as result we can parse the Json object and get the reslut.
Sample code:

 HttpClient disthttpclient = new DefaultHttpClient();
                
                      HttpPost distpost=new HttpPost("http://maps.google.com/maps/api/directions/json?origin="+lat2+","+lng2+"&destination="+lat1+","+lng1+"&sensor=true&units=metric");
                     
                       try{                           
                       ResponseHandler<String> responseHandler=new BasicResponseHandler();
                       String responseBody=disthttpclient.execute(distpost, responseHandler);
                       JSONObject d_Obj = new JSONObject(responseBody.toString());
                       if(d_Obj.getString("status").equals("OK")){
                           JSONArray dist_data=new JSONArray(d_Obj.getString("routes"));
                           JSONObject dist_Obj1 = dist_data.getJSONObject(0);
                           JSONArray dist_data1=new JSONArray(dist_Obj1.getString("legs"));
                           JSONObject dist_Obj2 = dist_data1.getJSONObject(0);
                           String res_str = dist_Obj2.getString("distance");
                           JSONObject dist_res = new JSONObject(res_str);                          
                           double resval=Double.parseDouble(dist_res.getString("value").toString());
                          double dist =(resval*0.000621);
                           dist = Math.round(dist*10);
                           dist = dist/10;                                
                      }
}catch(Exception e){
                        e.printStackTrace();
                        }
 finally we will get the result distance value as double and assigned to dist variable;
Here some the distance will be available for the location which is having the road way only. If the distance available the service object "status" as "OK". we need to check this and if the route distance is not available we can write some other logic to calculate the distance like below

Other way to find the distance between to locations using Location class in android

float results[] = new float[3];
                            Location.distanceBetween(lat2, lng2, lat1,lng1, results);
                            double dist_mtrs = results[0];
                            dist=(dist_mtrs*0.000621);
                            dist = Math.round(dist*10);
                            dist = dist/10;



Wednesday 15 February 2012

Gathered information


ARYABHATT (476 CE) MASTER ASTRONOMER AND MATHEMATICIAN

Born in 476 CE in Kusumpur ( Bihar ), Aryabhatt's intellectual brilliance remapped the boundaries of mathematics and astronomy. In 499 CE, at the age of 23, he wrote a text on astronomy and an unparallel treatise on mathematics called "Aryabhatiyam." He formulated the process of calculating the motion of planets and the time of eclipses. Aryabhatt was the first to proclaim that the earth is round, it rotates on its axis, orbits the sun and is suspended in space - 1000 years before Copernicus published his heliocentric theory. He is also acknowledged for calculating p (Pi) to four decimal places: 3.1416 and the sine table in trigonometry. Centuries later, in 825 CE, the Arab mathematician, Mohammed Ibna Musa credited the value of Pi to the Indians, "This value has been given by the Hindus." And above all, his most spectacular contribution was the concept of zero without which modern computer technology would have been non-existent. Aryabhatt was a colossus in the field of mathematics.
--------------------------------------------------------------- 
Gottlieb Daimler

In 1885, Gottlieb Daimler (together with his design partner Wilhelm Maybach) took Nicolaus Otto's internal combustion engine a step further and patented what is generally recognized as the prototype of the modern gas engine.


 First Motorcycle
 Gottlieb Daimler's connection to Nicolaus Otto was a direct one; Daimler worked as technical director of Deutz Gasmotorenfabrik, which Nicolaus Otto co-owned in 1872. There is some controversy as to who built the first motorcycle Nicolaus Otto or Gottlieb Daimler.
-------------------------------------------------------
Edward Goodrich Acheson - Carborundum

On February 28, 1893, Edward Goodrich Acheson (1856–1931) patented a method for making an industrial abrasive he called "Carborundum" or silicon carbide. On May 19, 1896, Edward Goodrich Acheson was also issued a patent for an electrical furnace used to produce carborundum. The United States Patent Office named carborundum as one of the 22 patents most responsible for the industrial age (1926). According to the National Inventors Hall of Fame, "without carborundum, the mass production manufacturing of precision-ground, interchangeable metal parts would be practically impossible."

----------------------------------------------
Acharya Kapil


Acharya Kapil is reverently known as the father of Cosmology. He was the founder of Sankhya Philsophy .His pioneering work threw light on the nature and principles of the ultimate Soul (Purusha), Primal matter (Prakriti) and creation. His concept of transformation of energy and profound commentaries on atma, Non –atma and the subtle elements of the cosmos, places him in an elite class of master achievers. He asserted that Prakriti, With the inspiration of purusha becomes the mother of cosmic creation and all energies.
------------------------------------------
 Walt Disney

In 1937, the Walt Disney Studios released its first fully animated feature film, Snow White and the Seven Dwarfs, and pioneered a new form of family entertainment. More than seven decades later, Walt Disney Animation Studios continues to honor its heritage through animated films that combine beautiful artistry, masterful storytelling and ground breaking technology.
---------------------------------------------------------
Ancient Pyramids in Giza, Egypt

Khafre (l.) and Khufu (r.) are two of the three ancient Pyramids in Giza, Egypt. Khufu is the biggest, consisting of more than 2 million stones with some weighing 9 tons. The Pyramids, built as elaborate tombs for divine kings, date back to 2,550 BC. Modern Egyptologists believe that the Pyramids are made from stones dragged from quarries and, despite ancient Greek testimony, were built predominantly by skilled craftsmen rather than slave labor.

--------------------------------------
TEJO MAHALAYA (Shiva's Temple)

No one has ever challenged it except Prof. P. N. Oak, who believes the whole world has been duped. In his book

Taj Mahal: The True Story, Oak says the Taj Mahal is not Queen Mumtaz's tomb but an ancient Hindu temple palace of Lord Shiva (then known as Tejo Mahalaya ) . In the course of his research Oak discovered that the Shiva temple palace was usurped by Shah Jahan from then Maharaja of Jaipur, Jai Singh. In his own court ch ronicle, Badshahnama, Shah Jahan admits that an exceptionally beautiful grand mansion in Agra was taken from Jai SIngh for Mumtaz's burial .

The ex-Maharaja of Jaipur still retains in his secret collection two orders from Shah Jahan for surrendering the Taj building. Using captured temples and mansions, as a burial place for dead courtiers and royalty was a common practice among Muslim rulers. For example, Humayun,Akbar, Etmud-ud-Daula and Safdarjung are all buried in such mansions. Oak's inquiries began with the name of Taj Mahal. He says the term " Mahal " has never been used for a building in any Muslim countries from Afghanisthan to Algeria .

"The unusual explanation that the term Taj Mahal derives from Mumtaz Mahal was illogical in atleast two respects. Firstly, her name was never Mumtaz Mahal but Mumtaz-ul-Zamani ," he writes. Secondly, one cannot omit the first three letters 'Mum' from a woman's name to derive the remainder as the name for the building."Taj Mahal, he claims, is a corrupt version of Tejo Mahalaya, or Lord Shiva's Palace . Oak also says the love story of Mumtaz and Shah Jahan is a fairy tale created by court sycophants, blundering historians and sloppy archaeologists Not a single royal chronicle of Shah Jahan's time corroborates the love story.

Furthermore, Oak cites several documents suggesting the Taj Mahal predates Shah Jahan's era, and was a temple dedicated to Shiva, worshipped by Rajputs of Agra city. For example, Prof. Marvin Miller of New York took a few samples from the riverside doorway of the Taj. Carbon dating tests revealed that the door was 300 years older than Shah Jahan. European traveler Johan Albert Mandelslo,who visited Agra in 1638 (only seven years after Mumtaz's death), describes the life of the cit y in his memoirs. But he makes no reference to the Taj Mahal being built. The writings of Peter Mundy, an English visitor to Agra within a year of Mumtaz's death, also suggest the Taj was a noteworthy building well before Shah Jahan's time. Prof.

Oak points out a number of design and architectural inconsistencies that support the belief of the Taj Mahal being a typical Hindu temple rather than a mausoleum. Many rooms in the Taj ! Mahal have remained sealed since Shah Jahan's time and are still inaccessible to the public .

Oak asserts they contain a headless statue of Lord Shiva and other objects commonly used for worship rituals in Hindu temples Fearing political backlash, Indira Gandhi's government t ried to have Prof. Oak's book withdrawn from the bookstores, and threatened the Indian publisher of the first edition dire consequences .

There is only one way to discredit or validate Oak's research. The current government should open the sealed rooms of the Taj Ma hal under U.N. supervision, and let international experts investigate. Do circulate this to all you know and let them know about this reality....

-----------------------------------------------------
Dr. Jonas Salk the Inventor of Polio Vaccine

Well before you go on to find who he is, first thank him. Thank him for what? for saving your life. Well he is Dr. Jonas Salk the Inventor of Polio Vaccine. His invention may or may not be a great thing, but whats great about him is he did not patent the vaccine and make personal profit. If he had patented the vaccine, he would have been a very rich man but millions of poor children would have been deprived of the life saving vaccine. When he was asked in a televised interview who owned the patent to the vaccine, Salk replied: "There is no patent. Could you patent the sun?". The world celebrates bill gates, steve jobs, etc for giving us high tech gadgets, but here is a man who has saved many of our lives but we don’t even remember him now, How sad.

Click like & share for this awesome Dr.:)

----------------------------------------------------------

Abraham Lincoln(February 12, 1809 – April 15, 1865)
Today is the birthday of the American President, Abraham Lincoln. He was the 16th President of the United States, serving from March 1861 until his assassination in April 1865. He successfully led his country through a great constitutional, military and moral crisis – the American Civil War – preserving the Union, while ending slavery, and promoting economic and financial modernization. Lincoln's Birthday is a legal holiday in some U.S. states including California, Connecticut, Illinois, Missouri, New Jersey, New York, and Indiana. It is observed annually on the anniversary of Abraham Lincoln's birth on February 12, 1809.

-----------------------------------------------------
NASA

The National Aeronautics and Space Administration (NASA) is the agency of the United States government that is responsible for the nation's civilian space program and for aeronautics and aerospace research. Since February 2006, NASA's mission statement has been to "pioneer the future in space exploration, scientific discovery and aeronautics research." On September 14, 2011, NASA announced that it had selected the design of a new Space Launch System that it said would take the agency's astronauts farther into space than ever before and provide the cornerstone for future human space exploration efforts by the U.S

NASA was established by the National Aeronautics and Space Act on July 29, 1958, replacing its predecessor, the National Advisory Committee for Aeronautics (NACA). The agency became operational on October 1, 1958. U.S. space exploration efforts have since been led by NASA, including the Apollo moon-landing missions, the Skylab space station, and later the Space Shuttle. Currently, NASA is supporting the International Space Station and is overseeing the development of the Orion Multi-Purpose Crew Vehicle and Commercial Crew vehicles. The agency is also responsible for the Launch Services Program (LSP) which provides oversight of launch operations and countdown management for unmanned NASA launches.

NASA science is focused on better understanding Earth through the Earth Observing System, advancing heliophysics through the efforts of the Science Mission Directorate's Heliophysics Research Program, exploring bodies throughout the Solar System with advanced robotic missions such as New Horizons, and researching astrophysics topics, such as the Big Bang, through the Great Observatories and associated programs. NASA shares data with various national and international organizations such as from the Greenhouse Gases Observing Satellite.

--------------------------------------------------------- 
National Geographic Society

Formation: Gardiner Greene Hubbard, January 27, 1888 (123 years ago)
President: John M. Fahey, Jr. (1998 - )
Location: Washington, D.C., USA

The National Geographic Society (NGS), headquartered in Washington, D.C. in the United States, is one of the largest non-profit scientific and educational institutions in the world. Its interests include geography, archaeology and natural science, the promotion of environmental and historical conservation, and the study of world culture and history. The National Geographic Society’s logo is a yellow portraitframe - rectangular in shape - which appears on the margins surrounding the front covers of its magazines and as its channel logo.

-------------------------------------------
History of The Statue of Liberty

The Statue of Liberty National Monument officially celebrated her 100th birthday on October 28, 1986. The people of France gave the Statue to the people of the United States over one hundred years ago in recognition of the friendship established during the American Revolution. Over the years, the Statue of Liberty's symbolism has grown to include freedom and democracy as well as this international friendship.

Sculptor Frederic Auguste Bartholdi was commissioned to design a sculpture with the year 1876 in mind for completion, to commemorate the centennial of the American Declaration of Independence. The Statue was a joint effort between America and France and it was agreed upon that the American people were to build the pedestal, and the French people were responsible for the Statue and its assembly here in the United States. However, lack of funds was a problem on both sides of the Atlantic Ocean. In France, public fees, various forms of entertainment, and a lottery were among the methods used to raise funds. In the United States, benefit theatrical events, art exhibitions, auctions and prize fights assisted in providing needed funds.

--------------------------------------------------
Swami Vivekananda 


Swami Vivekananda was one of the most influential spiritual leaders of Vedanta philosophy. He was the chief disciple of Ramakrishna Paramahansa and was the founder of Ramakrishna Math and Ramakrishna Mission. Swami Vivekananda was the living embodiment of sacrifice and dedicated his life to the country and yearned for the progress of the poor, the helpless and the downtrodden. He showed a beacon of light to a nation that had lost faith in its ability under British rule and inspired self-confidence among Indians that they are second to none. His ringing words and masterful oratory galvanized the slumbering nation.
----------------------------------------------------------
Sir Alexander Fleming

(6 August 1881 – 11 March 1955) was a Scottish biologist and pharmacologist. He wrote many articles on bacteriology, immunology, and chemotherapy. His best-known discoveries are the discovery of the enzyme lysozyme in 1923 and the antibiotic substance penicillin from the mould Penicillium notatum in 1928, for which he shared the Nobel Prize in Physiology or Medicine in 1945 with Howard Florey and Ernst Boris Chain.

In 1999, Time magazine named Fleming one of the 100 Most Important People of the 20th Century for his discovery of penicillin, and stated:

------------------------------------------
Sushrut Samhita


A genius who has been glowingly recognized in the annals of medical science. Born to sage Vishwamitra, Acharya Sushrut details the first ever surgery procedures in "Sushrut Samhita," a unique encyclopedia of surgery. He is venerated as the father of plastic surgery and the science of anesthesia. When surgery was in its infancy in Europe, Sushrut was performing Rhinoplasty (restoration of a damaged nose) and other challenging operations. In the "Sushrut Samhita," he prescribes treatment for twelve types of fractures and six types of dislocations. His details on human embryology are simply amazing. Sushrut used 125 types of surgical instruments including scalpels, lancets, needles, cathers and rectal speculums; mostly designed from the jaws of animals and birds. He has also described a number of stitching methods; the use of horse's hair as thread and fibers of bark. In the "Sushrut Samhita," he details 300 types of operations. The ancient Indians were the pioneers in amputation, caesarian and cranial surgeries. Acharya Sushrut was a giant in the arena of medical science.
 


Thursday 2 February 2012

Creating custom spinner for multiselection items


We can create a Spinner dynamically to show the items of spinner with
check boxes which can allow you to give multiple selection.
Steps for using the custom spinner in our class
created a custom class for spinner extending our class with Spinne class.
And used the spinner in our xml file as pre defined xml tag.

Create a custom spinner class
like

MultiSpinner.java

package cz.destil.settleup.gui;

import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.util.AttributeSet;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

public class MultiSpinner extends Spinner implements
        OnMultiChoiceClickListener, OnCancelListener {

    private List<String> items;
    private boolean[] selected;
    private String defaultText;
    private MultiSpinnerListener listener;
    int count=0;

    public MultiSpinner(Context context) {
        super(context);
    }

    public MultiSpinner(Context arg0, AttributeSet arg1) {
        super(arg0, arg1);
    }

    public MultiSpinner(Context arg0, AttributeSet arg1, int arg2) {
        super(arg0, arg1, arg2);
    }

    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
   
        if (isChecked)
            selected[which] = true;
        else
            selected[which] = false;
    }

    public void onCancel(DialogInterface dialog) {
        // refresh text on spinner
        StringBuffer spinnerBuffer = new StringBuffer();
        boolean someUnselected = false;
        for (int i = 0; i < items.size(); i++) {
            if (selected[i] == true) {
                spinnerBuffer.append(items.get(i));
                spinnerBuffer.append(", ");
               } else {
                someUnselected = true;
            }
        }
        String spinnerText;
        if (someUnselected) {
            spinnerText = spinnerBuffer.toString();
            //
            if(spinnerText.toString().length()==0){
            spinnerText="Not Selected";
            }
           //
            if (spinnerText.length() > 2){
                spinnerText = spinnerText.substring(0, spinnerText.length() - 2);
            }
        } else {
            spinnerText = defaultText;
        }
        //
        for(int i=0;i<selected.length;i++){
        if(selected[i]==true){
        System.out.println(i+" Count "+count);
        count=count++;
        }
        }
        if(count==items.size()){
        spinnerText="All Selected";
        System.out.println(" 66666666 ");
       
        }
        //
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(),android.R.layout.simple_spinner_item,new String[] { spinnerText });
        setAdapter(adapter);
        listener.onItemsSelected(selected);
    }

    @Override
    public boolean performClick() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setMultiChoiceItems(items.toArray(new CharSequence[items.size()]), selected, this);
        builder.setPositiveButton("Ok",
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
        builder.setOnCancelListener(this);
        builder.show();
        return true;
    }

    public void setItems(List<String> items, String allText,MultiSpinnerListener listener) {
        this.items = items;
        this.defaultText = allText;
        this.listener = listener;

        // all unselected by default
        selected = new boolean[items.size()];
        for (int i = 0; i < selected.length; i++)
            selected[i] = false;
        // all text on the spinner
       
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(),android.R.layout.simple_spinner_item, new String[] { allText });
        setAdapter(adapter);
    }

    public interface MultiSpinnerListener {
        public void onItemsSelected(boolean[] selected);  
    }
}

and use it in xml file like

<cz.destil.settleup.gui.MultiSpinner android:id="@+id/multi_spinner" android:layout_width="fill_parent"
    android:layout_height="wrap_content" />


and used it in main activity class as same as common spinner  MyClass.java



package cz.destil.settleup.gui;

import java.util.ArrayList;
import java.util.List;

import cz.destil.settleup.gui.MultiSpinner.MultiSpinnerListener;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;

public class MyClass extends Activity  implements MultiSpinnerListener{
    /** Called when the activity is first created. */
int[] selectedItems={0,0,0};
ArrayList al;
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        String[] arr={"Raghu","Ram","Reddy"};
     
       al=new ArrayList();
        al.add("raghu");
        al.add("ram");
        al.add("reddy");
        MultiSpinner multiSpinner = (MultiSpinner) findViewById(R.id.multi_spinner);
       
        multiSpinner.setItems(al, "Select",MyClass.this);
       
        multiSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){

@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub

}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub

}});
    }

@Override
public void onItemsSelected(boolean[] selected) {
for(int i=0;i<selected.length;i++){
if(selected[i]){
selectedItems[i]=1;
// System.out.println("______________________"+al.get(i));
}
else selectedItems[i]=0;
}
for(int i=0;i<selectedItems.length;i++){
// if(selectedItems[i]==1)
// System.out.println(al.get(i));
}
}
   
}

Getting time date based on time zone in android


Calendar calendar = Calendar.getInstance();
   SimpleDateFormat sdf = new SimpleDateFormat("MMM ddyyyy hh:mm:ss z");
   sdf.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
   System.out.println(sdf.format(calendar.getTime()));