Saturday, 26 July 2014

Android Example With ViewPager for Swiping Left to Right and Viceversa

ViewPager With Fragment in Android

Android Example With ViewPager for Swiping Left to Right and Viceversa

The Project Contains Swiping of Contact from Left to Right and ViceVersa.

MainActivity.java

public class MainActivity extends ActionBarActivity {

private static final int NUMBER_OF_PAGES = 10;

private ViewPager mViewPager;
private DataFragmentPagerAdapter mMyFragmentPagerAdapter;

ArrayList<Contact> contactsList;

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.viewpager);

contactsList = new ArrayList<Contact>();

prepareData();


mMyFragmentPagerAdapter = new DataFragmentPagerAdapter(
getSupportFragmentManager(), contactsList);
mViewPager.setAdapter(mMyFragmentPagerAdapter);
}

private void prepareData() {

contactsList.add(new Contact("pratap1", "5121390971"));
contactsList.add(new Contact("pratap2", "5121390972"));
contactsList.add(new Contact("pratap3", "5121390973"));
contactsList.add(new Contact("pratap4", "5121390974"));
contactsList.add(new Contact("pratap5", "5121390975"));
contactsList.add(new Contact("pratap6", "5121390976"));
contactsList.add(new Contact("pratap7", "5121390977"));

}


}


PageFragment .java

public class PageFragment extends Fragment {
 
    public static PageFragment newInstance(Contact singleContact) {

        PageFragment pageFragment = new PageFragment();
        Bundle bundle = new Bundle();
      /*  bundle.putString("name", singleContact.getName());
        bundle.putString("phone", singleContact.getPhone());
        pageFragment.setArguments(bundle);*/
     
        bundle.putSerializable("contact", singleContact);
        pageFragment.setArguments(bundle);
     
        return pageFragment;
    }
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
   
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
         
        View view = inflater.inflate(R.layout.fragment, container, false);
        final TextView textView1 = (TextView) view.findViewById(R.id.textView1);
        final TextView textView2 = (TextView) view.findViewById(R.id.textView2);
     
        Contact cont= (Contact) getArguments().getSerializable("contact");
     
        textView1.setText(cont.getName());
        textView2.setText(cont.getPhone());
     
        Button btnClick=(Button) view.findViewById(R.id.btnClick);
     
        btnClick.setOnClickListener(new  OnClickListener() {

@Override
public void onClick(View v) {

Toast.makeText(getActivity(), "Clciked "+textView1.getText().toString(), Toast.LENGTH_SHORT).show();

}
});
     
     
        return view;
    }
}


DataFragmentPagerAdapter.java

public  class DataFragmentPagerAdapter extends FragmentPagerAdapter {

ArrayList<Contact> users;

public DataFragmentPagerAdapter(FragmentManager fm, ArrayList<Contact> usersList) {
super(fm);
this.users=usersList;
}

@Override
public Fragment getItem(int index) {

return PageFragment.newInstance(users.get(index));
}

@Override
public int getCount() {

return users.size();
}
}


Contact.java

public class Contact implements Serializable{

private String name;

public Contact(String name, String phone) {
super();
this.name = name;
this.phone = phone;
}

private String phone;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}

}


activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.pratap.androidviewpager.MainActivity"
     >

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
       />

</RelativeLayout>

fragment.xml

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

    <Button
        android:id="@+id/btnClick"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:text="Click ME" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:text="Medium Text"
        android:layout_margin="5dp"
        android:textAppearance="?android:attr/textAppearanceMedium" />
 
</RelativeLayout>


Screenshots 




Download Source code for the entire project

Friday, 25 July 2014

Read Excel Sheet Programatically From Assets Folder in Android

Hi,

In one of my Project, I need to read an excel file data which is in assets folder.


1) Create Project in Android using Eclipse.
2) Download poi Java Library or After Downloading take this  poi-3.10-FINAL-20140208.jar file and add to the libs folder and add to Build Path.

3) Place an excel sheet in assets folder in your project.

4) Copy the following code in your activity

MainActivity.java

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
public class MainActivity extends ActionBarActivity implements OnClickListener {

 private Button btnReadExcel1;
 AssetManager assetManager;

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

  btnReadExcel1 = (Button) findViewById(R.id.btnReadExcel1);

  btnReadExcel1.setOnClickListener(this);

