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

Wednesday, September 4, 2013

Export And Import Data DB Table To CSV and Vice Versa

Hi Guys,

Today we are learning about the exporting and importing the table data from DB to CSV and CSV to DB table. In that tutorial first we are doing to insert the Person data into DB table by using the ORM open source. Then Exporting the same table data into the CSV file and stored in sd card.

For inserting the text data into sqlite table by using the ORM open source. More detail about the ORM open source in the last tutorial Here.

For exporting the db table we are using the opencsv.jar file. With the help of this jar file we are able to write and read the data of table and write into the CSV file. You can download the opencsv.jare file Here

In the next part we are sending to mail the csv file with attached with the help of android.content.Intent.ACTION_SEND.
So lets start the coding for the same.

activity_main.xml






















Person.java

package com.sunil.export;

import java.io.Serializable;

import com.j256.ormlite.field.DatabaseField;

public class Person implements Serializable{

@DatabaseField(generatedId=true)
private int id;
@DatabaseField
private String firtname;
@DatabaseField
private String lastname;
@DatabaseField
private String address;
@DatabaseField
private String email;


public Person(){

}

public Person(String fname, String lname, String address, String email){
this.firtname=fname;
this.lastname=lname;
this.address=address;
this.email=email;
}

public int getId() {
return id;
}

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

public String getFirtname() {
return firtname;
}

public void setFirtname(String firtname) {
this.firtname = firtname;
}

public String getLastname() {
return lastname;
}

public void setLastname(String lastname) {
this.lastname = lastname;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

}

DatabaseHelper.java

package com.sunil.export;

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.RuntimeExceptionDao;
import com.j256.ormlite.stmt.UpdateBuilder;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

public class DatabaseHelper extends OrmLiteSqliteOpenHelper {

private static final String TAG="DatabaseHelper";
private static final String DATABASE_NAME = "person.db";
private static final int DATABASE_VERSION = 1;
private RuntimeExceptionDao personRuntimeDao=null;

public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.v(TAG, "DatabaseHelper constructor call");
}


public RuntimeExceptionDao getPersonDataDao() {

Log.v(TAG, "getTimeDataDao call");

if (personRuntimeDao == null) {
personRuntimeDao = getRuntimeExceptionDao(Person.class);
}
return personRuntimeDao;
}
public int addPersonData(Person project)
{
Log.v(TAG, "addPersonData call");
RuntimeExceptionDao dao = getPersonDataDao();
int i = dao.create(project);
return i;
}

public List GetDataPerson()
{
Log.v(TAG, "GetDataPerson call");
RuntimeExceptionDao simpleDao = getPersonDataDao();
List list = simpleDao.queryForAll();
return list;
}

public void deleteAllPerson()
{
Log.v(TAG, "deleteAllPerson call");
RuntimeExceptionDao dao = getPersonDataDao();
List list = dao.queryForAll();
dao.delete(list);
}

public UpdateBuilder updatePersonData() throws SQLException
{
RuntimeExceptionDao simpleDao = getPersonDataDao();
UpdateBuilder updateBuilder = simpleDao.updateBuilder();
return updateBuilder;
}


@Override
public void close() {
super.close();
Log.v(TAG, "close call");
personRuntimeDao=null;
}

@Override
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
try {
Log.v(TAG, "onCreate call");
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.v(TAG, "onUpgrade call");
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);
}
}
}

MainActivity.java

package com.sunil.export;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.R.integer;
import android.R.string;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.CSVWriter;

