Saturday, 25 October 2014

Android Studio Shortcuts for Windows

Using shortcuts make a developer more productive. Eclipse provides keyboard shortcuts for the most common actions so does Android Studio. Android Studio will be official development IDE and this tutorial will help in migrating from Eclipse to Android Studio.

    1) Quick Access
Action
Android Studio Key Command
To quickly open any class
CTRL + N
To quickly open any file
CTRL + SHIFT + N
Toggle tools (maximize/minimize code window).
CTRL + SHIFT + F12
To find all places where a particular class, method or variable is used in the whole project by positioning the caret at the symbol's name or at its usage in code.
ALT + F7


    2) Editing
Action
Android Studio Key Command
Basic code completion
CTRL + SPACE
Smart code completion
CTRL + SHIFT + SPACE
Parameter Info
CTRL + P
Quick documentation
CTRL + Q
External doc
SHIFT + F1
Generate code... (Getters, Setters, constructors etc)
ALT + INSERT
Override methods
CTRL + O
Surround with… (if..else, try..catch, for, synchronized, etc.)
CTRL + ALT + T
Comment/Uncomment single line
CTRL + /
Comment/Uncomment block code
CTRL + SHIFT + /
Select successively increasing code blocks
CTRL + W
Decrease current selection to previous state
CTRL + SHIFT + W
Reformat code
ALT + CTRL + L
Optimize imports
ALT + CTRL + O
Auto indent lines
ALT + CTRL + I
Duplicate current line/selected block
CTRL + D
Delete current line
CTRL + Y
Close active editor
CTRL + F4
Highlight usage in file
CTRL + SHIFT + F7
Find usages / Find usages in file
ALT + F7/ CTRL + F7
Show usages
ALT + CTRL + F7
Rename
SHIFT + F6
Change signature
CTRL + F6
Extract method
ALT + CTRL + M
Search everywhere
Double shift
Find
CTRL + F
Find next/previous
F3/SHIFT + F3
Replace
CTRL + R
Find in path
CTRL + SHIFT + F
Replace in path
CTRL + SHIFT + R

    3) Navigation
Action
Android Studio Key Command
Go to symbol
ALT + CTRL + SHIFT + N
Next/previous editor tab
ALT + RIGHT/LEFT
Previous tool window
F12
Editor from tool window
ESC
Hide active/last active window
SHIFT + ESC
Go to line
CTRL + G
Recent file
CTRL + E
Go to declaration
CTRL + B/ CTRL + CLICK
Go to implementation
ALT + CTRL + B
Open quick definition lookup
CTRL + SHIFT + I
Go to type declaration
CTRL + SHIFT + B
Go to super-method/class
CTRL + U
Go to previous/next method
CTRL + ARROW UP/DOWN
File structure pop up
CTRL + F12
Type hierarchy
CTRL + H
Method hierarchy
CTRL + SHIFT + H
Call hierarchy
ALT + CTRL + H
Edit/View source
F4/ CTRL + ENTER
Navigation Bar
ALT + HOME
Toggle bookmark
F11
Show bookmark
SHIFT + F11
Jump to source
F4
Command look-up (autocomplete command name)
CTRL + SHIFT + A

    4) Build/Debug/Run
Action
Android Studio Key Command
Build
CTRL + F9
Build and run
SHIFT + F10
Debug
SHIFT + F9
Toggle project visibility
ALT + 1
Navigate open tabs
ALT + left-arrow; ALT + right-arrow
View recent changes
ALT + SHIFT + C
Step over
F8
Step into
F7
Smart step into
SHIFT + F7
Step out
SHIFT + F8
Resume program
F9
Toggle breakpoint
CTRL + F8
View breakpoints
CTRL + SHIFT + F8

Shortcuts on Mac OS:
The above description uses the shortcuts based on Windows and Linux. Mac OS uses the Cmd key frequently instead of the Ctrl key.

Note:                                                    
View/Edit Keymap shortcuts - File -> Settings ->  Keymap
Check this link for migrating from Eclipse to Android Studio.


Saturday, 11 October 2014

Android LinkedIn Integration with linkedin-j

