Monday, November 4, 2013

Multiple Row Item Deleted from Listview Android

Hi Guys!!

First of all Happy Diwali to all my friends and fans.

In this article we are learning the new android API concept that delete the multiple  row item of the list view.
Before we have knowledge about the delete the row item with the help of check box. But in new API-18 have provide the features to delete the multiple row item from the list-view without the check-box uses.

This feature is available inside the contextual action mode in higher android version 3.0. So here question is what is contextual action mode?
The contextual action mode is a system implementation of ActionMode that focuses user interaction toward performing contextual actions. When a user enables this mode by selecting an item, a contextual action bar appears at the top of the screen to present actions the user can perform on the currently selected item(s). While this mode is enabled, the user can select multiple items (if you allow it), deselect items, and continue to navigate within the activity (as much as you're willing to allow). The action mode is disabled and the contextual action bar disappears when the user deselects all items, presses the BACK button, or selects the Done action on the left side of the bar.

This event happen when the user performs a long-click on the view.  Contextual actions on groups of items in a ListView or GridView (allowing the user to select multiple items and perform an action on them all).
More details about this contextual menu. and MultiChoiceModeListener.

So lets start the to coding to see this features.


main_activity.xml









MainActivity.java

package com.sunil.listviewmuntilerowdelete;

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

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.ListView;

@SuppressLint("NewApi")
public class MainActivity extends Activity implements MultiChoiceModeListener{

private String[] myfriendname=null;
private String[] myfriendnickname=null;
private int[] photo=null;
ListView listView=null;
Context contex=null;
MyListAdapter adapter=null;
private List list=new ArrayList();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contex=this;
listView = (ListView) findViewById(R.id.listview);

myfriendname = new String[] { "Sunil Gupta", "Abhishek Tripathi","Sandeep Pal", "Amit Verma" };
myfriendnickname = new String[] { "sunil android", "Abhi cool","Sandy duffer", "Budhiya jokar"};
photo = new int[] { R.drawable.sunil, R.drawable.abhi, R.drawable.sandy, R.drawable.amit};

for(int index=0; index< myfriendname.length; index++){
MyFriendsSDetails details=new MyFriendsSDetails(myfriendname[index], myfriendnickname[index], photo[index]);
list.add(details);
}

adapter=new MyListAdapter(contex, list);
listView.setAdapter(adapter);
listView.setMultiChoiceModeListener(this);
listView.setChoiceMode(listView.CHOICE_MODE_MULTIPLE_MODAL);

}
@Override
public boolean onActionItemClicked(ActionMode arg0, MenuItem arg1) {
switch (arg1.getItemId()) {
case R.id.delete:
SparseBooleanArray selected = adapter.getSelectedIds();
for (int i = (selected.size() - 1); i >= 0; i--) {
if (selected.valueAt(i)) {
MyFriendsSDetails selecteditem = adapter.getItem(selected.keyAt(i));
adapter.remove(selecteditem);
}
}
// Close CAB
arg0.finish();
return true;
default:
return false;
}
}
@Override
public boolean onCreateActionMode(ActionMode arg0, Menu arg1) {
arg0.getMenuInflater().inflate(R.menu.main, arg1);
return true;

}
@Override
public void onDestroyActionMode(ActionMode arg0) {
adapter.removeSelection();
}
@Override
public boolean onPrepareActionMode(ActionMode arg0, Menu arg1) {
return false;
}
@Override
public void onItemCheckedStateChanged(ActionMode arg0, int arg1, long arg2, boolean arg3) {

final int checkedCount = listView.getCheckedItemCount();
arg0.setTitle(checkedCount + " Selected");
adapter.toggleSelection(arg1);
}

}

MyFriendsSDetails.java

package com.sunil.listviewmuntilerowdelete;

public class MyFriendsSDetails {

private String myfriendname=null;
private String myfriendnickname=null;
private int photo=0;

public MyFriendsSDetails(String friendname, String friendnickname, int myphoto){
this.myfriendname=friendname;
this.myfriendnickname=friendnickname;
this.photo=myphoto;
}

public String getMyfriendname() {
return myfriendname;
}

public void setMyfriendname(String myfriendname) {
this.myfriendname = myfriendname;
}

public String getMyfriendnickname() {
return myfriendnickname;
}

public void setMyfriendnickname(String myfriendnickname) {
this.myfriendnickname = myfriendnickname;
}

public int getPhoto() {
return photo;
}

public void setPhoto(int photo) {
this.photo = photo;
}


}

list_item.xml













MyListAdapter.java

package com.sunil.listviewmuntilerowdelete;

import java.util.List;

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

public class MyListAdapter extends ArrayAdapter{

Context context;
LayoutInflater inflater;
List list;
private SparseBooleanArray mSelectedItemsIds;

public MyListAdapter(Context context, List list) {
super(context, 0, list);
mSelectedItemsIds = new SparseBooleanArray();
this.context = context;
this.list = list;
inflater = LayoutInflater.from(context);
}

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

final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.list_item, null);
holder.name = (TextView) convertView.findViewById(R.id.title);
holder.nickname = (TextView) convertView.findViewById(R.id.subtitle);
holder.photo = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText(list.get(position).getMyfriendname());
holder.nickname.setText(list.get(position).getMyfriendnickname());
holder.photo.setImageResource(list.get(position).getPhoto());
return convertView;
}

