Check whether the sd card is available or not programatically?

Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);

if(isSDPresent) {
  // yes SD-card is present available
}
else   {
 // Sorry no sd card available
}

Calculate the time difference between two time fields?

long difference = date2.getTime() - date1.getTime(); 

days = (int) (difference / (1000*60*60*24));  
hours = (int) ((difference - (1000*60*60*24*days)) / (1000*60*60)); 
min = (int) (difference - (1000*60*60*24*days) - (1000*60*60*hours)) / (1000*60);

Multiple Selection Listview in Android?

  • In this example, we will create a ListView with multiple selection mode with button click event. On button click event, we retrieve the selected list view items and create a Bundle with array of selected items and store it in Intent and start another activity (ResultActivity).
  • ResultActivity retrieves the array and displays the result in ListView.

XML layout files

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <Button
        android:id="@+id/testbutton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="submit" />

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_above="@id/testbutton"
        android:layout_alignParentTop="true" />

</RelativeLayout>

resultactivity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearlayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ListView
        android:id="@+id/outputList"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</LinearLayout>


Activity classes

MainActivity.java

 public class MainActivity extends Activity implements OnClickListener {
    Button button;
    ListView listView;
    ArrayAdapter<String> adapter;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewsById();
        String[] data = { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",
    "Cricket", "Tennis", "Foodball", "Tabletennis", "Hockey", "Golf", "Handball", "Vollyball",
    "Chess", "More" };
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, data);
        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        listView.setAdapter(adapter);
        button.setOnClickListener(this);
    }
    private void findViewsById() {
        listView = (ListView) findViewById(R.id.list);
        button = (Button) findViewById(R.id.testbutton);
    }
    public void onClick(View v) {
        SparseBooleanArray checked = listView.getCheckedItemPositions();
        ArrayList<String> selectedItems = new ArrayList<String>();
        for (int i = 0; i < checked.size(); i++) {
            // Item position in adapter
            int position = checked.keyAt(i);
            // Add sport if it is checked i.e.) == TRUE!
            if (checked.valueAt(i))
                selectedItems.add(adapter.getItem(position));
        }
        String[] outputStrArr = new String[selectedItems.size()]; 
        for (int i = 0; i < selectedItems.size(); i++) {
            outputStrArr[i] = selectedItems.get(i);
        }
        Intent intent = new Intent(getApplicationContext(),  ResultActivity.class); 
        // Create a bundle object
        Bundle b = new Bundle();
        b.putStringArray("selectedItems", outputStrArr); 
        // Add the bundle to the intent.
        intent.putExtras(b); 
        // start the ResultActivity
        startActivity(intent);
    }
}

ResultActivity.java

package com.example.multiblecheckboxs;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ResultActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.resultactivity);

Bundle b = getIntent().getExtras();
String[] resultArr = b.getStringArray("selectedItems");
ListView lv = (ListView) findViewById(R.id.outputList);

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
         android.R.layout.simple_list_item_1, resultArr);
lv.setAdapter(adapter);
}
}

Output




Changing Edit-text status to password programmatically.


EditText edit = new EditText(MainActivity.this);
String temporary_stored_text = edit.getText().toString().trim();
edit.setTransformationMethod(PasswordTransformationMethod.getInstance());
edit.setText(temporary_stored_text);

Android Facebook login Using Facebook sdk3.0

First we check Facebook session in open or not Useing this

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCurrContext = this;
setContentView(R.layout.fb_activity_main);
facebook_button = (Button) findViewById(R.id.LikeFB_Button);

Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
        fb_session = Session.openActiveSessionFromCache(mCurrContext);

If Your Facebook session in null and not open state click this button to login facebook

          Button button =(Button) findViewById(R.id.button_share);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (fb_session != null && fb_session.isOpened()) {
makeMeRequest(fb_session);
Log.i("Facebook Login State == >", "Facebook Login State");
} else {
if (fb_session == null) {
fb_session = new Session(mCurrContext);          
       }
Session.setActiveSession(fb_session);
ConnectToFacebook();
  Log.i("Facebook not Login State == >", "Facebook Not login State");
}
}
});
   }

