Monday, August 26, 2013

Get the address using current latitude and longitude

Hi Guys,

Today I am sharing the code of getting the current address from the current latitude and longitude.
For implementing this concept we need to use the Geocoder. So here question is arises what is Geocoder?

Geocoder is a class for handling geocoding and reverse geocoding. Geocoding is the process of transforming a street address or other description of a location into a (latitude, longitude) coordinate. Reverse geocoding is the process of transforming a (latitude, longitude) coordinate into a (partial) address.

 The amount of detail in a reverse geocoded location description may vary, for example one might contain the full street address of the closest building, while another might contain only a city name and postal code.

The Geocoder class requires a backend service that is not included in the core android framework. The Geocoder query methods will return an empty list if there no backend service in the platform. Use the isPresent() method to determine whether a Geocoder implementation exists.
More about the GeoCoder and related method visit here GeoCoder

activity_main.xml









MainActivity.java

package com.sunil.address;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.example.addressfromlatlong.R;


public class MainActivity extends Activity implements OnClickListener{

private EditText result;
private Button btngetAddress;
private Context context=null;
private ProgressDialog dialog = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;

result=(EditText)findViewById(R.id.editText_result);
btngetAddress=(Button)findViewById(R.id.button_getAddress);
btngetAddress.setOnClickListener(this);


}
@Override
public void onClick(View arg0) {

dialog = ProgressDialog.show(context, "","Please wait..", true);
GetCurrentAddress currentadd=new GetCurrentAddress();
currentadd.execute();
}


public String getAddress(Context ctx, double latitude, double longitude) {
StringBuilder result = new StringBuilder();
try {
Geocoder geocoder = new Geocoder(ctx, Locale.getDefault());
List

addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (addresses.size() > 0) {
Address address = addresses.get(0);

String locality=address.getLocality();
String city=address.getCountryName();
String region_code=address.getCountryCode();
String zipcode=address.getPostalCode();
double lat =address.getLatitude();
double lon= address.getLongitude();

result.append(locality+" ");
result.append(city+" "+ region_code+" ");
result.append(zipcode);

}
} catch (IOException e) {
Log.e("tag", e.getMessage());
}

return result.toString();
}

private class GetCurrentAddress extends AsyncTask {

@Override
protected String doInBackground(String... urls) {
// this lat and log we can get from current location but here we given hard coded
double latitude=12.916523125961666;
double longitude=77.61959824603072;

String address= getAddress(context, latitude, longitude);
return address;
}

@Override
protected void onPostExecute(String resultString) {
dialog.dismiss();
result.setText(resultString);

}
}
}




 
You can download the source code GetAddress

Friday, August 23, 2013

Out Of Memory Exception during decode image from imagepath

Hi Guys!

Today In this tutorial we are sharing the code and knowledge about the out of memory exception when we are loading the image on imageview in the listview.
Images come in all shapes and sizes. In many cases they are larger than required for a typical application user interface (UI). For example, the system Gallery application displays photos taken using your Android devices's camera which are typically much higher resolution than the screen density of your device.
Given that you are working with limited memory, ideally you only want to load a lower resolution version in memory. The lower resolution version should match the size of the UI component that displays it. An image with a higher resolution does not provide any visible benefit, but still takes up precious memory and incurs additional performance overhead due to additional on the fly scaling.

Most of the time when we are taking the picture from the Camera or from the Gallery the image is too large. In that case when we are going to decode the image from the image path then it throw the out of memory exception just because of the when decoding the image that time it store in heap of memory. That contain the small size for executing this process. That's why it give the out of memory exception.

So the solution is: we need to decode the via FileOutPutStream or make it first re size the image after we can decode. Both are working perfect in my side. But when we showing the image in list view and we are not resizing the image then our listview working very slow just because of the large image size. So we need to scale the image first.

Here I am giving the three option to decode the image from the image path.

1. When decode the image via normal way.

  
  String imageInSD = "/sdcard/UserImages/" + userImageName;
Bitmap bitmap = BitmapFactory.decodeFile(imageInSD);

It gives the most of the time out of memory exception when image size is large. So we need to use Bitmap Option for the same.
    String imageInSD = "/sdcard/UserImages/" + userImageName;
BitmapFactory.Options options=null;
options = new BitmapFactory.Options();
options.inSampleSize = 2;
Bitmap bitmap = BitmapFactory.decodeFile(imageInSD, null, options);


