How to display the pdf in Android ?


Quick start incorporating a PDF viewing activity into your project:

1) Add PdfViewer.jar into your project’s build path

2) Copy the following drawable resources from PdfViewer/res/drawable into YourProject/res/drawable left_arrow.png right_arrow.png zoom_in.png zoom_out.png

3) Copy the following layout resources from PdfViewer/res/layout into YourProject/res/layout dialog_pagenumber.xml pdf_file_password.xml

4) Derive your PDF activity from net.sf.andpdf.pdfviewer.PdfViewerActivity

5) Using the default drawables and layouts:


public int getPreviousPageImageResource() { return R.drawable.left_arrow; }

public int getNextPageImageResource() { return R.drawable.right_arrow; }

public int getZoomInImageResource() { return R.drawable.zoom_in; }

public int getZoomOutImageResource() { return R.drawable.zoom_out; }

public int getPdfPasswordLayoutResource() { return R.layout.pdf_file_password; }

public int getPdfPageNumberResource() { return R.layout.dialog_pagenumber; }

public int getPdfPasswordEditField() { return R.id.etPassword; }

public int getPdfPasswordOkButton() { return R.id.btOK; }

public int getPdfPasswordExitButton() { return R.id.btExit; }

public int getPdfPageNumberEditField() { return R.id.pagenum_edit; }

6) Invoke your PdfViewActivity derived with the following code:


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

intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME, "PATH TO PDF GOES HERE");

startActivity(intent);

Download the source code and demo code from below link here

 

 

EDIT:  Another pdf viewer source for free  at github.

https://github.com/rameshakulapc/PDFViewer

Find the reference  Post by Andhradroid.

How to implement swipe delete in android like iphone ?


Step 1: Just extends below class and implement getListview method.

Step 2: The below MainActivity demonstrates in which direction single item should be swiped and gives the item position of clicked item. We have to manage it in adapter to swipe-delete operation from our own scratch.

SwipeListViewActivity.java:

public abstract class SwipeListViewActivity extends Activity {

private ListView list;
private int REL_SWIPE_MIN_DISTANCE;
private int REL_SWIPE_MAX_OFF_PATH;
private int REL_SWIPE_THRESHOLD_VELOCITY;

/**
*
* @return ListView
*/
public abstract ListView getListView();

/**
*
* @param isRight
* Swiping direction
* @param position
* which item position is swiped
*/
public abstract void getSwipeItem(boolean isRight, int position);

/**
* For single tap/Click
*
* @param adapter
* @param position
*/
public abstract void onItemClickListener(ListAdapter adapter, int position);

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

DisplayMetrics dm = getResources().getDisplayMetrics();
REL_SWIPE_MIN_DISTANCE = (int) (120.0f * dm.densityDpi / 160.0f + 0.5);
REL_SWIPE_MAX_OFF_PATH = (int) (250.0f * dm.densityDpi / 160.0f + 0.5);
REL_SWIPE_THRESHOLD_VELOCITY = (int) (200.0f * dm.densityDpi / 160.0f + 0.5);
}

@Override
protected void onResume() {
super.onResume();
list = getListView();
if (list == null) {
new Throwable("Listview not set exception");
}

@SuppressWarnings("deprecation")
final GestureDetector gestureDetector = new GestureDetector(
new MyGestureDetector());

View.OnTouchListener gestureListener = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
};
list.setOnTouchListener(gestureListener);

}

private void myOnItemClick(int position) {
if (position < 0)
return;
onItemClickListener(list.getAdapter(), position);

}