public void toggleSelection(int position) {
selectView(position, !mSelectedItemsIds.get(position));
}

public void selectView(int position, boolean value) {
if (value)
mSelectedItemsIds.put(position, value);
else
mSelectedItemsIds.delete(position);
notifyDataSetChanged();
}

public void removeSelection() {
mSelectedItemsIds = new SparseBooleanArray();
notifyDataSetChanged();
}

public SparseBooleanArray getSelectedIds() {
return mSelectedItemsIds;
}
private class ViewHolder {
TextView name;
TextView nickname;
ImageView photo;
}
}
Screen shot:


You can download the full source code ListViewMultipleRowDelete and here

Cheers Guys!!

Sunday, October 13, 2013

Alarm via BoardCast Reciever Android

Hi Guys,

This tutorial might be helpful for leaning about the Alarm with Broadcast Receiver in android.
A Broadcast Receiver is an Android component which allows you to register for system or application events. All registered receivers for an event will be notified by the Android run-time once this event happens. 

A BroadcastReceiver object is only valid for the duration of the call to onReceive(Context, Intent). Once your code returns from this function, the system considers the object to be finished and no longer active.

If registering a receiver in your Activity.onResume() implementation, you should unregistered it in Activity.onPause(). (You won't receive intents when paused, and this will cut down on unnecessary system overhead). Do not unregistered in Activity.onSaveInstanceState(), because this won't be called if the user moves back in the history stack.  More detail about broadcast receiever Here.

Alarm Manager class provides access to the system alarm services. These allow you to schedule your application to be run at some point in the future. When an alarm goes off, the Intent that had been registered for it is broadcast by the system, automatically starting the target application if it is not already running. Registered alarms are retained while the device is asleep (and can optionally wake the device up if they go off during that time), but will be cleared if it is turned off and rebooted.

The Alarm Manager holds a CPU wake lock as long as the alarm receiver's onReceive() method is executing. This guarantees that the phone will not sleep until you have finished handling the broadcast. Once onReceive() returns, the Alarm Manager releases this wake lock. This means that the phone will in some cases sleep as soon as your onReceive() method completes.

There are two way we can registered and unregistered the broadcast receive.
1. Dynamic way
2. Static Way 

Dynamic way:-

You can register a receiver dynamically via the Context.registerReceiver() method. You can also dynamically unregister receiver by using Context.unregisterReceiver() method.

Static Way:-

You can use the PackageManager class to enable or disable receivers registered in your AndroidManifest.xml file.
For Register
ComponentName receiver = new ComponentName(this, AlarmManagerBR.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
For UnRegister
ComponentName receiver = new ComponentName(this, AlarmManagerBR.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);

main_activity.xml




MainActivity.java

package com.sunil.br;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{

private Button btnstartalarm=null;
private Button btncancelalarm=null;
private Button btnenablebr=null;
private Button btndiablebr=null;
AlarmManager amanager=null;
PendingIntent pi=null;

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

btnstartalarm = (Button)findViewById(R.id.button_startalarm);
btncancelalarm = (Button)findViewById(R.id.button_cancelalarm);
btnenablebr = (Button)findViewById(R.id.button_enablebr);
btndiablebr = (Button)findViewById(R.id.button_disablebr);

btnstartalarm.setOnClickListener(this);
btndiablebr.setOnClickListener(this);
btncancelalarm.setOnClickListener(this);
btnenablebr.setOnClickListener(this);

}

@Override
public void onClick(View arg0) {

if(arg0==btnstartalarm)
{
amanager=(AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
Intent intent= new Intent(this, AlarmManagerBR.class);
pi=PendingIntent.getBroadcast(this, 0, intent, 0);
//After after 2 seconds
amanager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000*4, pi);
Toast.makeText(this, "Start Repating Alarm", Toast.LENGTH_SHORT).show();

}
else if (arg0==btncancelalarm) {

amanager.cancel(pi);
Toast.makeText(this, "Canceled Alarm", Toast.LENGTH_SHORT).show();
}

else if(arg0==btnenablebr){

ComponentName receiver = new ComponentName(this, AlarmManagerBR.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
Toast.makeText(this, "Enable Boradcast Reciever", Toast.LENGTH_SHORT).show();
}
else if (arg0==btndiablebr) {

ComponentName receiver = new ComponentName(this, AlarmManagerBR.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
Toast.makeText(this, "Diable Boradcast Reciever", Toast.LENGTH_SHORT).show();
}
}
}

AlarmManagerBR.java

package com.sunil.br;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class AlarmManagerBR extends BroadcastReceiver{

@SuppressLint("SimpleDateFormat")
@Override
public void onReceive(Context arg0, Intent arg1) {

StringBuilder sb=new StringBuilder();
SimpleDateFormat format=new SimpleDateFormat("hh:mm:ss a");
sb.append(format.format(new Date()));
Toast.makeText(arg0, sb, Toast.LENGTH_SHORT).show();
}

}

Manifest.xml


















You can download the source code BoradCastRecieverExample
Cheers Guys!!

Saturday, October 5, 2013

Insert And Retrieve Image into DB

Hi Guys,

In this tutorial we are sharing the code to insert the image into db and retrieve the image from db. I hope this article might be helpful to all learning developer.

SQLite is really a quick and compact android database technology which incorporates SQL syntax to create queries and also handle data.

Android SDK by itself provides the SQLite support which without doubt making the setup as well as utilization process within our applications with no trouble.

Whenever we make use of an Android SQLite Database all of us undoubtedly require the help of SQLiteOpenHelper to handle our data.SQLiteOpenHelper is surely an superb destination to place some initial values right into the android sqlite database when it is built.

For storing the image we are using the blob type. Blob is a Java interface representing the SQL BLOB type.
An SQL BLOB type stores a large array of binary data (bytes) as the value in a column of a database.
The java.sql.Blob interface provides methods for setting and retrieving data in the Blob, for querying Blob data length, and for searching for data within the Blob. More details about Blob Here

But i think in big level storing the image in database is not valuable because database sqlite have limited space so store the image path is valuable.

main_activity.xml








MainActivity.java

package com.sunil.insertimageindb;

import java.io.ByteArrayOutputStream;

import com.sunil.insertimageindb.R;

import android.os.Bundle;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{

private ImageView imageview=null;
private Button btninsert=null;
private Button btnretrive=null;
private MyDataBase mdb=null;
private SQLiteDatabase db=null;
private Cursor c=null;
private byte[] img=null;
private static final String DATABASE_NAME = "ImageDb.db";
public static final int DATABASE_VERSION = 1;

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

btninsert=(Button)findViewById(R.id.button_insert);
btnretrive= (Button)findViewById(R.id.button_retrieve);
imageview= (ImageView)findViewById(R.id.imageView_image);
imageview.setImageResource(0);
btninsert.setOnClickListener(this);
btnretrive.setOnClickListener(this);
mdb=new MyDataBase(getApplicationContext(), DATABASE_NAME,null, DATABASE_VERSION);


Bitmap b=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
ByteArrayOutputStream bos=new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 100, bos);
img=bos.toByteArray();
db=mdb.getWritableDatabase();
}
@Override
public void onClick(View arg0) {

if(btninsert==arg0)
{
ContentValues cv=new ContentValues();
cv.put("image", img);
db.insert("tableimage", null, cv);
Toast.makeText(this, "inserted successfully", Toast.LENGTH_SHORT).show();
}
else if(btnretrive==arg0)
{
String[] col={"image"};
c=db.query("tableimage", col, null, null, null, null, null);

if(c!=null){
c.moveToFirst();
do{
img=c.getBlob(c.getColumnIndex("image"));
}while(c.moveToNext());
}
Bitmap b1=BitmapFactory.decodeByteArray(img, 0, img.length);

imageview.setImageBitmap(b1);
Toast.makeText(this, "Retrive successfully", Toast.LENGTH_SHORT).show();
}
}

}

MyDatabase.java

package com.sunil.insertimageindb;


import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

public class MyDataBase extends SQLiteOpenHelper{

public MyDataBase(Context context, String dbname, CursorFactory factory, int dbversion) {
super(context, dbname, factory, dbversion);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table tableimage(image blob);");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

}

Store the image in db looks like that


You can download the source code InsertImageintoDB.
Cheers Guys!!

Wednesday, October 2, 2013

PayPal Android SDK With Multiple In-App Payment

Hi Guys,

I hope this tutorial and article might be helpful for all android developer to make a multiple payment with this new android sdk pay pal in app.
PayPal announced a new Android SDK that tries to make it easier for developers to accept in-app payments on Google�s mobile platform.
As expected, the Android payments solution accepts both PayPal and credit card payments. The company says it is quick and easy to use, and �removes payment friction so developers can focus on creating amazing experiences.�

PayPal�s strategy is to make it as easy as possible for mobile developers to integrate its payments into their work. The pitch is simple: if consumers don�t have to leave your app to pay, and they can do so in more ways than one (click a PayPal button or scan a credit/debit card), they will be more likely to do so.

The new PayPal Android SDK supports Android version 2.2 and up. The new Android payment solution will allow developers to accept payments via PayPal and via credit cards. PayPal believes that giving users the option to pay quickly and easily via their PayPal account or by scanning a credit card will lure more customers into paying developers for their work.

PayPal says that it is also offering security features that will allow developers to �significantly reduce� fraud they encounter with payments. So I think that its really amazing concept for android developer.
More in detail visit the pay pal developer site and git-hub repository Pay Pay Developer.

 
 

main_activity.xml




MainActivity.java

package com.paypal.sunil.paypalandroidsdk;

import java.math.BigDecimal;

import org.json.JSONException;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.paypal.android.sdk.payments.PayPalPayment;
import com.paypal.android.sdk.payments.PayPalService;
import com.paypal.android.sdk.payments.PaymentActivity;
import com.paypal.android.sdk.payments.PaymentConfirmation;

public class MainActivity extends Activity {

// set to PaymentActivity.ENVIRONMENT_LIVE to move real money.
// set to PaymentActivity.ENVIRONMENT_SANDBOX to use your test credentials from https://developer.paypal.com
// set to PaymentActivity.ENVIRONMENT_NO_NETWORK to kick the tires without communicating to PayPal's servers.
private static final String CONFIG_ENVIRONMENT = PaymentActivity.ENVIRONMENT_NO_NETWORK;

// note that these credentials will differ between live & sandbox environments.
private static final String CONFIG_CLIENT_ID = "credential from developer.paypal.com";
// when testing in sandbox, this is likely the -facilitator email address.
private static final String CONFIG_RECEIVER_EMAIL = "matching paypal email address";

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

Intent intent = new Intent(this, PayPalService.class);

intent.putExtra(PaymentActivity.EXTRA_PAYPAL_ENVIRONMENT, CONFIG_ENVIRONMENT);
intent.putExtra(PaymentActivity.EXTRA_CLIENT_ID, CONFIG_CLIENT_ID);
intent.putExtra(PaymentActivity.EXTRA_RECEIVER_EMAIL, CONFIG_RECEIVER_EMAIL);

startService(intent);
}

public void onBuyPressed(View pressed) {
PayPalPayment thingToBuy = new PayPalPayment(new BigDecimal("1.75"), "USD", "hipster jeans");

Intent intent = new Intent(this, PaymentActivity.class);

intent.putExtra(PaymentActivity.EXTRA_PAYPAL_ENVIRONMENT, CONFIG_ENVIRONMENT);
intent.putExtra(PaymentActivity.EXTRA_CLIENT_ID, CONFIG_CLIENT_ID);
intent.putExtra(PaymentActivity.EXTRA_RECEIVER_EMAIL, CONFIG_RECEIVER_EMAIL);

// It's important to repeat the clientId here so that the SDK has it if Android restarts your
// app midway through the payment UI flow.
intent.putExtra(PaymentActivity.EXTRA_CLIENT_ID, "credential-from-developer.paypal.com");
intent.putExtra(PaymentActivity.EXTRA_PAYER_ID, "your-customer-id-in-your-system");
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);

startActivityForResult(intent, 0);
}

@Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
PaymentConfirmation confirm = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null) {
try {
Log.i("paymentExample", confirm.toJSONObject().toString(4));

// TODO: send 'confirm' to your server for verification.
// see https://developer.paypal.com/webapps/developer/docs/integration/mobile/verify-mobile-payment/
// for more details.

} catch (JSONException e) {
Log.e("paymentExample", "an extremely unlikely failure occurred: ", e);
}
}
}
else if (resultCode == Activity.RESULT_CANCELED) {
Log.i("paymentExample", "The user canceled.");
}
else if (resultCode == PaymentActivity.RESULT_PAYMENT_INVALID) {
Log.i("paymentExample", "An invalid payment was submitted. Please see the docs.");
}
}