But this is not a good solution for the decode the image. Some time it also gives the Out Of Memory Exception . So let comes in the second way.

2. Decode the Image from the image path via FileInputStream and FileOutputStream.


public static Bitmap convertBitmap(String path)   {

Bitmap bitmap=null;
BitmapFactory.Options bfOptions=new BitmapFactory.Options();
bfOptions.inDither=false; //Disable Dithering mode
bfOptions.inPurgeable=true; //Tell to gc that whether it needs free memory, the Bitmap can be cleared
bfOptions.inInputShareable=true; //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future
bfOptions.inTempStorage=new byte[32 * 1024];


File file=new File(path);
FileInputStream fs=null;
try {
fs = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}

try {
if(fs!=null)
{
bitmap=BitmapFactory.decodeFileDescriptor(fs.getFD(), null, bfOptions);
}
} catch (IOException e) {

e.printStackTrace();
} finally{
if(fs!=null) {
try {
fs.close();
} catch (IOException e) {

e.printStackTrace();
}
}
}

return bitmap;
}

It does not give the Exception, we can use this to show the image on a particular imageview.
But It have certain limitation, After the decode we can not make the scale of this bitmap. And Its size will be same as a large so it makes slow to show in the list veiw.
So lets come the third way to decode the image from the image path. This one is the best and optamized solution which have seen the above.
If you want to make a small image from large image with height and width like 60 and 60 and scroll the listview fast then use this concept

3. First Resize the Image Size and then after Decode the Image From Image Path.


public static Bitmap decodeSampledBitmapFromPath(String path, int reqWidth,
int reqHeight) {

final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);

options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);

// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap bmp = BitmapFactory.decodeFile(path, options);
return bmp;
}

public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {

final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;

if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float) height / (float) reqHeight);
} else {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
}
return inSampleSize;
}

If you want to decode the image from the Drawable or the Resources then use this way.

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {

// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);

// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}


public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;

if (height > reqHeight || width > reqWidth) {

// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);

// Choose the smallest ratio as inSampleSize value, this will guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}

return inSampleSize;
}

If you want any help then visit the android developer site Here.

I hope You Guys enjoying this concept. (PL do not forget to give feedback).
Cheers !!

 

Monday, August 19, 2013

OrmLite Database in Android

Hi Guys!,

Today we are learning about the OrmLite database in android.
OrmLite is the lightweight java ORM supports for android Sqlite Database. The full OrmLite is Object Relational Mapping (ORMLite). and it provide some light weight functionality to store and retrieve java objects. OrmLite avoiding the complexity and more standard  Object Relational Mapping.

ORMLite supports more than one database  using JDBC and also sqlite with native calls to android api. Access Object classes. also provides simple and flexible query using QueryBuilder. Auto generates SQL to create and drop database tables and its have basic supports for database.
OrmLite simpley add Objects of java using annotations and it have powerful abstract Database Object classes also provides simple and flexible query using QueryBuilder. Auto generates SQL to create and drop database tables. And it have basic supports for database transactions.

Object Relational Mapping Lite (ORM Lite) provides some lightweight functionality for persisting Java objects to SQL databases while avoiding the complexity and overhead of more standard ORM packages. It supports a number of SQL databases using JDBC and also supports Sqlite with native calls to Android OS database APIs.

Users that are connecting to SQL databases via JDBC connections will need to download the ormlite-jdbc-4.46.jarand ormlite-core-4.46.jar files. For use with Android applications, you should download the ormlite-android-4.46.jar and ormlite-core-4.46.jar files.

Here is the link to download these jar files OrmLite Jars.
Or more ablout the ORMLite you can visit the ORL Developer site Here.

So In that scenario you need to first create the Pojo class means data model. Lets start the coding.



main.xml






row.xml






Person.java

package com.sunil.ormlite;

import com.j256.ormlite.field.DatabaseField;

public class Person {

@DatabaseField(generatedId = true)
private int id;
@DatabaseField
private String name;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

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

}

DatabaseHelper.java

package com.sunil.ormlite;
import java.sql.SQLException;
import java.util.List;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

public class DatabaseHelper extends OrmLiteSqliteOpenHelper {

private Context context;
private static final String DATABASE_NAME = "ormliteandroid.db";
private static final int DATABASE_VERSION = 1;

private Dao simpleDao = null;
private RuntimeExceptionDao simpleRuntimeDao = null;

public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
context = context;
}

public Dao getDao() throws SQLException {
if (simpleDao == null) {
simpleDao = getDao(Person.class);
}
return simpleDao;
}

public RuntimeExceptionDao getSimpleDataDao() {
if (simpleRuntimeDao == null) {
simpleRuntimeDao = getRuntimeExceptionDao(Person.class);
}
return simpleRuntimeDao;
}

//method for list of person
public List GetData()
{
DatabaseHelper helper = new DatabaseHelper(context);
RuntimeExceptionDao simpleDao = helper.getSimpleDataDao();
List list = simpleDao.queryForAll();
return list;
}

//method for insert data
public int addData(Person person)
{
RuntimeExceptionDao dao = getSimpleDataDao();
int i = dao.create(person);
return i;
}

//method for delete all rows
public void deleteAll()
{
RuntimeExceptionDao dao = getSimpleDataDao();
List list = dao.queryForAll();
dao.delete(list);
}

@Override
public void close() {
super.close();
simpleRuntimeDao = null;
}

@Override
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
try {
Log.i(DatabaseHelper.class.getName(), "onCreate");
TableUtils.createTable(connectionSource, Person.class);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Can't create database", e);
throw new RuntimeException(e);
}
}

@Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
try {
Log.i(DatabaseHelper.class.getName(), "onUpgrade");
TableUtils.dropTable(connectionSource, Person.class, true);
onCreate(db, connectionSource);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Can't drop databases", e);
throw new RuntimeException(e);
}
}
}

NameAdapter.java

package com.sunil.ormlite;

import java.util.List;

import com.sunil.ormlite.R;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class NameAdapter extends ArrayAdapter {
private Context mContext;
private int row;
private List list ;

public NameAdapter(Context context, int textViewResourceId, List list) {
super(context, textViewResourceId, list);

this.mContext=context;
this.row=textViewResourceId;
this.list=list;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder holder;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(row, null);

holder = new ViewHolder();
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}


if ((list == null) || ((position + 1) > list.size()))
return view; // Can't extract item

Person obj = list.get(position);

holder.name = (TextView)view.findViewById(R.id.tvname);

if(null!=holder.name&&null!=obj&&obj.getName().length()!=0){
holder.name.setText(obj.getName());
}



return view;
}

public static class ViewHolder {
public TextView name;
}
}

MainActivity.java

package com.sunil.ormlite;

import java.util.List;

import com.sunil.ormlite.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnItemClickListener {
EditText etEntry;
ListView listView;
NameAdapter adapter = null;
DatabaseHelper helper;
List list;

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

listView = (ListView) findViewById(R.id.listView1);
listView.setOnItemClickListener(this);

etEntry = (EditText) findViewById(R.id.etentry);

helper = new DatabaseHelper(getApplicationContext());

setDataToAdapter();

}

public void adddata(View v) {
String strName = etEntry.getText().toString().trim();
if (TextUtils.isEmpty(strName)) {
showToast("Please Add your Name!!!");
return;
}

Person person = new Person();
person.setName(strName);

helper.addData(person);

showToast("Data Successfully Added");

setDataToAdapter();

}

private void setDataToAdapter() {

list = helper.GetData();

adapter = new NameAdapter(this, R.layout.row, list);
listView.setAdapter(adapter);

}

private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}

@SuppressWarnings("deprecation")
public void deletedata(View v) {

list = helper.GetData();

if (null != list && list.size() > 0) {
AlertDialog alert = new AlertDialog.Builder(MainActivity.this)
.create();
alert.setTitle("Delete ?");
alert.setMessage("Are you sure want to delete All data from Database");

alert.setButton("No", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.setButton2("Yes", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();

helper.deleteAll();
etEntry.setText("");
showToast("Removed All Data!!!");

setDataToAdapter();
}
});
alert.show();
} else {
showToast("No data found from the Database");
}
}

@Override
public void onItemClick(AdapterView parent, View view, int position,
long id) {
showToast(list.get(position).getName());
}
}

You can download the source code OrmLite Database in Android

Saturday, August 17, 2013

Section Header Listview in android

Hi Guys,

Today we are learning about the section header in android.
Listview are commonly used to display a large set of similar data. But in the section header list we can show the similar data list in the different and separate section of the list view.
Here I am using the adapter class for loading the view of list one by one by using get view method.
So lets start the coding about the section header.

layout/main.xml








layout/list_item_section.xml






layout/list_item_enty.xml

  













Item.java

package com.sunil.util;