  assetManager = getAssets();

 }

 
 @Override
 public void onClick(View v) {

  if (v.getId() == R.id.btnReadExcel1) {

   readExcelFileFromAssets();

  }

 }

 public void readExcelFileFromAssets() {

  try {
   // Creating Input Stream
   /*
    * File file = new File( filename); FileInputStream myInput = new
    * FileInputStream(file);
    */

   InputStream myInput;

                       //  Don't forget to Change to your assets folder excel sheet
   myInput = assetManager.open("contacts.xls");

   // Create a POIFSFileSystem object
   POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);

   // Create a workbook using the File System
   HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);

   // Get the first sheet from workbook
   HSSFSheet mySheet = myWorkBook.getSheetAt(0);

   /** We now need something to iterate through the cells. **/
   Iterator<Row> rowIter = mySheet.rowIterator();

   while (rowIter.hasNext()) {
    HSSFRow myRow = (HSSFRow) rowIter.next();
    Iterator<Cell> cellIter = myRow.cellIterator();
    while (cellIter.hasNext()) {
     HSSFCell myCell = (HSSFCell) cellIter.next();
     Log.e("FileUtils", "Cell Value: " + myCell.toString()+ " Index :" +myCell.getColumnIndex());
     // Toast.makeText(getApplicationContext(), "cell Value: " +
     // myCell.toString(), Toast.LENGTH_SHORT).show();
    }
   }
  } catch (Exception e) {
   e.printStackTrace();
  }

  return;
 }
}



5) Note : For Output 

Please see the logcat in Eclipse for the data.

Import both project and AppCompat v7 Library. 

6) Download the full source code

Friday, 18 July 2014

Get Address using Reverse Geocoding and Showing Google Map V2 in Android

Get Address using Reverse Geocoding and ShowingGoogle Map V2 in Android


======================
GPSTracker .java
=======================
public class GPSTracker extends Service implements LocationListener {

private final Context mContext;

// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS status
boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude

// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

// Declaring a Location Manager
protected LocationManager locationManager;

public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}

public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);

// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);

// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}

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

return location;
}

/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}

/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}

// return latitude
return latitude;
}

/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}

// return longitude
return longitude;
}

/**
* Function to check GPS/wifi enabled
* @return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}

/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
   
        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
            }
        });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
}

@Override
public void onLocationChanged(Location location) {

latitude = location.getLatitude();
longitude = location.getLongitude();
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}

@Override
public IBinder onBind(Intent arg0) {
return null;
}

}



===================================
ShowAddressGoogleMap .java
==================================
public class ShowAddressGoogleMap extends ActionBarActivity {

GoogleMap googleMap;

GPSTracker gps;

double latitude = 0.0;
double longitude = 0.0;

private TextView tvAddress;
private Button btnSave;
private ProgressBar mActivityIndicator;

String addressText;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.showaddressmap);
tvAddress = (TextView) findViewById(R.id.tvAddress);

btnSave = (Button) findViewById(R.id.btnSave);
mActivityIndicator = (ProgressBar) findViewById(R.id.address_progress);
mActivityIndicator.setVisibility(View.GONE);

try {
// Loading map
initilizeMap();

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

setLocation();

btnSave.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

UIUtils.showToast(getApplicationContext(), ""+addressText);

}
});

}

private void setLocation() {
// TODO Auto-generated method stub
gps = new GPSTracker(this);
// check if GPS enabled
if (gps.canGetLocation()) {

latitude = gps.getLatitude();
longitude = gps.getLongitude();

// \n is for new line
/*
* Toast.makeText( getApplicationContext(),
* "Your Location is - \nLat: " + latitude + "\nLong: " + longitude,
* Toast.LENGTH_LONG).show();
*/

showGoogleMap();

getAddress();
} else {
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}

@SuppressLint("NewApi")
public void getAddress() {
// Ensure that a Geocoder services is available
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD
&& Geocoder.isPresent()) {
// Show the activity indicator

/*
* Reverse geocoding is long-running and synchronous. Run it on a
* background thread. Pass the current location to the background
* task. When the task finishes, onPostExecute() displays the
* address.
*/

if (gps.canGetLocation() && gps.isNetworkEnabled) {

(new GetAddressTask(this)).execute(gps.getLocation());
}
else
{
tvAddress.setText("No Internet Connection");
}

}

}

private void showGoogleMap() {

int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());

// Showing status
if (status != ConnectionResult.SUCCESS) {
// Google Play Services are not available

int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();

} else {

// googleMap.setMyLocationEnabled(true);

LatLng currentposition = null;
currentposition = new LatLng(latitude, longitude);

// position1

MarkerOptions markerOptions1 = new MarkerOptions();
markerOptions1.position(currentposition);

markerOptions1.title("Your Location");
markerOptions1.snippet("Lat: " + latitude + ", Lng: " + longitude);
markerOptions1.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_launcher));

googleMap.addMarker(markerOptions1);

googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
currentposition, 15));

googleMap.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);

}

}