public class MainActivity extends Activity implements OnClickListener{

private static final String TAG="MainActivity";
private Button btnexport=null;
private Button btnimport=null;
private Button btninsertdata=null;
private Button btnsendmail=null;
private EditText txtfirtsname;
private EditText txtlastname;
private EditText txtaddress;
private EditText txtto;
private EditText txtsubj;
private EditText txttextmsg;
private EditText txtemail;
DatabaseHelper dbhelper=null;
File file=null;

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

Log.v(TAG, "onCreate called");
txtfirtsname = (EditText)findViewById(R.id.editText_fname);
txtlastname = (EditText)findViewById(R.id.editText_lname);
txtaddress = (EditText)findViewById(R.id.editText_address);
txtemail = (EditText)findViewById(R.id.editText_email);
txtto = (EditText) findViewById(R.id.editText_to);
txtsubj = (EditText) findViewById(R.id.editText_subj);
txttextmsg = (EditText) findViewById(R.id.editText_text);

btnexport=(Button)findViewById(R.id.button_export);
btnexport.setOnClickListener(this);
btninsertdata=(Button)findViewById(R.id.button_Insert);
btninsertdata.setOnClickListener(this);
btnsendmail=(Button) findViewById(R.id.button_sendmail);
btnsendmail.setOnClickListener(this);
btnimport=(Button)findViewById(R.id.button_import);
btnimport.setOnClickListener(this);

dbhelper=new DatabaseHelper(getApplicationContext());
}
@Override
public void onClick(View arg0) {

Log.v(TAG, "onClick called");
if(arg0==btnexport){

ExportDatabaseCSVTask task=new ExportDatabaseCSVTask();
task.execute();
}

else if(arg0==btnimport){


File exportDir = new File(Environment.getExternalStorageDirectory(), "");
if (!exportDir.exists()) {
exportDir.mkdirs();
}

file = new File(exportDir, "PersonCSV.csv");
try {
CSVReader reader = new CSVReader(new FileReader(file));
String [] nextLine;
try {
while ((nextLine = reader.readNext()) != null) {

// nextLine[] is an array of values from the line

String fname=nextLine[0];
String lname=nextLine[1];
String address=nextLine[2];
String email=nextLine[3];

if(fname.equalsIgnoreCase("First Name"))
{

}
else
{
int value=dbhelper.addPersonData(new Person(fname,lname,address,email));
if(value==1)
{
Toast.makeText(getApplicationContext(), "Data inerted into table", Toast.LENGTH_LONG).show();
}
}

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

} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else if (arg0==btninsertdata) {

String firstname=txtfirtsname.getText().toString().trim();
String lastname=txtlastname.getText().toString().trim();
String addresss=txtaddress.getText().toString().trim();
String email=txtemail.getText().toString().trim();

if(firstname.length() < 1)
{
Toast.makeText(getApplicationContext(), "Please Enter First name", Toast.LENGTH_LONG).show();
}
else if (lastname.length() < 1) {
Toast.makeText(getApplicationContext(), "Please Enter Last name", Toast.LENGTH_LONG).show();
}
else if (addresss.length() < 1) {
Toast.makeText(getApplicationContext(), "Please Enter Address", Toast.LENGTH_LONG).show();
}
else if (email.length() < 1) {
Toast.makeText(getApplicationContext(), "Please Enter Email", Toast.LENGTH_LONG).show();
}
else {

Person person=new Person(firstname, lastname, addresss, email);
int status=dbhelper.addPersonData(person);
if(status==1)
{
Toast.makeText(getApplicationContext(), "Data inserted successfully.", Toast.LENGTH_LONG).show();
txtfirtsname.setText("");
txtlastname.setText("");
txtaddress.setText("");
txtemail.setText("");
}
}
}

else if (arg0==btnsendmail) {

String to=txtto.getText().toString().trim();
String subj=txtsubj.getText().toString().trim();
String msg=txttextmsg.getText().toString().trim();

if(to.length() < 1)
{
Toast.makeText(getApplicationContext(), "Please Enter Recipent Email", Toast.LENGTH_LONG).show();
}
else if (subj.length() < 1) {
Toast.makeText(getApplicationContext(), "Please Enter Subject", Toast.LENGTH_LONG).show();
}
else if (msg.length() < 1) {
Toast.makeText(getApplicationContext(), "Please Enter Message", Toast.LENGTH_LONG).show();
}
else {

Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("image/jpeg");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{to});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subj);
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, msg);
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(file.getAbsolutePath()));
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
}
}
}

private class ExportDatabaseCSVTask extends AsyncTask{
private final ProgressDialog dialog = new ProgressDialog(MainActivity.this);

@Override
protected void onPreExecute() {

this.dialog.setMessage("Exporting database...");
this.dialog.show();

}
protected Boolean doInBackground(final String... args){

File dbFile=getDatabasePath("person.db");
Log.v(TAG, "Db path is: "+dbFile); //get the path of db

File exportDir = new File(Environment.getExternalStorageDirectory(), "");
if (!exportDir.exists()) {
exportDir.mkdirs();
}

file = new File(exportDir, "PersonCSV.csv");
try {

file.createNewFile();
CSVWriter csvWrite = new CSVWriter(new FileWriter(file));

//ormlite core method
List listdata=dbhelper.GetDataPerson();
Person person=null;

// this is the Column of the table and same for Header of CSV file
String arrStr1[] ={"First Name", "Last Name", "Address", "Email"};
csvWrite.writeNext(arrStr1);

if(listdata.size() > 1)
{
for(int index=0; index < listdata.size(); index++)
{
person=listdata.get(index);
String arrStr[] ={person.getFirtname(), person.getLastname(), person.getAddress(), person.getEmail()};
csvWrite.writeNext(arrStr);
}
}

csvWrite.close();
return true;
}
catch (IOException e){
Log.e("MainActivity", e.getMessage(), e);
return false;
}
}

@Override
protected void onPostExecute(final Boolean success) {

if (this.dialog.isShowing()){
this.dialog.dismiss();
}
if (success){
Toast.makeText(MainActivity.this, "Export successful!", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MainActivity.this, "Export failed!", Toast.LENGTH_SHORT).show();
}
}
}
}

Manifest.xml



















You can download the source code from here ExportSqliteToCSV

Tuesday, September 3, 2013

Call logs in Android