This methods used for Login to Facebook Session

  private void ConnectToFacebook(){
Session session = Session.getActiveSession();
        if (!session.isOpened() && !session.isClosed()) {
        Log.i("ConnectToFacebook  if == >", "ConnectToFacebook if");
        OpenRequest newSession = new Session.OpenRequest(this);
        newSession.setCallback(callback);
        session.openForRead(newSession);          
        try {
        Session.OpenRequest request = new Session.OpenRequest(this);
        request.setPermissions(Arrays.asList("email"));
        } catch (Exception e) {
        e.printStackTrace();
        }
        } else {
        Log.i("ConnectToFacebook  else == >", "ConnectToFacebook else");
            Session.openActiveSession(this, true, callback);        
        }
}

private Session.StatusCallback callback = new Session.StatusCallback() {
       public void call(final Session session, final SessionState state, final Exception exception) {
           onSessionStateChange(session, state, exception);
       }
   };
 
   private void onSessionStateChange(final Session session, SessionState state, Exception exception) {
       if (session != null && session.isOpened()) {
        makeMeRequest(session);
       }
   }
 
   private void makeMeRequest(final Session session) {
     Request request = Request.newMeRequest(session, new Request.GraphUserCallback() {
    public void onCompleted(GraphUser user, Response response) {
    try{
      //UserInfoDisplay(user);
    //FrieddsInfoDisplay(session);
       } catch (Exception e) {
    e.printStackTrace();
    }
    }
    });              
       request.executeAsync();
   }

NOTE:

InManifestfile you Implement facebook login activity like this

  <activity
            android:name="com.facebook.LoginActivity"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />        

        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/app_id" />

And your App id create create in  res/values/string
  Like this

<resources>   
    <string name="app_id">FACEBOOKAPPLICATIONID</string> 
</resources> 

Android Store data and Image to server?

First Declare file to global like this
private File file;
After that convert to Drawable Image to Bitmap usein this two lines

Drawable myDrawable = getResources().getDrawable(R.drawable.logo);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
After that call your method where we want  "SaveImage_State" and give String name by default

SaveImage_State(myLogo, "name");


private String SaveImage_State(Bitmap finalBitmap, String name) {
String root = Environment.getExternalStorageDirectory().toString() + "/pm";
File myDir = new File(root);
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = name + ".jpg";
file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return file.toString();
}


Call this where you want button on click like ......


AsyncTask<Void, Void, HttpEntity> editProfileTask = new AsyncTask<Void, Void, HttpEntity>() {
        
@Override
 protected HttpEntity doInBackground(Void... params) {          
 HttpClient httpclient = new DefaultHttpClient();
 HttpPost httppost = new HttpPost("Your url"); // your url

 try {                     
 MultipartEntity reqEntity = new MultipartEntity();
  reqEntity.addPart("firstname",new StringBody(firstnameEV.getText().toString(),
   "text/plain",Charset.forName("UTF-8")));
                   "text/plain",Charset.forName("UTF-8")));
 if (file != null) {
   reqEntity.addPart("image",new FileBody(((File) file),"application/zip"));
 }         
 httppost.setEntity(reqEntity);
 HttpResponse resp = httpclient.execute(httppost);          
 HttpEntity resEntity = resp.getEntity();
  return resEntity;
 } catch (ClientProtocolException e) {
  e.printStackTrace();
 } catch (IOException e) {
  e.printStackTrace();
 }return null;
 }
   @Override
   protected void onPostExecute(HttpEntity resEntity) {
     if (resEntity != null) {             
       try {
         JSONObject responseJsonObject = new JSONObject(EntityUtils.toString(resEntity));
          String status = responseJsonObject.getString("status");             
           if (status.equals("success")) {
                Toast.makeText(activity, "Your Profile is updated", Toast.LENGTH_LONG).show();
                 String data = responseJsonObject.getString("data");              
                 isUpdatedSuccessfully=true;            
           } else {
              Toast.makeText(activity, "Profile not updated", Toast.LENGTH_LONG).show();
         }
        } catch (Exception e) {
       e.printStackTrace();
      }
        }            
  }
       };
 editProfileTask.execute(null, null, null);
      



