Wednesday, February 18, 2015

Android PDFView

Android PDFView is a library which provides a fast PDFView component for Android, with animations, gestures, and zoom.

the reference is taken from PDF View.

We just need to use com.joanzapata.pdfview.PDFView at xml layout as follows

<com.joanzapata.pdfview.PDFView
        android:id="@+id/pdfview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>


and than can be used in main activity as follows

pdfView.fromAsset(pdfName)
    .pages(0, 2, 1, 3, 3, 3)
    .defaultPage(1)
    .showMinimap(false)
    .enableSwipe(true)
    .onDraw(onDrawListener)
    .onLoad(onLoadCompleteListener)
    .onPageChange(onPageChangeListener)
    .load();

for a reference here is a full code of

activity_main.xml is as follows


<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

    <com.joanzapata.pdfview.PDFView
        android:id="@+id/pdfView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>

while PDFView can be used in PDFViewActivity as follows

import com.joanzapata.pdfview.PDFView;
import com.joanzapata.pdfview.listener.OnPageChangeListener;

import android.app.Activity;
import android.os.Bundle;

public class PDFViewActivity extends Activity implements OnPageChangeListener {

public static final String SAMPLE_FILE = "sample.pdf";

public static final String ABOUT_FILE = "about.pdf";

PDFView pdfView;

String pdfName = ABOUT_FILE;

Integer pageNumber = 1;

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

pdfView = (PDFView) findViewById(R.id.pdfView);
display(pdfName, false);
}

private void display(String assetFileName, boolean jumpToFirstPage) {
if (jumpToFirstPage)
pageNumber = 1;
setTitle(pdfName = assetFileName);

pdfView.fromAsset(assetFileName).defaultPage(pageNumber)
.onPageChange(this).load();
}

@Override
    public void onPageChanged(int page, int pageCount) {
        pageNumber = page;
    setTitle(pdfName = pageNumber+"");
    }
}


make sure that you have sample pdf files in Asset folder of yours project.

the library code can be downloaded from https://github.com/JoanZapata/android-pdfview  and than PDFViewActivity  can be used simply as in above given  example.

Download code from Demo PDF Activity

Tuesday, April 15, 2014

Using Butter Knife in Android

Butter Knife  is View "injection" library for Android which uses annotation processing to generate the code for you.

we should follow these steps

  • Eliminate findViewById calls by using @InjectView on fields.
  • Group multiple views in a list using @InjectViews. Operate on all of them at once with actions, setters, or properties.
  • Eliminate anonymous inner-classes for listeners by annotating methods with @OnClick and others.
for an example create a project and have a layout as follows

example.xml

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

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Insert Username" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Insert Password"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Login" />

</LinearLayout>

correspondingly write the Activity code as follows
SimpleActivity.java 

import static android.widget.Toast.LENGTH_SHORT;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

public class SimpleActivity extends Activity {
       @InjectView(R.id.editText1)
EditText username;
@InjectView(R.id.editText2)
EditText password;
@InjectView(R.id.button1)
Button login;
@OnClick(R.id.button1) void sayLogin() {
Toast.makeText(this, "Hello!"+" yours username is "+username.getText().toString()+" & Yours password is "+password.getText().toString(), LENGTH_SHORT).show();
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.example);
ButterKnife.inject(this);

}
}


beside this write application class as follows

import android.app.Application;
import butterknife.ButterKnife;

public class SimpleApp extends Application {
@Override
public void onCreate() {
super.onCreate();
ButterKnife.setDebug(BuildConfig.DEBUG);
}
}


and include it at manifest as 

 <application
        android:name="com.packagenamee.SimpleApp"  .....


finally run the code and see a login screen, Happy coding

download the butter knife jar from 

http://jakewharton.github.io/butterknife/

on having problems and issues follow




Tuesday, December 31, 2013

Android Loaders

Loaders in Android

Introduction with Honeycomb
Where we can use?
1) to access data of databases 2) content providers

They load data asynchronously and notify the listeners when the results are available/ready.

characteristics:
  • They are available to every Activity and Fragment.
  • They provide asynchronous loading of data.
  • They monitor the source of their data and deliver new results when the content changes.
  • They automatically reconnect to the last loader's cursor when being recreated after a configuration change. Thus, they don't need to re-query their data.


the main classes and interfaces are as folllows


1)LoaderManager = Manages your Loaders for you. Responsible for dealing with the Activity or Fragment lifecycle


2)Loader =The base class for all Loaders


3)LoaderManager.LoaderCallbacks = A callback interface you must implement


4)AsyncTaskLoader = An implementation that uses an AsynTask to do its work


5)CursorLoader = A subclass of AsyncTaskLoader for accessing ContentProvider data


eXample


please visit at github




and


https://github.com/emil10001/AndroidSerialSQL/tree/sample (Source code)

Advantage==>  Loaders in Android are great, they allow us to asynchronously load data to be used in Adapters. It is found that CursorLoaders very useful for getting data from a database to the UI in a way that minimizes blocking calls on the UI thread.