public interface Item {

public boolean isSection();

}

SectionItem.java

package com.sunil.util;

public class SectionItem implements Item{

private final String title;

public SectionItem(String title) {
this.title = title;
}

public String getTitle(){
return title;
}

@Override
public boolean isSection() {
return true;
}

}

EntryItem.java

package com.sunil.util;


public class EntryItem implements Item{

public final String title;
public final String subtitle;

public EntryItem(String title, String subtitle) {
this.title = title;
this.subtitle = subtitle;
}

@Override
public boolean isSection() {
return false;
}

}

EntryAdapter.java

package com.sunil.util;

import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.sunil.sectionlist.R;

public class EntryAdapter extends ArrayAdapter {

private Context context;
private ArrayList items;
private LayoutInflater vi;

public EntryAdapter(Context context,ArrayList items) {
super(context,0, items);
this.context = context;
this.items = items;
vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}


@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;

final Item i = items.get(position);
if (i != null) {
if(i.isSection()){
SectionItem si = (SectionItem)i;
v = vi.inflate(R.layout.list_item_section, null);

v.setOnClickListener(null);
v.setOnLongClickListener(null);
v.setLongClickable(false);

final TextView sectionView = (TextView) v.findViewById(R.id.list_item_section_text);
sectionView.setText(si.getTitle());

}else{
EntryItem ei = (EntryItem)i;
v = vi.inflate(R.layout.list_item_entry, null);
final TextView title = (TextView)v.findViewById(R.id.list_item_entry_title);
final TextView subtitle = (TextView)v.findViewById(R.id.list_item_entry_summary);


if (title != null)
title.setText(ei.title);
if(subtitle != null)
subtitle.setText(ei.subtitle);
}
}
return v;
}

}

SectionListExampleActivity.java

package com.sunil.sectionactivity;

import java.util.ArrayList;

import com.sunil.util.EntryAdapter;
import com.sunil.util.EntryItem;
import com.sunil.util.Item;
import com.sunil.util.SectionItem;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
import com.sunil.sectionlist.R;

public class SectionListExampleActivity extends Activity implements OnItemClickListener{

ArrayList items = new ArrayList();
ListView listview=null;

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

listview=(ListView)findViewById(R.id.listView_main);

items.add(new SectionItem("My Friends"));
items.add(new EntryItem("Abhi Tripathi", "Champpu"));
items.add(new EntryItem("Sandeep Pal", "Sandy kaliya"));
items.add(new EntryItem("Amit Verma", "Budhiya"));
items.add(new EntryItem("Awadhesh Diwaker ", "Dadda"));

items.add(new SectionItem("Android Version"));
items.add(new EntryItem("Jelly Bean", "android 4.2"));
items.add(new EntryItem("IceCream Sandwich", "android 4.0"));
items.add(new EntryItem("Honey Comb", "android 3.0"));
items.add(new EntryItem("Ginger Bread ", "android 2.2"));

items.add(new SectionItem("Android Phones"));
items.add(new EntryItem("Samsung", "Gallexy"));
items.add(new EntryItem("Sony Ericson", "Xperia"));
items.add(new EntryItem("Nokiya", "Lumia"));

EntryAdapter adapter = new EntryAdapter(this, items);
listview.setAdapter(adapter);
listview.setOnItemClickListener(this);
}


@Override
public void onItemClick(AdapterView arg0, View arg1, int position, long arg3) {

EntryItem item = (EntryItem)items.get(position);
Toast.makeText(this, "You clicked " + item.title , Toast.LENGTH_SHORT).show();
}
}



You can download the source code Section Header ListView.

Cheers Guys! 

Sunday, August 11, 2013

ActionBar Tab Navigation in Android

Hi Guys!

In this tutorial we are learning about the ActionBar Tab Navigation means Swipe the Tab.
Swipe views provide lateral navigation between sibling screens such as tabs with a horizontal finger gesture (a pattern sometimes known as horizontal paging). This lesson teaches you how to create a tab layout with swipe views for switching between tabs.

For more details about the swipe the Tabs visit the android developer site Tab Swipe(Navigation).
I have implemented the tabs swipe by using the action bar and Fragment Page Adapter that is available in the android-support v4 library.
Implementation of PagerAdapter that represents each page as a Fragment that is persistently kept in the fragment manager as long as the user can return to the page.
For more details about the Fragment Page Adapter, please visit the android developer site Fragment Page Adapter.