Android GridView with full Image?

GridView layout in one of the most useful layouts in android. Gridview is mainly useful when we want show data in grid layout like displaying images or icons. This layout can be used to build applications like image viewer, audio or video players in order to show elements in grid manner.




1). Create a new project by going to File ⇒ New Android Project and fill required details.  
2). Prepare your images which you want to show in grid layout and place them in res ⇒ drawable-hdpi folder.
3).Create a new XML layout under layout and name it as 


<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/grid_view"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:numColumns="auto_fit"
    android:columnWidth="90dp"
    android:horizontalSpacing="10dp"
    android:verticalSpacing="10dp"
    android:gravity="center"
    android:stretchMode="columnWidth" >  

</GridView>

Android Disable and Enable WIFI, GORS and Mobile Data state useing Toggle Button?


Wifi_State.java

public class Wifi_State extends Activity {
private int bv;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wifi);

bv = Build.VERSION.SDK_INT;

ToggleButton togglegps = (ToggleButton) findViewById(R.id.GpsButton);
togglegps
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {

if (isChecked) {
turnOnDataConnection(true, Wifi_State.this);
Toast.makeText(getApplicationContext(),
"gprs Enabled!", Toast.LENGTH_LONG).show();
} else {
turnOnDataConnection(false, Wifi_State.this);
Toast.makeText(getApplicationContext(),
"gprs Disabled!", Toast.LENGTH_LONG).show();
}
}
});

ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleButton);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
toggleWiFi(true);
Toast.makeText(getApplicationContext(), "Wi-Fi Enabled!",
Toast.LENGTH_LONG).show();
} else {
toggleWiFi(false);
Toast.makeText(getApplicationContext(), "Wi-Fi Disabled!",
Toast.LENGTH_LONG).show();
}

if (isChecked) {
// Button is ON
Log.i("", "true");
Intent intent = new Intent(
"android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
sendBroadcast(intent);

String provider = Settings.Secure.getString(
getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (!provider.contains("gps")) { // if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings",
"com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
} else {
// Button is OFF
Log.i("", "false");
String provider = Settings.Secure.getString(
getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (provider.contains("gps")) { // if gps is enabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings",
"com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}
}
});
}

   // this is used for mobile data on and off condition

boolean turnOnDataConnection(boolean ON, Context context) {

try {
if (bv == Build.VERSION_CODES.FROYO)

{
Method dataConnSwitchmethod;
Class<?> telephonyManagerClass;
Object ITelephonyStub;
Class<?> ITelephonyClass;

TelephonyManager telephonyManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);

telephonyManagerClass = Class.forName(telephonyManager
.getClass().getName());
Method getITelephonyMethod = telephonyManagerClass
.getDeclaredMethod("getITelephony");
getITelephonyMethod.setAccessible(true);
ITelephonyStub = getITelephonyMethod.invoke(telephonyManager);
ITelephonyClass = Class.forName(ITelephonyStub.getClass()
.getName());

if (ON) {
dataConnSwitchmethod = ITelephonyClass
.getDeclaredMethod("enableDataConnectivity");
} else {
dataConnSwitchmethod = ITelephonyClass
.getDeclaredMethod("disableDataConnectivity");
}
dataConnSwitchmethod.setAccessible(true);
dataConnSwitchmethod.invoke(ITelephonyStub);

} else {
final ConnectivityManager conman = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
final Class<?> conmanClass = Class.forName(conman.getClass()
.getName());
final Field iConnectivityManagerField = conmanClass
.getDeclaredField("mService");
iConnectivityManagerField.setAccessible(true);
final Object iConnectivityManager = iConnectivityManagerField
.get(conman);
final Class<?> iConnectivityManagerClass = Class
.forName(iConnectivityManager.getClass().getName());
final Method setMobileDataEnabledMethod = iConnectivityManagerClass
.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(iConnectivityManager, ON);
}
return true;
} catch (Exception e) {
Log.e("TAG", "error turning on/off data");
return false;
}
}

public void toggleWiFi(boolean status) {
WifiManager wifiManager = (WifiManager) this
.getSystemService(Context.WIFI_SERVICE);
if (status == true && !wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(true);
} else if (status == false && wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(false);
}
}
}

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" >

    <ToggleButton
        android:id="@+id/toggleButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/imageView1"
        android:layout_alignLeft="@+id/imageView1"
        android:layout_marginBottom="37dp"
        android:text="ToggleButton" />