@Override
public void onDestroy() {
stopService(new Intent(this, PayPalService.class));
super.onDestroy();
}
}

Manifest.xml













































You can download the source code PaypalSDK

Saturday, September 28, 2013

Custom ListView AlertDialog With Filter and Search

Hi Guys,

I hope this tutorial might be helpful to all android developer to search or filter the item of the custom list view.
Here the list view which shows in Alert-dialog. And we can search the item of the list view.

Here I am creating the ListView and Editext programatically and search the item of the list view.
So lets start the coding to search the item of the listview in alert dialog.


Main_activity.xml






alertlistrow.xml








MainActivity.java

package com.sunil.listviewdialog;

import java.util.ArrayList;
import java.util.Arrays;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;

public class MainActivity extends Activity implements OnClickListener, OnItemClickListener{

private Button btn_listviewdialog=null;
private EditText txt_item=null;
private String TitleName[]={"Sunil Gupta","Ram Chnadra"," Abhishek Tripathi","Amit Verma","Sandeep Pal","Awadhesh Diwakar","Shishir Verma","Ravi Vimal","Prabhakr Singh","Manish Srivastva","Jitendra Singh","Surendra Pal"};
private ArrayList array_sort;
int textlength=0;
private AlertDialog myalertDialog=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

txt_item=(EditText)findViewById(R.id.editText_item);
btn_listviewdialog=(Button)findViewById(R.id.button_listviewdialog);
btn_listviewdialog.setOnClickListener(this);
}
@Override
public void onClick(View arg0) {

AlertDialog.Builder myDialog = new AlertDialog.Builder(MainActivity.this);

final EditText editText = new EditText(MainActivity.this);
final ListView listview=new ListView(MainActivity.this);
editText.setCompoundDrawablesWithIntrinsicBounds(R.drawable.discoverseed_larg1, 0, 0, 0);
array_sort=new ArrayList (Arrays.asList(TitleName));
LinearLayout layout = new LinearLayout(MainActivity.this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(editText);
layout.addView(listview);
myDialog.setView(layout);
CustomAlertAdapter arrayAdapter=new CustomAlertAdapter(MainActivity.this, array_sort);
listview.setAdapter(arrayAdapter);
listview.setOnItemClickListener(this);
editText.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged(Editable s){

}
public void beforeTextChanged(CharSequence s,
int start, int count, int after){

}
public void onTextChanged(CharSequence s, int start, int before, int count)
{
editText.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
textlength = editText.getText().length();
array_sort.clear();
for (int i = 0; i < TitleName.length; i++)
{
if (textlength <= TitleName[i].length())
{

if(TitleName[i].toLowerCase().contains(editText.getText().toString().toLowerCase().trim()))
{
array_sort.add(TitleName[i]);
}
}
}
listview.setAdapter(new CustomAlertAdapter(MainActivity.this, array_sort));
}
});
myDialog.setNegativeButton("cancel", new DialogInterface.OnClickListener() {

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

myalertDialog=myDialog.show();

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

myalertDialog.dismiss();
String strName=TitleName[position];
txt_item.setText(strName);
}

}