With help of Fragment page Adapter we have implemented the Tabs Swipe(Navigation). Please watch the video for same.


So lets start the coding tabs swipe by using the action bar and fragment page adapter.

 

activity_main.xml






MainActivity.java

package com.sunil.actionbartabnavigation;

import com.sunil.actionabrtabnavigation.R;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.view.Menu;

public class MainActivity extends FragmentActivity {

ActionBar actionabar;
ViewPager viewpager;

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

actionabar = getActionBar();
actionabar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

viewpager = (ViewPager) findViewById(R.id.pager);
FragmentManager fm = getSupportFragmentManager();

/** Defining a listener for pageChange */
ViewPager.SimpleOnPageChangeListener pageChangeListener = new ViewPager.SimpleOnPageChangeListener(){
@Override
public void onPageSelected(int position) {
super.onPageSelected(position);
actionabar.setSelectedNavigationItem(position);
}
};

/** Setting the pageChange listner to the viewPager */
viewpager.setOnPageChangeListener(pageChangeListener);

/** Creating an instance of FragmentPagerAdapter */
MyFragmentPagerAdapter fragmentPagerAdapter = new MyFragmentPagerAdapter(fm);

viewpager.setAdapter(fragmentPagerAdapter);
actionabar.setDisplayShowTitleEnabled(true);

/** Defining tab listener */
ActionBar.TabListener tabListener = new ActionBar.TabListener() {

@Override
public void onTabReselected(Tab arg0, android.app.FragmentTransaction arg1) {

}

@Override
public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {
viewpager.setCurrentItem(tab.getPosition());

}

@Override
public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {

}
};

/** Creating Android Tab */
// Tab tab = actionabar.newTab().setText("My Friends").setIcon(R.drawable.myfriends).setTabListener(tabListener);
Tab tab = actionabar.newTab().setText("My Friends").setTabListener(tabListener);
actionabar.addTab(tab);
tab = actionabar.newTab().setText("Android Version").setTabListener(tabListener);
actionabar.addTab(tab);
tab = actionabar.newTab().setText("Android Phones").setTabListener(tabListener);
actionabar.addTab(tab);


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}

MyFriendsListFragment.java

package com.sunil.actionbartabnavigation;

import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;


public class MyFriendsListFragment extends ListFragment{

/** An array of items to display in ArrayList */
String myfriends_list[] = new String[]{
"Abhi Tripathi",
"Sandeep Pal",
"Avi Diwakar",
"Shishir Verma",
"Amit Verma"
};


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

/** Creating array adapter to set data in listview */
ArrayAdapter adapter = new ArrayAdapter(getActivity().getBaseContext(), android.R.layout.simple_list_item_multiple_choice, myfriends_list);
setListAdapter(adapter);

return super.onCreateView(inflater, container, savedInstanceState);

}

@Override
public void onStart() {
super.onStart();
/** Setting the multiselect choice mode for the listview */
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

}
}

MyAndroidPhonesListFragment.java

package com.sunil.actionbartabnavigation;

import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MyAndroidPhonesListFragment extends ListFragment{

private String myandroidphone[]=new String[]{
"Samsung Android",
"Sony Experia",
"Micromax",
"Nokiya Lumia",
"Windows phone"
};

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){

ArrayAdapter adapter = new ArrayAdapter(getActivity().getBaseContext(), android.R.layout.simple_list_item_multiple_choice, myandroidphone);
setListAdapter(adapter);

return super.onCreateView(inflater, container, savedInstanceState);

}

@Override
public void onStart() {
super.onStart();
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

}
}

MyAndroidVersionListFragment.java

package com.sunil.actionbartabnavigation;

import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MyAndroidVersionListFragment extends ListFragment{

/** An array of items to display in ArrayList */
String android_versions[] = new String[]{
"Jelly Bean",
"IceCrean Sandwich",
"Honey Comb",
"Gingerbread",
"Froyo"
};

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){

ArrayAdapter adapter = new ArrayAdapter(getActivity().getBaseContext(), android.R.layout.simple_list_item_multiple_choice, android_versions);
setListAdapter(adapter);

return super.onCreateView(inflater, container, savedInstanceState);

}

@Override
public void onStart() {
super.onStart();
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);

}
}

MyFragmentPagerAdapter.java

package com.sunil.actionbartabnavigation;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class MyFragmentPagerAdapter extends FragmentPagerAdapter{

final int PAGE_COUNT = 3;

public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);

}