Google did not only introduce Loaders but also deprecated the previous way to handle a Cursor within your activities. You shouldn’t use startManagingCursor()or managedQuery() in your projects anymore.





Tuesday, October 29, 2013

Android using Singleton






Java Singleton Class Example Using Private Constructor

  • We can make constructor as private. So that We can not create an object outside of the class.
  • This property is useful to create singleton class in java.
  • Singleton pattern helps us to keep only one instance of a class at any time.
  • The purpose of singleton is to control object creation by keeping private constructor.


=====> the main class
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package designpattern;

/**
 *
 * @author jiteshupadhyay
 */
public class DesignPattern {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        Singleton tmp = Singleton.getInstance();
        tmp.demoMethod();
        

    }

}


===>the singleton class

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package designpattern;

/**
 *
 * @author jiteshupadhyay
 */
public class Singleton {
    
private static Singleton singleton = new Singleton( );
   
   /* A private Constructor prevents any other 
    * class from instantiating.
    */
   private Singleton(){ }
   
   /* Static 'instance' method */
   public static Singleton getInstance( ) {
      return singleton;
   }
   /* Other methods protected by singleton-ness */
   protected static void demoMethod( ) {
      System.out.println("demoMethod for singleton"); 
   }
}





Saturday, October 26, 2013

Breaking and android applications APk file (a reverse engineering )

Procedure for decoding .apk files, step-by-step method:

Step 1:

Make a new folder and put .apk file in it (which you want to decode). Now rename the extension of this .apk file to .zip (eg.: rename from filename.apk to filename.apk.zip) and save it. Now you get classes.dex files, etc. At this stage you are able to see drawable but not xml and java files, so continue.

Step 2:

Now extract this zip apk file in the same folder (or NEW FOLDER). Now download dex2jar from this linkhttp://code.google.com/p/dex2jar/ and extract it to the same folder (or NEW FOLDER). Now open command prompt and change directory to that folder (or NEW FOLDER). Then write dex2jar classes.dex and press enter. Now you get classes.dex.dex2jar file in the same folder. Then download java decompiler from http://java.decompiler.free.fr/?q=jdgui and now double click on jd-gui and click on open file. Then open classes.dex.dex2jar file from that folder. Now you get class files and save all these class files (click on file then click "save all sources" in jd-gui) by src name. At this stage you get java source but the xml files are still unreadable, so continue.

Step 3:

Now open another new folder and put these files
  1. put .apk file which you want to decode
  2. download apktool v1.x AND apktool install window (both can be downloaded at the same location) and put in the same folder
  3. download framework-res.apk file and put in the same folder (Not all apk file need framework-res.apk file)
  4. Open a command window
  5. Navigate to the root directory of APKtool and type the following command: apktool if framework-res.apk
  6. apktool d "fname".apk ("fname" denotes filename which you want to decode)
now you get a file folder in that folder and now you can easily read xml files also.

Friday, October 25, 2013

Something about AAPT(Android asset packaging tool)

the given diagram is about a build process of android apps.

Android Asset Packaging Tool (AAPT) -
 
Constructs the Android package files (.apk). 

This tool provides developers with the ability to deal with zip-compatible archives, which includes creating, extracting as well as viewing its contents.
A Detailed Look at the Build Process

The general process for a typical build is outlined below:

  • The Android Asset Packaging Tool (aapt) takes your application resource files, such as the AndroidManifest.xml file and the XML files for your Activities, and compiles them. An R.java is also produced so you can reference your resources from your Java code.
  • The aidl tool converts any .aidl interfaces that you have into Java interfaces.
  • All of your Java code, including the R.java and .aidl files, are compiled by the Java compiler and .class files are output.
  • The dex tool converts the .class files to Dalvik byte code. Any 3rd party libraries and .class files that you have included in your project are also converted into .dex files so that they can be packaged into the final .apk file.
  • All non-compiled resources (such as images), compiled resources, and the .dex files are sent to the apkbuilder tool to be packaged into an .apk file.
  • Once the .apk is built, it must be signed with either a debug or release key before it can be installed to a device.
  • Finally, if the application is being signed in release mode, you must align the .apk with the zipalign tool. Aligning the final .apk decreases memory usage when the application is running on a device

MVP in android (Model View Presenter)


Model-View-Presenter pattern fit s for android 

  • serving as an entry point
  • rendering the  components
  • routing user events to the presenter
This allows us to implement our model like :
View - this contains UI components, and handles events for them.
Presenter - this will handle communication between model and view, it as a gateway to the model. Meaning, if we have a complex domain model representing, god know what, and our view only needs a very small subset of this model, the presenters job is to query the model and then update the view.
Model - this should basically be full domain model, hopefully it will help making your domain model more "tight" as well, since we wont need special methods to deal with cases

MVP separates the UI concerns between the data of the UI (Model), the display of the UI (View), and the logic of the UI (Presenter). For Android, the View is the Activity, which will handle gathering user input and updating the display; the Presenter is a class that will handle communication between the Model and View; the Model will handle persisting and retrieving data, along with any business logic that the data must adhere to. Interfaces will be used to de-couple each of these components