class MyGestureDetector extends SimpleOnGestureListener {

private int temp_position = -1;

// Detect a single-click and call my own handler.
@Override
public boolean onSingleTapUp(MotionEvent e) {

int pos = list.pointToPosition((int) e.getX(), (int) e.getY());
myOnItemClick(pos);
return true;
}

@Override
public boolean onDown(MotionEvent e) {

temp_position = list
.pointToPosition((int) e.getX(), (int) e.getY());
return super.onDown(e);
}

@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
if (Math.abs(e1.getY() - e2.getY()) > REL_SWIPE_MAX_OFF_PATH)
return false;
if (e1.getX() - e2.getX() > REL_SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > REL_SWIPE_THRESHOLD_VELOCITY) {

int pos = list
.pointToPosition((int) e1.getX(), (int) e2.getY());

if (pos >= 0 && temp_position == pos)
getSwipeItem(false, pos);
} else if (e2.getX() - e1.getX() > REL_SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > REL_SWIPE_THRESHOLD_VELOCITY) {

int pos = list
.pointToPosition((int) e1.getX(), (int) e2.getY());
if (pos >= 0 && temp_position == pos)
getSwipeItem(true, pos);

}
return false;
}

}

}
<h3>

MainActivity.java:

public class MainActivity extends SwipeListViewActivity {

private ListView mListView;
 private ArrayAdapter<String> mAdapter;

@Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);
 mListView = (ListView) findViewById(R.id.listView1);
 mAdapter = new ArrayAdapter<String>(this,
 android.R.layout.simple_list_item_1, new String[] { "Item 1",
 "Item 2", "Item 2", "Item 3", "Item 4", "Item 5" });
 mListView.setAdapter(mAdapter);
 }

@Override
 public ListView getListView() {
 return mListView;
 }

@Override
 public void getSwipeItem(boolean isRight, int position) {
 Toast.makeText(this,
 "Swipe to " + (isRight ? "right" : "left") + " direction",
 Toast.LENGTH_SHORT).show();
 }

@Override
 public void onItemClickListener(ListAdapter adapter, int position) {
 Toast.makeText(this, "Single tap on item position " + position,
 Toast.LENGTH_SHORT).show();
 }

}

Get the source code from the following link .
Let you comment on posts and encourage me for nice posts in future…

Service Tutorial in android Part-I


Service:

A service is a task that runs in the background without the user’s direct interaction, similar to a Unix daemon. For example, consider a music player. The music may be started by an activity, but you want it to keep playing even when the user has moved on to a different program. So, the code that does the actual playing should be in a service. Later,another activity may bind to that service and tell it to switch tracks or stop playing. Android comes with many services built in, along with convenient APIs to access them.

      A Service is a component which runs in the background, without interacting with the user. Every developer can create new Services in his application. Services support true multitasking for Android, as they can run in their own process. If you use threads in Activities their are still connected to the life-cycle of Activities and the Android system may decide to terminate them at any point in point.

For information about services:  http://developer.android.com/reference/android/app/Service.html#RemoteMessengerServiceSample

The following topics are covered in this topic.

  1. Local Services
  2. Service using Binder
  3. Service using Messanger
  4. Serivice using Remote AIDL files
  5. Intent Service

1. Local Services:

We can start the service in two ways .

step 1:
Intent intent=new Intent(context,ServiceClassName.class);
startService(intent);
step 2:
Intent intent=new Intent(“com.ramesh.myservice.ACTION”);
startService(intent);

When we start service using step 2, make sure that adding the action in manifest file.


<service android:name="BindingService" >
 <intent-filter>
 <action android:name="com.ramesh.myservice.ACTION" >
 </action>
 </intent-filter>
 </service>

SimpleService.java:

 public class SimpleService extends Service
 {
 @Override
 public IBinder onBind(Intent arg0)
 {
 return null;
 }
 @Override
 public void onCreate()
 {
 super.onCreate();
 Toast.makeText(this,"Service created ...", Toast.LENGTH_LONG).show();
 }
 @Override
 public void onDestroy() {
 super.onDestroy();
 Toast.makeText(this, "Service destroyed ...", Toast.LENGTH_LONG).show();
 }
 }

In Activity take two buttons for testing , start the service with one button and stop the service with another.

You can choose one of the two steps to start the service.

2. Services using binder:

In Activity we are going to the bind service to communicating with it.