/** This method will be invoked when a page is requested to create */
@Override
public Fragment getItem(int arg0) {
Bundle data = new Bundle();
switch(arg0){

/** Android tab is selected */
case 0:
MyFriendsListFragment myfriends = new MyFriendsListFragment();
data.putInt("current_page", arg0+1);
myfriends.setArguments(data);
return myfriends;

case 1:
MyAndroidVersionListFragment androidversion = new MyAndroidVersionListFragment();
data.putInt("current_page", arg0+1);
androidversion.setArguments(data);
return androidversion;

case 2:
MyAndroidPhonesListFragment androidphone = new MyAndroidPhonesListFragment();
data.putInt("current_page", arg0+1);
androidphone.setArguments(data);
return androidphone;
}

return null;
}

/** Returns the number of pages */
@Override
public int getCount() {
return PAGE_COUNT;
}

}






You can download the source code Action Bar Tab Navigation

ActionBar Tab ListFragment in Android

Hi Guys!

In this tutorial we are learning about the Action Bar Tab in android.
Action bar was introduced from API level 11. In this post I will explain how to create tab in action bar with fragments. The final result is shown below where user can move between tabs.

After these steps we have to create our tabs and add it to the action bar. In our example we create three different tabs. What we want is when user touches one of the tab the UI content changes. To achieve it we need two things:
  • Fragment that fills the UI when user changes the tab according to the tab selected
  • A listener that gets notification when user interacts with the tabs
 So we are using the List Fragment to show the list content when user touch on tab. So view the video for the same.


Lets Start the coding to make the tab by Action bar in Fragment Activity.

main_activity.xml



list_fragment.xml

 





MainActivity.java

package com.sunil.actionbartab;

import com.sunil.actionbartab.R;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class MainActivity extends FragmentActivity implements ActionBar.TabListener {

private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";

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

// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

// For each of the sections in the app, add a tab to the action bar.
actionBar.addTab(actionBar.newTab().setText("My Friends").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText(R.string.title_section2).setTabListener(this));
actionBar.addTab(actionBar.newTab().setText(R.string.title_section3).setTabListener(this));
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
getActionBar().setSelectedNavigationItem(savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
}
}

@Override
public void onSaveInstanceState(Bundle outState) {
outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar().getSelectedNavigationIndex());
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}



@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}

@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {

/**
* On first tab we will show our list
*/
if (tab.getPosition() == 0) {
MyFriendsListFragment simpleListFragment = new MyFriendsListFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.container, simpleListFragment).commit();
}
else if (tab.getPosition() == 1) {
AndroidList androidlidt = new AndroidList();
getSupportFragmentManager().beginTransaction().replace(R.id.container, androidlidt).commit();
}



else {

AndroidVersionList androidversionlist = new AndroidVersionList();
getSupportFragmentManager().beginTransaction().replace(R.id.container, androidversionlist).commit();
}
}

@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
}

MyFriendsListFragment.java

package com.sunil.actionbartab;

import com.sunil.actionbartab.R;

import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MyFriendsListFragment extends ListFragment {

private String myfriends[];

public MyFriendsListFragment() {

myfriends = new String[] {
"Sandeep Pal",
"Abhi Tripathi",
"Amit Verma",
"Awadhesh Diwakar",
"Shishir Verma",
"Ravi",
};
}


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

ListAdapter listAdapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, myfriends);
setListAdapter(listAdapter);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.list_fragment, container, false);
}

@Override
public void onListItemClick(ListView list, View v, int position, long id) {

Toast.makeText(getActivity(), getListView().getItemAtPosition(position).toString(), Toast.LENGTH_LONG).show();
}
}

AndroidList.java

package com.sunil.actionbartab;

import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class AndroidList extends ListFragment{

private String myandroidphone[];

public AndroidList() {

myandroidphone = new String[] {
"Samsung Gallexy S",
"Sony Experia",
"Nokiya Lumia",
"Google Nuxes",
"Micromax",

};
}

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

ListAdapter listAdapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, myandroidphone);
setListAdapter(listAdapter);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.list_fragment, container, false);
}

@Override
public void onListItemClick(ListView list, View v, int position, long id) {

Toast.makeText(getActivity(), getListView().getItemAtPosition(position).toString(), Toast.LENGTH_LONG).show();
}
}

AndroidVersionList.java

package com.sunil.actionbartab;