</RelativeLayout>

And give this permissions to You `Androidmanifest.xml`

   <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
    <uses-permission android:name="android.permission.WAKE_LOCK"/>

Android Check GPS State On and Off condition useing Toggle Button?

MainActivity.java

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

final ToggleButton tB = (ToggleButton) findViewById(R.id.toggleButton);
tB.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
if (tB.isChecked()) {
// Button is ON
Log.i("", "true");
Intent intent = new Intent(
"android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
sendBroadcast(intent);

String provider = Settings.Secure.getString(
getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (!provider.contains("gps")) { // if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings",
"com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
} else {
// Button is OFF
Log.i("", "false");
String provider = Settings.Secure.getString(
getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (provider.contains("gps")) { // if gps is enabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings",
"com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}
}
});
}
}

activity.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" >

    <LinearLayout
        android:id="@+id/toggleButton1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <ToggleButton
            android:id="@+id/toggleButton"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="50dp"
            android:layout_marginRight="50dp"
            android:layout_marginTop="50dp"
            android:text="ToggleButton" />
    </LinearLayout>

</RelativeLayout>

and give permissions to in  `Androidmanifest.xml ` like this 

      <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />    
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>

Android Orientation changes With out reload Activity?

In API level 13 or above, the screen size changes when the orientation changes, so this still causes the activity to be destroyed and started when orientation changes.
Simply add the "screenSize" attribute  in `Androidmanifest.xml`
<activity
    android:name=".YourActivityName"
    android:configChanges="orientation|screenSize">
</activity>
Now, when your change orientation (and screen size changes), the activity keeps its state and onConfigurationChanged() is called. This will keep whatever is on the screen.  

Reference: See this Articals
And here is Another way see picture 


Android Select image from gallery and display in imageview?

GallerysampleActivity.java  
 

  public class GallerysampleActivity extends Activity {
private static Bitmap Image = null;
private static Bitmap rotateImage = null;
private ImageView imageView;
private static final int GALLERY = 1;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

imageView = (ImageView) findViewById(R.id.imageView1);

Button gallery = (Button) findViewById(R.id.button1);
gallery.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

imageView.setImageBitmap(null);
if (Image != null)Image.recycle();
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), GALLERY);
}
});
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == GALLERY && resultCode != 0) {
Uri mImageUri = data.getData();
try {

Image = Media.getBitmap(this.getContentResolver(), mImageUri);
if (getOrientation(getApplicationContext(), mImageUri) != 0) {
Matrix matrix = new Matrix();
matrix.postRotate(getOrientation(getApplicationContext(), mImageUri));
if (rotateImage != null)
rotateImage.recycle();
rotateImage = Bitmap.createBitmap(Image, 0, 0, Image.getWidth(), Image.getHeight(), matrix,
true);
imageView.setImageBitmap(rotateImage);
} else
imageView.setImageBitmap(Image);
} catch (FileNotFoundException e) {

e.printStackTrace();
} catch (IOException e) {

e.printStackTrace();
}
}
}

public static int getOrientation(Context context, Uri photoUri) {
/* it's on the external media. */
Cursor cursor = context.getContentResolver().query(photoUri,
new String[] { MediaStore.Images.ImageColumns.ORIENTATION }, null, null, null);

if (cursor.getCount() != 1) {
return -1;
}

cursor.moveToFirst();
return cursor.getInt(0);
}
}

main.xml 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="100dp"
        android:layout_marginTop="20dp"
        android:text="Go to gallery" />


    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

Output Images






Select DateRange UsingRangePicker.

  /* * This Method is for select range from picker. * */ private fun selectDateRangeUsingRangePicker () { pageNumber = 1 val displ...