CustomAlertAdapter.java

package com.sunil.listviewdialog;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class CustomAlertAdapter extends BaseAdapter{

Context ctx=null;
ArrayList listarray=null;
private LayoutInflater mInflater=null;
public CustomAlertAdapter(Activity activty, ArrayList list)
{
this.ctx=activty;
mInflater = activty.getLayoutInflater();
this.listarray=list;
}
@Override
public int getCount() {

return listarray.size();
}

@Override
public Object getItem(int arg0) {
return null;
}

@Override
public long getItemId(int arg0) {
return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup arg2) {
final ViewHolder holder;
if (convertView == null ) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.alertlistrow, null);

holder.titlename = (TextView) convertView.findViewById(R.id.textView_titllename);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}

String datavalue=listarray.get(position);
holder.titlename.setText(datavalue);

return convertView;
}

private static class ViewHolder {
TextView titlename;
}
}





You can download the source code CustomListviewFilter.
Cheers Guys! 

Friday, September 27, 2013

Custom Time Picker with Time Interval of 15 minute.

Android it�s very easy to set the time using the android.widget.TimePicker component. In this tutorial we are going to see how the user can select the hour, and the minute using the android.app.TimePickerDialog which is an easy to use the dialog box.

In this tutorial I am creating the custom Time Picker with minute interval 00-15-30-45.