import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class AndroidVersionList extends ListFragment{

private String myandroidversions[];
public AndroidVersionList() {
myandroidversions= new String[] {
"Jelly Bean",
"Ice cream Sandwich",
"GingerBread",
"HoneyComb",
"Friyo",

};

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

ListAdapter listAdapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, myandroidversions);
setListAdapter(listAdapter);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.list_fragment, container, false);
}

@Override
public void onListItemClick(ListView list, View v, int position, long id) {

Toast.makeText(getActivity(), getListView().getItemAtPosition(position).toString(), Toast.LENGTH_LONG).show();
}
}





You can download the source code ActionBar ListFregment

Friday, August 9, 2013

DialogFragment in Android

Hi Guys!

In this tutorial we are learning about the dialog fragment.
A fragment that displays a dialog window, floating on top of its activity's window. This fragment contains a Dialog object, which it displays as appropriate based on the fragment's state. Control of the dialog (deciding when to show, hide, dismiss it) should be done through the API here, not with direct calls on the dialog.
More detail about the dialog fragment visit the android developer site Dialog Fragment.

So lets start the coding about the alert dialog in Fragment.

main.xml

    




MyAlertDialog,java

package com.sunil.alert;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.widget.Toast;

public class MyAlertDialogWIndow extends DialogFragment {

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

OnClickListener positiveClick = new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getActivity().getBaseContext(), "Application finishing ...", Toast.LENGTH_SHORT).show();
getActivity().finish();
}
};

OnClickListener negativeClick = new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getActivity().getBaseContext(), "No option selecting", Toast.LENGTH_SHORT).show();

}
};

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Do you want Yes or No ?");
builder.setNegativeButton("No", negativeClick);
builder.setPositiveButton("Yes", positiveClick);
builder.setTitle("Confirmation");
Dialog dialog = builder.create();
return dialog;
}

}

MainActivity.java

package com.sunil.alert;

import com.sunil.alert.R;
import android.app.Activity;
import android.app.FragmentManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Button click = (Button) findViewById(R.id.btn_quit);
click.setOnClickListener(this);

}
@Override
public void onClick(View v) {
FragmentManager fm = getFragmentManager();
MyAlertDialogWIndow alert = new MyAlertDialogWIndow();
alert.show(fm, "Alert_Dialog");

}
}


You can download the source code Dialog Fragment

Friday, August 2, 2013

Facebook Integration with Android App

Hi Guys!

Today I going to share about the Facebook Integration with Android App.
The Facebook SDK for Android is the easiest way to integrate your Android app with Facebook's platform. The SDK provides support for Login with Facebook authentication, reading and writing to Facebook APIs and support for UI elements such as pickers and dialogs.

What I am going to implement watch in video.



The First thing is Download and extract the SDK ZIP file. The resulting folder, facebook-android-sdk-3.0.2, contains the SDK itself. We need to add this sdk library with our new android app project.

Now the second thing is need to get the SHA1 (Hash Key). For this we need to download the openssl and install in our system and configure with the system environment variable. Here is the link to download the setup OpenSsl. 
And set the path like that C:\Program Files (x86)\GnuWin32\bin (this is default directory to install in your system).
In the next step we have to create a folder inside the C drive name "Android" and copy the debug.keystore (default directory in my system is "C:\Users\sunil\.android") and paste inside thie Android folder.

Now the time is to generate the sha1 key by using the keystore file so use this command
C:\>keytool -exportcert -alias androiddebugkey -keystore "C:\Android\debug.keystore" | openssl sha1 -binary | openssl base64



 Once run this command then it asking about password then give password "android". Then it will generate the app id.

Now need to use this app id with your Facebook account. So logged your Facebook Account and click on developer tab and click on Apps tab.

 
You need to registered as a developer and save your SHA1 key here.


In the next step we need to create the new app then go to dashboard Apps tab and create new app.

After that it show the app id and secret app id


So you can use this APP ID  in your android project.

Lets create the the android project name "First Android" and add the facebook sdk as a library.



Lets start the coding now.


activity_main.xml





MainActivity.java

package com.sunil;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;