/**
* function to load map. If map is not created it will create it for you
* */
private void initilizeMap() {
if (googleMap == null) {
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
googleMap = fm.getMap();

// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}

@Override
protected void onResume() {
super.onResume();
initilizeMap();
}

public class GetAddressTask extends AsyncTask<Location, Void, String> {
Context mContext;

public GetAddressTask(Context context) {
super();
mContext = context;
}

/**
* Get a Geocoder instance, get the latitude and longitude look up the
* address, and return it
*
* @params params One or more Location objects
* @return A string containing the address of the current location, or
*         an empty string if no address can be found, or an error
*         message
*/
@Override
protected String doInBackground(Location... params) {
mActivityIndicator.setVisibility(View.VISIBLE);
Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
// Get the current location from the input parameter list
Location loc = params[0];
// Create a list to contain the result address
List<Address> addresses = null;
try {
/*
* Return 1 address.
*/
addresses = geocoder.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
} catch (IOException e1) {
Log.e("LocationSampleActivity",
"IO Exception in getFromLocation()");
e1.printStackTrace();
return ("IO Exception trying to get address");
} catch (IllegalArgumentException e2) {
// Error message to post in the log
String errorString = "Illegal arguments "
+ Double.toString(loc.getLatitude()) + " , "
+ Double.toString(loc.getLongitude())
+ " passed to address service";
Log.e("LocationSampleActivity", errorString);
e2.printStackTrace();
return errorString;
}
// If the reverse geocode returned an address
if (addresses != null && addresses.size() > 0) {
// Get the first address
Address address = addresses.get(0);
/*
* Format the first line of address (if available), city, and
* country name.
*/

addressText = String.format(
"%s, %s, %s, %s ",
// If there's a street address, add it
address.getMaxAddressLineIndex() > 0 ? address
.getAddressLine(0) : "", address
.getAddressLine(1), address.getAddressLine(2), // Locality
// is
// usually
// a
// city

// The country of the address
address.getCountryName());
// Return the text
return addressText;
} else {
return "No address found";
}
}

@Override
protected void onPostExecute(String address) {
// Set activity indicator visibility to "gone"
mActivityIndicator.setVisibility(View.GONE);
// Display the results of the lookup.
tvAddress.setText(address);
}
}
}

=======================
XML Layout file
========================
<LinearLayout 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"
    
    android:orientation="vertical" >

    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="8.5"
        class="com.google.android.gms.maps.SupportMapFragment" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:orientation="horizontal"
       
        android:background="#C9C9C9"
        >

        <TextView
            android:id="@+id/tvAddress"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Address :"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <Button
            android:id="@+id/btnSave"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:text="Save" />

        <ProgressBar
            android:id="@+id/address_progress"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true" />

    </RelativeLayout>

</LinearLayout>


======================
AndroidManifest file
=====================
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.your.app"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <permission
        android:name="com.infodat.trackme.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

  
    <!-- for maps -->

    <uses-permission android:name="com.infodat.trackme.permission.MAPS_RECEIVE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.FLASHLIGHT" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
               
          <activity
            android:name="com.your.app.ShowAddressGoogleMap"
            android:label="@string/app_name" >
          <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
      

        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="your key" />
    </application>

</manifest>

Monday, 14 July 2014

Get Contact Name from Mobile Number in Android

A Simple Function to get the contact Name from Mobile Number in Android


public String retrieveContactRecord(Context context, String phoneNo) {
try {
Uri uri = Uri.withAppendedPath(
ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(phoneNo));
String[] projection = new String[] {
ContactsContract.PhoneLookup._ID,
ContactsContract.PhoneLookup.DISPLAY_NAME };
String selection = null;
String[] selectionArgs = null;
String sortOrder = ContactsContract.PhoneLookup.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
ContentResolver cr = context.getContentResolver();
if (cr != null) {
Cursor resultCur = cr.query(uri, projection, selection,
selectionArgs, sortOrder);
if (resultCur != null) {
while (resultCur.moveToNext()) {
contactId = resultCur
.getString(resultCur
.getColumnIndex(ContactsContract.PhoneLookup._ID));
contactName = resultCur
.getString(resultCur
.getColumnIndexOrThrow(ContactsContract.PhoneLookup.DISPLAY_NAME));
Log.e("Info", "Contact Id : " + contactId);
Log.e("Info", "Contact Display Name : " + contactName);

break;
}
resultCur.close();

}
}
} catch (Exception sfg) {
Log.e("Error", "Error in loadContactRecord : " + sfg.toString());
return phoneNo;
}

return contactName;
}


 AndroidManifest.xml
==================

 <!-- for contacts -->
    <uses-permission android:name="android.permission.READ_CONTACTS" />

Lottie Android Example

Render After Effects animations natively on Android using this Great Library https://github.com/airbnb/lottie-android Let's see ho...