So lets start the coding to create the custom time picker in android.



activity_main.xml











MainActivity.java

package com.example.customtimepicker;

import java.util.Calendar;

import android.app.Activity;
import android.app.TimePickerDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TimePicker;

public class MainActivity extends Activity implements OnClickListener{

private EditText txt_time=null;
private Button btn_time=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

txt_time=(EditText)findViewById(R.id.editText_time);
btn_time=(Button)findViewById(R.id.button_time);
btn_time.setOnClickListener(this);
}
@Override
public void onClick(View arg0) {
CustomTimePickerDialog timePickerDialog = new CustomTimePickerDialog(MainActivity.this, timeSetListener,
Calendar.getInstance().get(Calendar.HOUR),
CustomTimePickerDialog.getRoundedMinute(Calendar.getInstance().get(Calendar.MINUTE) + CustomTimePickerDialog.TIME_PICKER_INTERVAL), true);
timePickerDialog.setTitle("Set hours and minutes");
timePickerDialog.show();
}

public static class CustomTimePickerDialog extends TimePickerDialog{

public static final int TIME_PICKER_INTERVAL=15;
private boolean mIgnoreEvent=false;

public CustomTimePickerDialog(Context context, OnTimeSetListener callBack, int hourOfDay, int minute, boolean is24HourView) {
super(context, callBack, hourOfDay, minute, is24HourView);
}

@Override
public void onTimeChanged(TimePicker timePicker, int hourOfDay, int minute) {
super.onTimeChanged(timePicker, hourOfDay, minute);
if (!mIgnoreEvent){
minute = getRoundedMinute(minute);
mIgnoreEvent=true;
timePicker.setCurrentMinute(minute);
mIgnoreEvent=false;
}
}

public static int getRoundedMinute(int minute){
if(minute % TIME_PICKER_INTERVAL != 0){
int minuteFloor = minute - (minute % TIME_PICKER_INTERVAL);
minute = minuteFloor + (minute == minuteFloor + 1 ? TIME_PICKER_INTERVAL : 0);
if (minute == 60) minute=0;
}

return minute;
}
}

private CustomTimePickerDialog.OnTimeSetListener timeSetListener = new CustomTimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
txt_time.setText(String.format("%02d", hourOfDay) + ":" +String.format("%02d", minute));
}
};
}







You can download the source code CustomTimePicker.

Cheers Guys!

Wednesday, September 18, 2013

File Upload on PHP Server in Android

Hi guys,

This tutorial might be helpful to all developer to upload the image or any file on the server. Most of the critical code that most of the beginner facing stuff to upload image on server.