Hi Guys!,

Today I am sharing the code to get the call logs of a android device. For Access the call logs we need to first the aware about Content Provider.

Content providers manage access to a structured set of data. They encapsulate the data, and provide mechanisms for defining data security. Content providers are the standard interface that connects data in one process with code running in another process.
More About the Content Provider you can visit the android developer site Here.

One of the most commonly used Content Providers is CallLog.Calls which is used to provide access to call logs data. Call logs contain information about outgoing, incoming and missed calls.  

Lets start the coding for call logs data accessing from the device.

main_activity.xml







list_row.xml
















MainActivity.java

package com.sunil.callloginfo;

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

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.CallLog;
import android.widget.ListView;

public class MainActivity extends Activity {

private ListView listview=null;
private String callType=null;
private String phoneNumber=null;
private String callDate=null;
private String callDuration=null;
private Date callDateTime=null;

private List list=new ArrayList();
private Context context=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;

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

getCallDetails();
CustomAdapter adapter=new CustomAdapter(MainActivity.this, list);
listview.setAdapter(adapter);
}

public void getCallDetails()
{
@SuppressWarnings("deprecation")
Cursor managedCursor = managedQuery( CallLog.Calls.CONTENT_URI,null, null,null, null);

int number = managedCursor.getColumnIndex( CallLog.Calls.NUMBER );
int type = managedCursor.getColumnIndex( CallLog.Calls.TYPE );
int date = managedCursor.getColumnIndex( CallLog.Calls.DATE);
int duration = managedCursor.getColumnIndex( CallLog.Calls.DURATION);


while (managedCursor.moveToNext())
{

phoneNumber = managedCursor.getString(number);
callType = managedCursor.getString(type);
callDate = managedCursor.getString(date);

callDateTime = new Date(Long.valueOf(callDate));

callDuration = managedCursor.getString(duration);

String cType = null;

int cTypeCode = Integer.parseInt(callType);

switch(cTypeCode)
{
case CallLog.Calls.OUTGOING_TYPE:
cType = "OUTGOING";
break;

case CallLog.Calls.INCOMING_TYPE:
cType= "INCOMING";
break;

case CallLog.Calls.MISSED_TYPE:
cType = "MISSED";
break;
}

CallData calldata=new CallData(cType, phoneNumber, callDateTime, callDuration);
list.add(calldata);
}

managedCursor.close();
}
}

CallData.java

package com.sunil.callloginfo;

import java.io.Serializable;
import java.util.Date;

public class CallData implements Serializable{

private String calltype;
private String callnumber;
private Date calldatetime;
private String callduration;

public CallData()
{

}

public CallData(String calltype, String callnumber, Date calldatetime, String callduration)
{
this.calldatetime=calldatetime;
this.callduration=callduration;
this.callnumber=callnumber;
this.calltype=calltype;
}

public String getCalltype() {
return calltype;
}

public void setCalltype(String calltype) {
this.calltype = calltype;
}

public String getCallnumber() {
return callnumber;
}

public void setCallnumber(String callnumber) {
this.callnumber = callnumber;
}

public Date getCalldatetime() {
return calldatetime;
}

public void setCalldatetime(Date calldatetime) {
this.calldatetime = calldatetime;
}

public String getCallduration() {
return callduration;
}

public void setCallduration(String callduration) {
this.callduration = callduration;
}


}

CustomAdapter.java

package com.sunil.callloginfo;

import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class CustomAdapter extends ArrayAdapter{

private List listdata=null;
private LayoutInflater mInflater=null;
public CustomAdapter(Activity context, List calldata) {
super(context, 0);
this.listdata=calldata;
mInflater = context.getLayoutInflater();
}


@Override
public int getCount() {
return listdata.size();
}


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

final ViewHolder holder;

if (convertView == null || convertView.getTag() == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.list_row, null);

holder.callnumber = (TextView) convertView.findViewById(R.id.textView_callnumber);
holder.calltype = (TextView) convertView.findViewById(R.id.textView_calltype);
holder.calldate = (TextView) convertView.findViewById(R.id.textView_calldate);
holder.callduration = (TextView) convertView.findViewById(R.id.textView_callduration);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}

CallData calldatalist=listdata.get(position);
String callnumber=calldatalist.getCallnumber();
String calltype=calldatalist.getCalltype();
Date calldate= calldatalist.getCalldatetime();
String callduration=calldatalist.getCallduration();

holder.callnumber.setText("Call Number: "+callnumber);
holder.calltype.setText("Call Type: "+calltype);
holder.calldate.setText("Call Date: "+String.valueOf(calldate));
holder.callduration.setText("Duration: "+callduration);

return convertView;
}

private static class ViewHolder {
TextView callnumber;
TextView calltype;
TextView calldate;
TextView callduration;
}

}

Manifest.xml



















You can download the source code from Here Call Logs

 

Copyright @ 2013 Android Developers Tipss.