1. Refer LinkedIn development site before continuing: http://developer.linkedin.com/
2. Create your LinkedIn application on LinkedIn.
3. Save Access token and Access token secret in your application(Save in your constant file).
4. Download linkedin-j jar file from http://code.google.com/p/linkedin-j/ (Read the documentation).
5. Create OAuthWebViewActivity.java with WebView.
6. Make a manifest entry for this:

 <activity  
 android:name=”com.android.sample.OAuthWebViewActivity”  
 android:launchMode=”singleInstance”  
 android:theme=”@android:style/Theme.Black.NoTitleBar” >  
 <intent-filter>  
 <action android:name=”android.intent.action.VIEW” />  
 <category android:name=”android.intent.category.DEFAULT” />  
 <category android:name=”android.intent.category.BROWSABLE” />  
 <data  
 android:host=”callback”  
 android:scheme=”sample” />  
 </intent-filter>  
 </activity> 

7. Build your authentication process in OAuthWebViewActivity.java:

public class OAuthWebViewActivity extends Activity{  
 final String TAG = getClass().getName();  
 private WebView mWebview;  
 private LinkedInOAuthService oauthService;  
 private LinkedInRequestToken mLinkedInRequestToken;  
 private SharedPreferences mPref = null;  
 private int mResult = -1;  
 @Override  
 public void onCreate(Bundle savedInstanceState) {  
 super.onCreate(savedInstanceState);  
 setContentView(R.layout.auth_layout);  
 mPref = getSharedPreferences(APP_PREFERENCE_NAME, MODE_PRIVATE);  
 mWebview = (WebView)findViewById(R.id.web);  
 mWebview.getSettings().setJavaScriptEnabled(true);  
 mWebview.getSettings().setBuiltInZoomControls(true);  
 mWebview.getSettings().setRenderPriority(RenderPriority.HIGH);  
 mWebview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);  
 class MyWebViewClient extends WebViewClient {  
 @Override  
 public boolean shouldOverrideUrlLoading(WebView view, String url) {  
 DebugUtil.printLog(TAG, "Url: " + url, Log.INFO);  
 if (Uri.parse(url).getHost().equals("callback")) {  
 // This is your web site, so do not override; let the WebView to load the page  
 Uri uri = Uri.parse(url);  
 new RetrieveAccessToken(uri.getQueryParameter("oauth_verifier")).execute();  
 return true;  
 }  
 // Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs  
 return false;  
 }  
 }  
 mWebview.setWebViewClient(new MyWebViewClient());  
 new OAuthTokenTask().execute();  
 }  
 private void redirect(){  
 setResult(mResult);  
 finish();  
 }  
 class RetrieveAccessToken extends AsyncTask<Void, Void, Void> {  
 private String oAuthVerifier;  
 public RetrieveAccessToken(String oAuthVerifier) {  
 this.oAuthVerifier = oAuthVerifier;  
 }  
 @Override  
 protected void onPreExecute() {  
 super.onPreExecute();  
 }  
 /**  
 * Store the oauth_token and oauth_token_secret  
 * for future API calls.  
 */  
 @Override  
 protected Void doInBackground(Void... params) {  
 // TODO Auto-generated method stub  
 try {  
 LinkedInAccessToken accessToken = oauthService.getOAuthAccessToken(mLinkedInRequestToken, oAuthVerifier);  
 Editor edit = mPref.edit();  
 edit.putString(APIConstant.LINKEDIN_OAUTH_TOKEN, accessToken.getToken());  
 edit.putString(APIConstant.LINKEDIN_OAUTH_SECRET, accessToken.getTokenSecret());  
 edit.commit();  
 mResult = RESULT_OK;  
 redirect();  
 } catch (Exception e) {  
 // TODO Auto-generated catch block  
 mResult = RESULT_CANCELED;  
 Log.e(TAG, "Access token failed: ", e);  
 redirect();  
 }  
 return null;  
 }  
 @Override  
 protected void onPostExecute(Void result) {  
 // TODO Auto-generated method stub  
 super.onPostExecute(result);  
 }  
 }  
 class OAuthTokenTask extends AsyncTask<Void, Void, Void> {  
 @Override  
 protected Void doInBackground(Void... params) {  
 try {  
 oauthService = LinkedInOAuthServiceFactory.getInstance().  
 createLinkedInOAuthService(APIConstant.LINKEDIN_API_KEY, APIConstant.LINKEDIN_SECRET_KEY);  
 mLinkedInRequestToken = oauthService.getOAuthRequestToken(APIConstant.LINKEDIN_CALLBACK_URL);  
 String authUrl = mLinkedInRequestToken.getAuthorizationUrl();  
 mWebview.loadUrl(authUrl);  
 } catch (Exception e) {  
 mResult = RESULT_CANCELED;  
 Log.e(TAG, "Error during OAUth retrieve request token: ", e);  
 redirect();  
 }  
 return null;  
 }  
 }  
 } 