For this using multipart boundary. So here question is arises what is multipart boundary and why use it?
The Content-Type field for multipart entities requires one parameter, "boundary", which is used to specify the encapsulation boundary. The encapsulation boundary is defined as a line consisting entirely of two hyphen characters ("-", decimal code 45) followed by the boundary parameter value from the Content-Type header field.
Thus, a typical multipart Content-Type header field might look like this:

 Content-Type: multipart/mixed; boundary=gc0p4Jq0M2Yt08jU534c0p 
 
This indicates that the entity consists of several parts, each itself with a structure that is syntactically identical to an RFC 822 message, except that the header area might be completely empty, and that the parts are each preceded by the line --gc0p4Jq0M2Yt08jU534c0p.

Things to Note:
  1. The encapsulation boundary must occur at the beginning of a line, i.e., following a CRLF (Carriage Return-Line Feed)
  2. The boundary must be followed immediately either by another CRLF and the header fields for the next part, or by two CRLFs, in which case there are no header fields for the next part (and it is therefore assumed to be of Content-Type text/plain).
  3. Encapsulation boundaries must not appear within the encapsulations, and must be no longer than 70 characters, not counting the two leading hyphens.
The encapsulation boundary following the last body part is a distinguished delimiter that indicates that no further body parts will follow. Such a delimiter is identical to the previous delimiters, with the addition of two more hyphens at the end of the line. More Details Here.

Here first I am using the code for getting the image from the gallery and set on image-view. And the set image path of the gallery  on textview and send to this path for upload the image.
Lets start the code:



main_activity.xml

 




MainActivity.java

package com.sunil.upload;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{

private TextView messageText;
private Button uploadButton, btnselectpic;
private ImageView imageview;
private int serverResponseCode = 0;
private ProgressDialog dialog = null;

private String upLoadServerUri = null;
private String imagepath=null;
@Override
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

uploadButton = (Button)findViewById(R.id.uploadButton);
messageText = (TextView)findViewById(R.id.messageText);
btnselectpic = (Button)findViewById(R.id.button_selectpic);
imageview = (ImageView)findViewById(R.id.imageView_pic);

btnselectpic.setOnClickListener(this);
uploadButton.setOnClickListener(this);
upLoadServerUri = "http://192.168.0.15/UploadToServer.php";
}


@Override
public void onClick(View arg0) {
if(arg0==btnselectpic)
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
}
else if (arg0==uploadButton) {

dialog = ProgressDialog.show(MainActivity.this, "", "Uploading file...", true);
messageText.setText("uploading started.....");
new Thread(new Runnable() {
public void run() {

uploadFile(imagepath);

}
}).start();
}

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

if (requestCode == 1 && resultCode == RESULT_OK) {
//Bitmap photo = (Bitmap) data.getData().getPath();

Uri selectedImageUri = data.getData();
imagepath = getPath(selectedImageUri);
Bitmap bitmap=BitmapFactory.decodeFile(imagepath);
imageview.setImageBitmap(bitmap);
messageText.setText("Uploading file path:" +imagepath);

}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}

public int uploadFile(String sourceFileUri) {


String fileName = sourceFileUri;

HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);

if (!sourceFile.isFile()) {

dialog.dismiss();

Log.e("uploadFile", "Source File not exist :"+imagepath);

runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :"+ imagepath);
}
});

return 0;

}
else
{
try {

// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);

// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);

dos = new DataOutputStream(conn.getOutputStream());

dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd);

dos.writeBytes(lineEnd);

// create a buffer of maximum size
bytesAvailable = fileInputStream.available();

bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];

// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);

while (bytesRead > 0) {

dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);

}

// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();

Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);

if(serverResponseCode == 200){

runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+" F:/wamp/wamp/www/uploads";
messageText.setText(msg);
Toast.makeText(MainActivity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
}
});
}

//close the streams //
fileInputStream.close();
dos.flush();
dos.close();

} catch (MalformedURLException ex) {

dialog.dismiss();
ex.printStackTrace();

runOnUiThread(new Runnable() {
public void run() {
messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(MainActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
}
});

Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {

dialog.dismiss();
e.printStackTrace();

runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(MainActivity.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;

} // End else block
}


}

UploadToServer.php

 < ?php

$file_path = "uploads/";

$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
echo "success";
} else{
echo "fail";
}
? >

Please put the UploadToServer.php file inside the www folder of the WAMP Server.
And create the folder uploads inside the www folder of the wamp. See the screen shot to upload the pictures.



You can download the source code file with php file UploadFileOnServer.
Cheers  Guys!

Saturday, September 14, 2013

Lazy Loading Image Download from Internet in android

Hi Guys,

Today we have share the knowledge about the lazy loading image download from the internet in android.
The images will downloaded very fast with the help of the multiple thread.

Images that are not visible on the initial page load are not loaded or downloaded until they come into the main viewing area. Once an image comes into view it is then downloaded and faded into visibility. Scroll down this page to see the action for same.

For this i am using the open source library universal image loader made by nostra. Here you can download the universal image loader library Here.

I added the video to show the lazy loading the image and show in the list view.


Lets start the coding about the lazy loading.

 

MainActivity.java

package com.sunil.lazyloading;