public class MainActivity extends Activity {

// Your Facebook APP ID
private static String APP_ID = "Your APP_ID"; // Replace with your App ID

// Instance of Facebook Class
private Facebook facebook = new Facebook(APP_ID);
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;

// Buttons
Button btnFbLogin;
Button btnFbGetProfile;
Button btnPostToWall;
Button btnShowAccessTokens;

@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

btnFbLogin = (Button) findViewById(R.id.btn_fblogin);
btnFbGetProfile = (Button) findViewById(R.id.btn_get_profile);
btnPostToWall = (Button) findViewById(R.id.btn_fb_post_to_wall);
btnShowAccessTokens = (Button) findViewById(R.id.btn_show_access_tokens);
mAsyncRunner = new AsyncFacebookRunner(facebook);

/**
* Login button Click event
* */
btnFbLogin.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
Log.d("Image Button", "button Clicked");
loginToFacebook();
}
});

/**
* Getting facebook Profile info
* */
btnFbGetProfile.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
getProfileInformation();
}
});

/**
* Posting to Facebook Wall
* */
btnPostToWall.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
postToWall();
}
});

/**
* Showing Access Tokens
* */
btnShowAccessTokens.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
showAccessTokens();
}
});

}

/**
* Function to login into facebook
* */
@SuppressWarnings("deprecation")
public void loginToFacebook() {

mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);

if (access_token != null) {
facebook.setAccessToken(access_token);

btnFbLogin.setVisibility(View.INVISIBLE);

// Making get profile button visible
btnFbGetProfile.setVisibility(View.VISIBLE);

// Making post to wall visible
btnPostToWall.setVisibility(View.VISIBLE);

// Making show access tokens button visible
btnShowAccessTokens.setVisibility(View.VISIBLE);

Log.d("FB Sessions", "" + facebook.isSessionValid());
}

if (expires != 0) {
facebook.setAccessExpires(expires);
}

if (!facebook.isSessionValid()) {
facebook.authorize(this,
new String[] { "email", "publish_stream" },
new DialogListener() {

@Override
public void onCancel() {
// Function to handle cancel event
}

@Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();

// Making Login button invisible
btnFbLogin.setVisibility(View.INVISIBLE);

// Making logout Button visible
btnFbGetProfile.setVisibility(View.VISIBLE);

// Making post to wall visible
btnPostToWall.setVisibility(View.VISIBLE);

// Making show access tokens button visible
btnShowAccessTokens.setVisibility(View.VISIBLE);
}

@Override
public void onError(DialogError error) {
// Function to handle error

}

@Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors

}

});
}
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}


/**
* Get Profile information by making request to Facebook Graph API
* */
@SuppressWarnings("deprecation")
public void getProfileInformation() {
mAsyncRunner.request("me", new RequestListener() {
@Override
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
// Facebook Profile JSON data
JSONObject profile = new JSONObject(json);

// getting name of the user
final String name = profile.getString("name");

// getting email of the user
final String email = profile.getString("email");

runOnUiThread(new Runnable() {

@Override
public void run() {
Toast.makeText(getApplicationContext(), "Name: " + name + "\nEmail: " + email, Toast.LENGTH_LONG).show();
}

});


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

@Override
public void onIOException(IOException e, Object state) {
}

@Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}

@Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}

@Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}

/**
* Function to post to facebook wall
* */
@SuppressWarnings("deprecation")
public void postToWall() {
// post on user's wall.
facebook.dialog(this, "feed", new DialogListener() {

@Override
public void onFacebookError(FacebookError e) {
}

@Override
public void onError(DialogError e) {
}

@Override
public void onComplete(Bundle values) {
}

@Override
public void onCancel() {
}
});

}

/**
* Function to show Access Tokens
* */
public void showAccessTokens() {
String access_token = facebook.getAccessToken();

Toast.makeText(getApplicationContext(),
"Access Token: " + access_token, Toast.LENGTH_LONG).show();
}

/**
* Function to Logout user from Facebook
* */
@SuppressWarnings("deprecation")
public void logoutFromFacebook() {
mAsyncRunner.logout(this, new RequestListener() {
@Override
public void onComplete(String response, Object state) {
Log.d("Logout from Facebook", response);
if (Boolean.parseBoolean(response) == true) {
runOnUiThread(new Runnable() {

@Override
public void run() {
// make Login button visible
btnFbLogin.setVisibility(View.VISIBLE);

// making all remaining buttons invisible
btnFbGetProfile.setVisibility(View.INVISIBLE);
btnPostToWall.setVisibility(View.INVISIBLE);
btnShowAccessTokens.setVisibility(View.INVISIBLE);
}

});

}
}

@Override
public void onIOException(IOException e, Object state) {
}

@Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}

@Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}

@Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}

}






You can download the source code First Android.

 

Copyright @ 2013 Android Developers Tipss.