Android Twitter Integration with Twitter4j

1. Refer twitter development site before continuing: https://dev.twitter.com/
2. Create your Twitter application on Twitter.
3. Save Access token and Access token secret in your application(Save in your constant file).
4. Download twitter4j jar file from http://twitter4j.org/en/index.html.
5. Create OAuthWebViewActivity.java with WebView.
6. Make a manifest entry for this:

<activity  
 android:name="com.android.sample.OAuthWebViewActivity"  
 android:launchMode="singleInstance"  
 android:theme="@android:style/Theme.Black.NoTitleBar" >  
 <intent-filter>  
 <action android:name="android.intent.action.VIEW" />  
 <category android:name=”android.intent.category.DEFAULT” />  
 <category android:name=”android.intent.category.BROWSABLE” />  
 <data  
 android:host=”callback”  
 android:scheme=”sample” />  
 </intent-filter>  
 </activity> 

7. Build your authentication process in OAuthWebViewActivity.java:
public class OAuthWebViewActivity extends Activity{  
 final String TAG = getClass().getName();  
 private WebView mWebview;  
 private Twitter mTwitter;  
 private RequestToken mTwitterRequestToken;  
 private SharedPreferences mPref = null;  
 private int mResult = -1;  
 @Override  
 public void onCreate(Bundle savedInstanceState) {  
 super.onCreate(savedInstanceState);  
 setContentView(R.layout.auth_layout);  
 mPref = getSharedPreferences(APP_PREFERENCE_NAME, MODE_PRIVATE);  
 mWebview = (WebView)findViewById(R.id.web);  
 mWebview.getSettings().setJavaScriptEnabled(true);  
 mWebview.getSettings().setBuiltInZoomControls(true);  
 mWebview.getSettings().setRenderPriority(RenderPriority.HIGH);  
 mWebview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);  
 class MyWebViewClient extends WebViewClient {  
 @Override  
 public boolean shouldOverrideUrlLoading(WebView view, String url) {  
 if (Uri.parse(url).getHost().equals("callback")) {  
 // This is your web site, so do not override; let the WebView to load the page  
 Uri uri = Uri.parse(url);  
 new RetrieveAccessToken(uri.getQueryParameter("oauth_verifier")).execute();  
 return true;  
 }  
 // Otherwise, the link is not for a page on my site,  
 //so launch another Activity that handles URLs  
 return false;  
 }  
 }  
 mWebview.setWebViewClient(new MyWebViewClient());  
 new OAuthTokenTask().execute();  
 }  
 private void redirect(){  
 setResult(mResult);  
 finish();  
 }  
 class RetrieveAccessToken extends AsyncTask<Void, Void, Void> {  
 private String oAuthVerifier;  
 public RetrieveAccessToken(String oAuthVerifier) {  
 this.oAuthVerifier = oAuthVerifier;  
 }  
 @Override  
 protected void onPreExecute() {  
 super.onPreExecute();  
 }  
 /**  
 * Store the oauth_token and oauth_token_secret  
 * for future API calls.  
 */  
 @Override  
 protected Void doInBackground(Void... params) {  
 // TODO Auto-generated method stub  
 try {  
 AccessToken accessToken = mTwitter.getOAuthAccessToken(mTwitterRequestToken, oAuthVerifier);  
 DebugUtil.printLog(TAG, "Access Token Retrieved.", Log.INFO);  
 Editor edit = mPref.edit();  
 edit.putString(APIConstant.TWITTER_TOKEN, accessToken.getToken());  
 edit.putString(APIConstant.TWITTER_TOKEN_SECRET, accessToken.getTokenSecret());  
 edit.commit();  
 mResult = RESULT_OK;  
 redirect();  
 } catch (Exception e) {  
 // TODO Auto-generated catch block  
 mResult = RESULT_CANCELED;  
 Log.e(TAG, "Access token failed: ", e);  
 redirect();  
 }  
 return null;  
 }  
 @Override  
 protected void onPostExecute(Void result) {  
 // TODO Auto-generated method stub  
 super.onPostExecute(result);  
 }  
 }  
 class OAuthTokenTask extends AsyncTask<Void, Void, Void> {  
 @Override  
 protected Void doInBackground(Void... params) {  
 try {  
 ConfigurationBuilder builder = new ConfigurationBuilder();  
 builder.setOAuthConsumerKey(APIConstant.TWITTER_API_KEY);  
 builder.setOAuthConsumerSecret(APIConstant.TWITTER_SECRET_KEY);  
 TwitterFactory factory = new TwitterFactory(builder.build());  
 mTwitter = factory.getInstance();  
 mTwitterRequestToken = mTwitter.getOAuthRequestToken(APIConstant.TWITTER_CALLBACK_URL);  
 String authUrl = mTwitterRequestToken.getAuthorizationURL();  
 mWebview.loadUrl(authUrl);  
 } catch (Exception e) {  
 mResult = RESULT_CANCELED;  
 Log.e(TAG, "Error during OAUth retrieve request token: ", e);  
 redirect();  
 }  
 return null;  
 }  
 }  
 }  