import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener{

private Button btnlist=null;

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

btnlist= (Button)findViewById(R.id.button_listview);
btnlist.setOnClickListener(this);
}
@Override
public void onClick(View arg0) {

Intent intent = new Intent(this, ImageListActivity.class);
intent.putExtra("stringarrayimage", Constants.IMAGES);
startActivity(intent);

}

}

CustomAdapter.java

package com.sunil.adapter;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.sunil.lazyloading.R;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CustomAdapter extends BaseAdapter{

private String imageurl[]=null;
private Context context=null;
DisplayImageOptions doption=null;
private ImageLoadingListener animateFirstListener =null;


public CustomAdapter(Activity activity, String[] imageurl)
{
this.context=activity;
this.imageurl=imageurl;
doption=new DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.ic_empty).showImageOnFail(R.drawable.ic_error).showStubImage(R.drawable.ic_stub).cacheInMemory(true).cacheOnDisc(true).displayer(new RoundedBitmapDisplayer(20)).build();
animateFirstListener = new AnimateFirstDisplayListener();
}

@Override
public int getCount() {
return imageurl.length;
}

@Override
public Object getItem(int arg0) {
return arg0;
}

@Override
public long getItemId(int arg0) {
return arg0;
}

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

View view = convertView;
final ViewHolder holder;

if (convertView == null) {
view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_list_row, parent, false);
holder = new ViewHolder();
holder.text = (TextView) view.findViewById(R.id.text);
holder.image = (ImageView) view.findViewById(R.id.image);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}

holder.text.setText("Item " + (position + 1));
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(imageurl[position], holder.image, doption, animateFirstListener);

return view;
}

private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {

static final List displayedImages = Collections.synchronizedList(new LinkedList());

@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}

private class ViewHolder {
public TextView text;
public ImageView image;
}
}

ImageListActivity.java

package com.sunil.lazyloading;


import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.sunil.adapter.CustomAdapter;

public class ImageListActivity extends Activity implements OnItemClickListener{

private ListView listview=null;
private String[] imageUrls;
protected ImageLoader imageLoader=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imagelist);

listview=(ListView)findViewById(R.id.listView_image);
imageLoader = ImageLoader.getInstance();
Bundle bundle = getIntent().getExtras();
imageUrls = bundle.getStringArray("stringarrayimage");
CustomAdapter adapter=new CustomAdapter(ImageListActivity.this, imageUrls);
listview.setAdapter(adapter);

listview.setOnItemClickListener(this);

}
@Override
public void onItemClick(AdapterView arg0, View arg1, int position, long arg3) {
Intent intent = new Intent(this, ImagePagerActivity.class);
intent.putExtra("imageurlpostion", imageUrls);
intent.putExtra("imagepostion", position);
startActivity(intent);

}

@Override
public void onBackPressed() {
AnimateFirstDisplayListener.displayedImages.clear();
super.onBackPressed();
}


private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {

static final List displayedImages = Collections.synchronizedList(new LinkedList());

@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item_clear_memory_cache:
imageLoader.clearMemoryCache();
return true;
case R.id.item_clear_disc_cache:
imageLoader.clearDiscCache();
return true;
default:
return false;
}
}
}

activity_main.xml




imagelist.xml







item_list_row.xml











You can download the source code Lazy Loading Image Cheers guys!

Sunday, September 8, 2013

Slide Menu Navigation Drawer in Android Sherlock

Hi Guys,

In this tutorial I describe about the slide menu navigation drawer in android. For this I have to use the Sherlock library as for supporting the Sherlock Fragment which is supported the lower version of API also.

ActionBarSherlock is an extension of the support library designed to facilitate the use of the action bar design pattern across all versions of Android with a single API.

The library will automatically use the native action bar when appropriate or will automatically wrap a custom implementation around your layouts. This allows you to easily develop an application with an action bar for every version of Android from 2.x and up.You can download the Sherlock library from Here.

Now you just import this library into your project area of eclipse. And Add this action sherlock library with your uses of project. How to Add the library with your project?
Right Click of your proejct -> Properties -> Android -> Add (click here and select your library).


In this library android support v4 library already there then there is no need to put android-support v4 library in your project. If this is availability in your project libs then remove from there.

Navigation Drawer:  The navigation drawer is a panel that transitions in from the left edge of the screen and displays the app�s main navigation options.
The user can bring the navigation drawer onto the screen by swiping from the left edge of the screen or by touching the application icon on the action bar. You can download the sample for same by use of Action Bar and more detail about Navigaion Drawert Here.

So in this tutorial I have implemented this navigation drawer features by using of sherlock library.
Here is the video you can watch what have implemented with this.


Now Lets Start the Coding to implements the Slid Menu Navigation Drawer in android.
 

activity_main.xml








MainActivity.java

package com.sunil.navigation;

import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;