1. In oncreate method, we are binding the service using following statement.

bindService(new Intent(this, BindingService.class), conn,
Service.BIND_AUTO_CREATE);

2.Make sure that unbind the service connection  in onDestroy method Otherwise it gives service connection leaked exception.

  unbindService(conn);

3.When create the IBinder in service, its better to use WeakReference.This bug is mentioned in this blog.

private MyBinder mService;

 private ServiceConnection conn = new ServiceConnection()
 {
 @Override
 public void onServiceDisconnected(ComponentName name)
 {
 //service is disconnected!
 }

@Override
 public void onServiceConnected(ComponentName name, IBinder service)
 {
 //Service is connected.
 mService = (MyBinder) service;
 ((Button)findViewById(R.id.button1)).setText(mService.getName());
 mService.setName("Joy!");
 }
 };

/***BindingService.java:***/

public class BindingService extends Service {

public static final String MY_CUSTOM_ACTION = "com.ramesh.myservice.ACTION";
 private MyBinder<BindingService> binder;
 private String name = "Hi";

@Override
 public IBinder onBind(Intent intent) {
 binder = new MyBinder<BindingService>(this);
 return binder;
 }

@Override
 public int onStartCommand(Intent intent, int flags, int startId) {
 return START_STICKY;
 }

public class MyBinder<T> extends Binder implements IMybinder {
 private WeakReference<T> mService;

public MyBinder(T service) {
 mService = new WeakReference<T>(service);
 }

public T getService() {
 return mService.get();
 }

@Override
 public String getName() {

Random r = new Random();
 return name + "=> your lucky number is:" + r.nextInt(100);
 }

@Override
 public void setName(String newname) {
 name = newname;
 }
 }
}

 /** Interface setting the name and getting the name.**/

 public interface IMybinder
 {
 public String getName();

 public void setName(String name);
 }

Continue to be service tutorial-II…..

Custom xml layouts in android .


i’ll walk through you how to use the styles and implementing the custom layouts in android.
You can learn the following concepts:

  1. Styles: Styles are used to simplifies our code in xml layout and complexity.
  2. Attributes: Here we can learn the usage of custom attributes.In my example i am creating rating bar.I am introducing in this example, level-list which is used to show the ratings icons.
  3. Level-list: A Drawable that manages a number of alternate Drawables, each assigned a maximum numerical value. Setting the level value of the drawable with setLevel() loads the drawable resource in the level list that has a android:maxLevel value greater than or equal to the value passed to the method.
  4. How to decalare custom layouts in Xml.
  5. How to accept the custom attributes and its values for custom layout in Xml.
Code Explanation:
—————–
  • When we are creating custom layouts we need to define constructor with 2 or 3 parameters.
  • In init() , reading the values which are defined in xml layout and which are defined with custom attributes .Custom attributes are available with attributesParentname_yourAttibutesName (in my example: R.styleable.customratingbar_rating).
  • In switch case first argument is R.styleable.customratingbar_rating, is used to get the current rating.
  • Second argument R.styleable.customratingbar_src, is used to read level-list Xml.
  • Last argument is R.styleable.customratingbar_max, is used to set the maximum rating.
  • ImageView#setImageLevel() is used to load the drawable resource in the level list.

res/values/attr.xml:


<?xml version="1.0" encoding="utf-8"?>
<resources >
 <declare-styleable name="customratingbar">
 <attr name="rating" format="integer"/>
 <attr name="max" format="integer"/>
 <attr name="src" format="reference"/>
 </declare-styleable>

</resources>

res/layout/main.xml:


<!--xmlns:pref="http://schemas.android.com/apk/res/"com.ramesh.customratingbar.demo" is application packag name and pref is your prefix to identify the attributes and assinging the values.-->
 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:pref="http://schemas.android.com/apk/res/com.ramesh.customratingbar.demo"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:orientation="vertical" >

<com.ramesh.customratingbar.demo.CustomRatingBar
 android:id="@+id/customRatingBar1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 pref:max="5"
 pref:rating="1"
 pref:src="@drawable/layer_list_demo" />