Sunday, 31 March 2013

Location


To find the location of user, comes with cost and cost includes battery, CPU etc.
Android provides two way to get the user location:

1. Network Provider:
a) It uses cell tower and wifi signals. 
b) It works indoor and outdoor both.
c) It consumes less battery and takes less time to give result.

2. GPS Provider:
a) It is more accurate than Network Provider.
b) It works only outdoor.
c) It consumes more battery and takes more time to give result.

Permission:
1. ACCESS_COARSE_LOCATION:
Required for NETWORK_PROVIDER.
2. ACCESS_FINE_LOCATION:
Required for GPS_PROVIDER. It includes permission for NETWORK_PROVIDER too. Use this if you are using both provider.

To get the location, we need to register the listner(LocationListener) with LocationManager:

// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
      // Called when a new location is found by the network location provider.
      makeUseOfNewLocation(location);
    }
    public void onStatusChanged(String provider, int status, Bundle extras) {}
    public void onProviderEnabled(String provider) {}
    public void onProviderDisabled(String provider) {}
  };

// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER/LocationManager.NETWORK_PROVIDER, min_time_interval, min_distance_change, locationListener);

Note:
1) Setting min_time_interval and min_distance_change to 0 receives the updates as frequently as possible.
2) To get the location updates from both provider, you need to register twice one with GPS_PROVIDER and second with NETWORK_PROVIDER.

Getting Location while registering:
You will not get location as soon as you register, it takes time. So for first time
we can use the last cached location.

String locationProvider = LocationManager.NETWORK_PROVIDER;
// Or use LocationManager.GPS_PROVIDER
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);

Note:
It may happen that last received location is more accurate than the newest one.
How to Know which provider to use?
If you are not sure  know about the best provider for your requirments then you can use Criteria class:

Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
/**
*  Get the critria list here(http://developer.android.com/reference/android/location/Criteria.html).
*/
String provider = locationManager.getBestProvider(criteria, true);

Note:
For detailed analysis, follow the doc.



profile for Vineet Shukla at Stack Overflow, Q&A for professional and enthusiast programmers

Saturday, 29 September 2012

Animation Prior to Android 3.0

Before Android 3.0, we have View Animation which covers:

1. Tween Animation

Tween animation calculates the animation with information such as the start point, end point, size, rotation, and other common aspects of an animation.

A sequence of animation instructions defines the tween animation, defined by either XML or Android code. As with defining a layout, an XML file is recommended because it's more readable, reusable, and swappable than hard-coding the animation.


The animation XML file belongs in the res/anim/ directory of your Android project. The file must have a single root element: this will be either a single <alpha><scale><translate><rotate>, interpolator element, or<set> element that holds groups of these elements (which may include another <set>).


Note:

Be sure to use the proper format for what you want ("50" for 50% relative to the parent, or "50%" for 50% relative to itself).

Using translate animation we can do animation like slide left, slide right, slide up, slide down, shake etc.


slide_left.xml




<?xml version="1.0" encoding="utf-8"?>
<translate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromXDelta="0%"
    android:toXDelta="-100%"
    android:interpolator="@android:anim/linear_interpolator"
    android:duration="2000" />


slide_right.xml


<?xml version="1.0" encoding="utf-8"?>
<translate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromXDelta="0%"
    android:toXDelta="100%"
    android:interpolator="@android:anim/linear_interpolator"
    android:duration="2000" />

slide_up.xml