public class MainActivity extends SherlockFragmentActivity implements OnItemClickListener{

private DrawerLayout drawlayout=null;
private ListView listview=null;
private ActionBarDrawerToggle actbardrawertoggle=null;

private String[] myfriendname=null;
private String[] myfriendnickname=null;
private int[] photo=null;
//Fragment fragment1 = new Fragment1();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

myfriendname = new String[] { "Sunil Gupta", "Abhishek Tripathi","Sandeep Pal", "Amit Verma" };
myfriendnickname = new String[] { "sunil android", "Abhi cool","Sandy duffer", "Budhiya jokar"};
photo = new int[] { R.drawable.sunil, R.drawable.abhi, R.drawable.sandy, R.drawable.amit};

drawlayout = (DrawerLayout)findViewById(R.id.drawer_layout);
listview = (ListView) findViewById(R.id.listview_drawer);

getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(true);

drawlayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
drawlayout.setBackgroundColor(Color.WHITE);

MenuListAdapter menuadapter=new MenuListAdapter(getApplicationContext(), myfriendname, myfriendnickname, photo);
listview.setAdapter(menuadapter);

actbardrawertoggle= new ActionBarDrawerToggle(this, drawlayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close)
{
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
}

public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);

}

};
drawlayout.setDrawerListener(actbardrawertoggle);

listview.setOnItemClickListener(this);

if (savedInstanceState == null) {
selectItem(0);
}
}

@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actbardrawertoggle.syncState();
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actbardrawertoggle.onConfigurationChanged(newConfig);
}

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

}


private void selectItem(int position) {

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

// Locate Position
switch (position) {
case 0:
Fragment1 fragment1=new Fragment1();
ft.replace(R.id.content_frame, fragment1);
Bundle b = new Bundle();
b.putString("name",myfriendname[position]);
b.putInt("photo",photo[position]);
fragment1.setArguments(b);
break;
case 1:
Fragment2 fragment2=new Fragment2();
ft.replace(R.id.content_frame, fragment2);
Bundle b1 = new Bundle();
b1.putString("name",myfriendname[position]);
b1.putInt("photo",photo[position]);
fragment2.setArguments(b1);
break;
case 2:
Fragment3 fragment3=new Fragment3();
ft.replace(R.id.content_frame, fragment3);
Bundle b2 = new Bundle();
b2.putString("name",myfriendname[position]);
b2.putInt("photo",photo[position]);
fragment3.setArguments(b2);
break;
case 3:
Fragment4 fragment4=new Fragment4();
ft.replace(R.id.content_frame, fragment4);
Bundle b3 = new Bundle();
b3.putString("name",myfriendname[position]);
b3.putInt("photo",photo[position]);
fragment4.setArguments(b3);
break;
}
ft.commit();
listview.setItemChecked(position, true);
setTitle(myfriendname[position]);
drawlayout.closeDrawer(listview);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

if(item.getItemId()==android.R.id.home)
{
if(drawlayout.isDrawerOpen(listview))
{
drawlayout.closeDrawer(listview);
}
else {
drawlayout.openDrawer(listview);
}
}
return super.onOptionsItemSelected(item);
}

}

drawer_list_item.xml














MenuListAdapter.java

package com.sunil.navigation;

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

public class MenuListAdapter extends BaseAdapter{

private Context context;
private String[] mtitle;
private String[] msubTitle;
private int[] micon;
private LayoutInflater inflater;

public MenuListAdapter(Context context, String title[], String subtilte[], int icon[])
{
this.context=context;
this.mtitle=title;
this.msubTitle=subtilte;
this.micon=icon;

}
@Override
public int getCount() {
return mtitle.length;
}

@Override
public Object getItem(int arg0) {
return arg0;
}

@Override
public long getItemId(int arg0) {
return arg0;
}

@Override
public View getView(int position, View arg1, ViewGroup parent) {

TextView title;
TextView subtitle;
ImageView icon;

inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.drawer_list_item, parent, false);

title = (TextView) itemView.findViewById(R.id.title);
subtitle = (TextView) itemView.findViewById(R.id.subtitle);
icon = (ImageView) itemView.findViewById(R.id.icon);

title.setText(mtitle[position]);
subtitle.setText(msubTitle[position]);
icon.setImageResource(micon[position]);

return itemView;

}

}

fragment1.xml
























Fragment1.java

package com.sunil.navigation;

import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragment;

public class Fragment1 extends SherlockFragment{

private ImageView imageview=null;
private TextView textname=null;
private TextView textdescription=null;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment1, container, false);

imageview=(ImageView)view.findViewById(R.id.imageView_pic);
textname=(TextView)view.findViewById(R.id.textView_name);
textdescription=(TextView)view.findViewById(R.id.textView_descroption);

textname.setTextColor(Color.BLACK);
textdescription.setTextColor(Color.BLACK);

Bundle bundle=this.getArguments();
if(bundle != null)
{
String name=bundle.getString("name");
int pic=bundle.getInt("photo");
textname.setText(name);
imageview.setImageResource(pic);
}

textdescription.setText("I'm currently working as Android developer, interested in a wide-range of technology topics, including programming languages, opensource and any other cool technology that catches my eye. I love developing apps for Android, designing and coding.");
return view;
}

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


}
}

Manifest.xml

















Same way you can add the Fragment2, Fragment3 and Fragment4. I have not added this classes to make clean this article.



You can download the source code ABSMenuNavigationDrawer and from GitHub

 

Copyright @ 2013 Android Developers Tipss.