</LinearLayout>

CustomRatingBar.java:

public class CustomRatingBar extends ImageView {

private int currentRating = 0;
 private int maxRating = 0;
 private int ratingResId;
 private LevelListDrawable drawable;
 private OnRatingBarChangeListener listener;

public CustomRatingBar(Context context, AttributeSet attrs, int defStyle) {
 super(context, attrs, defStyle);
 init(context, attrs);
 }

public CustomRatingBar(Context context, AttributeSet attrs) {
 super(context, attrs);
 init(context, attrs);
 }

public void init(Context context, AttributeSet attrs) {
 setOnTouchListener(onTouch);
 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.customratingbar);
 final int n = a.getIndexCount();
 for (int i = 0; i < n; ++i) {
 int attr = a.getIndex(i);
 switch (attr) {
 case R.styleable.customratingbar_rating:
 currentRating = a.getInt(attr, 0);
 setRating(currentRating);
 break;
 case R.styleable.customratingbar_src:
 ratingResId = a.getResourceId(attr, 0);
 try {
 drawable = (LevelListDrawable) LevelListDrawable
 .createFromXml(getResources(), getResources()
 .getXml(ratingResId));
 } catch (NotFoundException e) {
 e.printStackTrace();
 } catch (XmlPullParserException e) {
 e.printStackTrace();
 } catch (IOException e) {
 e.printStackTrace();
 }

setRatingDrawable(drawable);
 break;
 case R.styleable.customratingbar_max:
 maxRating = a.getInt(attr, 0);
 setMax(maxRating);
 break;

}
 }
 a.recycle();
 }

@Override
 public void setImageLevel(int level) {
 super.setImageLevel(level);
 currentRating = level;
 }

public void setRating(int rating) {
 setImageLevel(rating);
 }

public void setRatingDrawable(Drawable drawable) {
 setImageDrawable(drawable);
 }

public void setRatingDrawable(int ratingResId) {

this.ratingResId = ratingResId;
 setImageResource(ratingResId);
 }

public void setMax(int max) {
 maxRating = max;
 }

public void setOnRatingListener(OnRatingBarChangeListener listener) {
 this.listener = listener;
 }

interface OnRatingBarChangeListener {
 public void setOnRatingChageListener(CustomRatingBar ratingbar,
 int rating);
 }

public OnTouchListener onTouch = new OnTouchListener() {

@Override
 public boolean onTouch(View v, MotionEvent event) {
 float rawX = event.getX();
 if (event.getAction() == MotionEvent.ACTION_MOVE) {
 float width = CustomRatingBar.this.getWidth();
 if (width > 0)
 {
 float tem1 = (rawX / width) * 100 * maxRating;
 int perc = (int) tem1 / 100;
 if (perc <= maxRating && perc >= 0) {
 currentRating = perc + 1;
 currentRating = currentRating > maxRating ? maxRating
 : currentRating;
 setImageLevel(currentRating);
 }
 }
 }
 if (event.getAction() == MotionEvent.ACTION_UP) {
 float width = CustomRatingBar.this.getWidth();
 if (width > 0) {
 float temp = (rawX / width) * maxRating;
 int perc = (int) temp;
 if (perc <= maxRating && perc >= 0) {
 currentRating = perc + 1;
 currentRating = currentRating > maxRating ? maxRating
 : currentRating;
 setImageLevel(currentRating);
 listener.setOnRatingChageListener(CustomRatingBar.this,
 currentRating);
 }
 }
 }

return true;
 }
 };
}

Referred Links:

http://kevindion.com/2011/01/custom-xml-attributes-for-android-widgets/

https://staticallytyped.wordpress.com/tag/layer-list-level-list-android-custom-views-resources/

http://iserveandroid.blogspot.in/2010/10/progress-bar-implementation-using-level.html

you can download the source code here.

Screenshot here:

custom xml layout

custom xml layout