<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromYDelta="0%"
    android:toYDelta="-100%"
    android:duration="2000"
    android:interpolator="@android:anim/linear_interpolator" />


slide_down.xml


<?xml version="1.0" encoding="utf-8"?>
<translate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromYDelta="0%"
    android:toYDelta="100%"
    android:duration="2000"
    android:interpolator="@android:anim/linear_interpolator" />

shake.xml




<?xml version="1.0" encoding="utf-8"?>
<translate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromXDelta="0"
    android:toXDelta="100"
    android:duration="1000"
    android:interpolator="@android:anim/cycle_interpolator"
    android:repeatCount="50"
    android:repeatMode="reverse" />


Note:

To implement shake behaviour we need to use cycle interpolator and repeatCount attribute. 



Using rotate animation we can do rotation with different angles and points.


rotate_360.xml


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

Note:




android:pivotX
Float. The X coordinate to remain fixed when the object is scaled.
android:pivotY
Float. The Y coordinate to remain fixed when the object is scaled.


Using alpha animation we can do fade in/ fade out animation.

fade_in.xml




<?xml version="1.0" encoding="utf-8"?>
<alpha
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromAlpha="0"
    android:toAlpha="1"
    android:interpolator="@android:anim/linear_interpolator"
    android:duration="2000" />


fade_out.xml



<?xml version="1.0" encoding="utf-8"?>
<alpha
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="2000"
    android:fromAlpha="1"
    android:interpolator="@android:anim/linear_interpolator"
    android:toAlpha="0" />


Loading View Animation:


Animation animation = AnimationUtils.loadAnimation(this, R.anim.yourAnim);
animation.startAnimation(animation);

2. Frame by Frame Animation

Drawable animation lets you load a series of Drawable resources one after another to create an animation.

frame_animation.xml



<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="false">
    <item android:drawable="@drawable/active" android:duration="500" />
    <item android:drawable="@drawable/deactive" android:duration="500" />
</animation-list>


Note:
By setting the android:oneshot attribute of the list to true, it will cycle just once then stop and hold on the last frame.

Loading Frame Animation:



@Override
public void onWindowFocusChanged(boolean hasFocus) {
  // TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
((AnimationDrawable)view.getBackground()).start();
}



profile for Vineet Shukla at Stack Overflow, Q&A for professional and enthusiast programmers

Thursday, 23 August 2012

Passing Data Object from one Activity to Another

We often need to pass data model from one activity to another. For this Android provides a way to do this and it is called Parcelable.

Using parcelable we can pass different types of data:

1. int and int[]
2. float and float[]
3. double and double[]
4. byte and byte[]
5. boolean[]
6. long and long[]
7. String and String[]
8. Object and Object[]
9. List and List<T>
10. Map
11. Nested data model and many more.

Below I am covering some basic types and rest you can try on your own.

Create a data Model: TestModel


public class TestModel implements Parcelable{

public int testInt;
public Double testDouble;
public String testString;
public boolean testBoolean;
private byte testByte;

public TestModel() {
testInt = 0;
testDouble = 0.0;
testString = "";
testBoolean = false;
testByte = 0;
}

//Get your data here in the same order in which you have set it. public TestModel(Parcel in) {
testInt = in.readInt();
testDouble = in.readDouble();
testString = in.readString();
boolean[] flag = new boolean[1];
in.readBooleanArray(flag);
testBoolean = (flag[0] == true)? true : false;
testByte = in.readByte();
}

public int getTestInt() {
return testInt;
}

public void setTestInt(int testInt) {
this.testInt = testInt;
}

public Double getTestDouble() {
return testDouble;
}

public void setTestDouble(Double testDouble) {
this.testDouble = testDouble;
}

public String getTestString() {
return testString;
}

public void setTestString(String testString) {
this.testString = testString;
}

public boolean isTestBoolean() {
return testBoolean;
}

public void setTestBoolean(boolean testBoolean) {
this.testBoolean = testBoolean;
}

public byte getTestByte() {
return testByte;
}

public void setTestByte(byte testByte) {
this.testByte = testByte;
}

//Write your data here

public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(testInt);
dest.writeDouble(testDouble);
dest.writeString(testString);
dest.writeBooleanArray(new boolean[]{testBoolean});
dest.writeByte(testByte);

}

public static final Parcelable.Creator<TestModel> CREATOR = new Parcelable.Creator<TestModel>()
{
public TestModel createFromParcel(Parcel in)
{
return new TestModel(in);
}
public TestModel[] newArray(int size)
{
return new TestModel[size];
}
};

public int describeContents() {
// TODO Auto-generated method stub
return 0;
}

}

Passing data model to another Activity:
//Setting data in the model
TestModel  model = new TestModel ();
//Set values in the model...

//Create intent

Intent intent = new Intent(getApplicationContext(),YourActivity.class);
Bundle bundle = new Bundle();                //create bundle..
bundle.putParcelable("data",  model  );    
intent.putExtras(bundle);                    //set the bundle..
startActivity(intent);

Get the data in the Activity:




Bundle bundle = getIntent().getExtras();
TestModel  model = bundle.getParcelable("data");


profile for Vineet Shukla at Stack Overflow, Q&A for professional and enthusiast programmers

Sunday, 22 July 2012

Working with HttpsUrlConnection


Refer this doc over HttpsUrlConnection.
To create key and import certificate use Portecle tool.
To create key using Keytool, follow the doc.


String query = "emailId=" + URLEncoder.encode("xxx@gmail.com", HTTP.UTF_8) + "&pwd=" + URLEncoder.encode("password", HTTP.UTF_8);


HttpsURLConnection urlConnection = null;
try{
    KeyStore keyStore = KeyStore.getInstance("BKS");
    InputStream in =  
    getResources().openRawResource(R.raw.keystore);
    keyStore.load(in, "password".toCharArray());
    TrustManagerFactory tmf = 
    TrustManagerFactory.getInstance("X509");
    tmf.init(keyStore);


    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, tmf.getTrustManagers(), null);
    System.setProperty("http.keepAlive", "false");
    URL url = new URL("https://www.google.co.in/");
    urlConnection = (HttpsURLConnection) url.openConnection();
     
urlConnection.setSSLSocketFactory(context.getSocketFactory());
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);
    urlConnection.setRequestMethod("POST");
    urlConnection.setRequestProperty("content-type",
    "application/x-www-form-urlencoded");
    urlConnection.setRequestProperty("Content-length", "" +  query.getBytes().length);

     //To post data...
     DataOutputStream output = new DataOutputStream( urlConnection.getOutputStream() );
     output.writeBytes( query );
     output.flush();
     output.close();

     InputStream stream = null;


     if ( urlConnection.getResponseCode() == 201 )
stream = urlConnection.getInputStream();
     else
       //Report error...

     urlConnection.disconnect();


}catch(Exception e){
     urlConnection.disconnect();
}



profile for Vineet Shukla at Stack Overflow, Q&A for professional and enthusiast programmers

Thursday, 5 July 2012

WebView Settings


Note: To know the HTML5 browser support for your device, you only need to open the url in your browser: http://html5test.com/


WebSettings settings = mWebView.getSettings();
//To enable the built-in zoom
settings.setBuiltInZoomControls(true);


//To enable JavaScript
settings.setJavaScriptEnabled(true);


//To enable Plugin
settings.setPluginState(PluginState.ON);


Plugin:
plug-ins are commonly used in web browsers to play video, 
scan for viruses, and display new file types. 
Well-known plug-ins examples include 
Adobe Flash Player, QuickTime, and Microsoft Silverlight.


//To enable or disable file access within WebView. 
//File access is enabled by default.
settings.setAllowFileAccess(true);


//To enable dom storage
//DOM Storage is a way to store meaningful amounts of 
//client-side data in a persistent and secure manner.
settings.setDomStorageEnabled(true);


//To enable wide viewport.
settings.setUseWideViewPort(true);


//To enable JavaScript to open windows automatically.
settings.setJavaScriptCanOpenWindowsAutomatically(true);


//To enable twitter, youtube etc.
settings.setUserAgentString("Mozilla/5.0 (Linux; U; Android 2.0; en-us; Droid Build/ESD20) 
AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17");


Detailed Description: WebSettingsWebView
profile for Vineet Shukla at Stack Overflow, Q&A for professional and enthusiast programmers

Monday, 25 June 2012

Programmatically add Image to Gallery


private void addPicToGallery() {
    Intent media = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);


//mCurrentPhotoPath is the path to image.
    File f = new File(mCurrentPhotoPath);
    Uri contentUri = Uri.fromFile(f);
    media.setData(contentUri);
    this.sendBroadcast(media);
}
profile for Vineet Shukla at Stack Overflow, Q&A for professional and enthusiast programmers