Wednesday, 21 December 2016

Retrofit in Android


Retrofit is a type-safe REST client for Android developed by Square. The library provides a powerful framework for authenticating and interacting with APIs and sending network requests with OkHttp

Integrate Retrofit in Android follow Below steps:

1) Add dependencies in build.gradle file



compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.squareup.retrofit2:converter-scalars:2.1.0'

2) Create Interface which will have all the api calls


public interface DataCall{


    //Get Method Call
    @GET("Pass your api path) //ex: "register.php"
    Call<String>getDataGet(@Query("name") String name);


   //Post Method Call
@FormUrlEncoded @POST("index.php") Call<String>getDataPost(@Field("name")String name);
   //Post Method Call with Query annotation
@POST("index.php") Call<String>getDataPostQuery(@Query("name")String name); //Post Method Call with HashMap request
    @POST("index.php")
    Call<String>getDataPostQueryMap(@QueryMap HashMap<String,String> map);

   //Post Method Call with Json request
    @POST("index.php")
    Call<String>getDataPostQueryJson(@Body RequestBody name);

   
}

3) Create Retrofit object and call api methods.

Retrofit retrofit = new Retrofit.Builder().baseUrl("pass here your base url, 
shoul end with /")
        .addConverterFactory(ScalarsConverterFactory.create()).build();
//ScalarsConverterFactory.create() is for String response handling
//GsonConverterFactory.create() is used for automatically will parse the 
//response with proper bean classes


DataCall datacall = retrofit.create(DataCall.class);


//Get Method call
 Call<String> call = datacall.getDataGet("GET name");
     call.enqueue(new Callback<String>() {
         @Override         public void onResponse(Call<String> call,
 Response<String> response) {
             System.out.println("Response data :"+response.body());
         }

         @Override         public void onFailure(Call<String> call, Throwable t) {
             System.out.println("Response data :"+t.getMessage());
         }
     });

//Post Method call
call = datacall.getDataPost("POST name"); call.enqueue(new Callback<String>() { @Override public void onResponse(Call<String> call,
Response<String> response) {
             System.out.println("Response data :"+response.body());
         }

         @Override         public void onFailure(Call<String> call, Throwable t) {
             System.out.println("Response data :"+t.getMessage());
         }
     });


//Post Method call
call = datacall.getDataPostQuery("POST Query"); call.enqueue(new Callback<String>() { @Override public void onResponse(Call<String> call,
Response<String> response) {
             System.out.println("Response data :"+response.body());
         }

         @Override         public void onFailure(Call<String> call, Throwable t) {
             System.out.println("Response data :"+t.getMessage());
         }
     });



//Post Method call with Hash map request
HashMap<String,String>map=new HashMap(); JSONObject ob2=null; // JSONObject map=new JSONObject(); try { map.put("name1", "Map name"); map.put("password1", "Map password"); ob2=new JSONObject(map); }catch (Exception e) { e.printStackTrace();; } RequestBody body = RequestBody.
create(okhttp3.MediaType.parse("application/json; charset=utf-8"),ob2.toString());

        call = datacall.getDataPostQueryJson(body);
     call.enqueue(new Callback<String>() {
         @Override         public void onResponse(Call<String> call, 
Response<String> response) {
             System.out.println("Response data :"+response.body());
         }

         @Override         public void onFailure(Call<String> call, Throwable t) {
             System.out.println("Response data :"+t.getMessage());
         }
     });

//Post Method call with JSon Request

  JSONObject map=new JSONObject();
     try {
         map.put("name1", "Map name");
         map.put("password1", "Map password");

          
     }catch (Exception e)
     {
         e.printStackTrace();;
     }
     RequestBody body = RequestBody.
create(okhttp3.MediaType.parse("application/json; charset=utf-8"),map.toString());

        call = datacall.getDataPostQueryJson(body);
     call.enqueue(new Callback<String>() {
         @Override         public void onResponse(Call<String> call, 
Response<String> response) {
             System.out.println("Response data :"+response.body());
         }

         @Override         public void onFailure(Call<String> call, Throwable t) {
             System.out.println("Response data :"+t.getMessage());
         }
     });

Wednesday, 2 November 2016

Android Notifications


Notification creation in android has updated with few methods are deprecated in Marsh Mallows Version

I have created notification in differert formats
check below Fragment class and xml files

/**
 * A fragment that enables display of notifications.
 */
public class ActiveNotificationFragment extends Fragment {

    private static final String TAG = "ActiveNotificationFragment";

    private NotificationManager mNotificationManager;
    private TextView mNumberOfNotifications;

    // Every notification needs a unique ID otherwise the previous one would be overwritten.
    private int mNotificationId = 0;
    private PendingIntent mDeletePendingIntent;

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

    @Override
    public void onResume() {
        super.onResume();
        updateNumberOfNotifications();
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mNotificationManager = (NotificationManager) getActivity().getSystemService(
                Context.NOTIFICATION_SERVICE);
        mNumberOfNotifications = (TextView) view.findViewById(R.id.number_of_notifications);

        // Supply actions to the button that is displayed on screen.
        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.add_notification:
                        addNotificationAndReadNumber();
                        break;
                        case R.id.add_notification_big:
                            addBigText();
                            break;
                    case R.id.add_notification_big_image:
                        addBigImage();
                        break;
                    case R.id.add_notification_heads:
                        addHeadsUpNotification();
                        break;
                    case R.id.add_notification_action:
                        customNotification();
                        break;

                }
            }
        };
        view.findViewById(R.id.add_notification).setOnClickListener(onClickListener);

        view.findViewById(R.id.add_notification_big).setOnClickListener(onClickListener);

        view.findViewById(R.id.add_notification_big_image).setOnClickListener(onClickListener);

        view.findViewById(R.id.add_notification_heads).setOnClickListener(onClickListener);

        view.findViewById(R.id.add_notification_action).setOnClickListener(onClickListener);
       
        // Create a PendingIntent to be fired upon deletion of a Notification.
        Intent deleteIntent = new Intent("YOUR ACTIVITY/BORADCASTRECEIVER";
        mDeletePendingIntent = PendingIntent.getBroadcast(getActivity(),
                2 /* requestCode */, deleteIntent, 0);
       
    }

    /**
     * Add a new {@link Notification} with sample data and send it to the system.
     * Then read the current number of displayed notifications for this application.
     */
    private void addNotificationAndReadNumber() {
        // [BEGIN create_notification]
        // Create a Notification and notify the system.
        final Notification.Builder builder = new Notification.Builder(getActivity())
                .setSmallIcon(R.mipmap.ic_notification)
                .setContentTitle(getString(R.string.app_name))
                .setContentText(getString(R.string.sample_notification_content))
                .setAutoCancel(true)
                .setDeleteIntent(mDeletePendingIntent);


builder.setContentIntent(getPendingIntent());

        final Notification notification = builder.build();
        mNotificationManager.notify(++mNotificationId, notification);
        // [END create_notification]
        Log.i(TAG, "Add a notification");
        updateNumberOfNotifications();

    }

    private void addBigText()
    {
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getActivity())
                .setSmallIcon(R.mipmap.ic_notification)
                .setContentTitle("Event tracker")
                .setContentText("Events received")/*.
                        setVisibility(NotificationCompat.VISIBILITY_SECRET)
                .setPriority(NotificationCompat.PRIORITY_MAX)
                .setVibrate(new long[] {1, 1, 1})*/;


      /*  Intent push = new Intent();
        push.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        push.setClass(getActivity(), MainActivity.class);

        PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(getActivity(), 0,
                push, PendingIntent.FLAG_CANCEL_CURRENT);
        mBuilder
                .setContentText("A Heads-Up notification for Lollipop and above")
                .setFullScreenIntent(fullScreenPendingIntent, true);
*/
       // notificationManager.notify(HEADS_UP_NOTIFICATION_ID, notificationBuilder.build());
        mBuilder .setAutoCancel(true);
        NotificationCompat.InboxStyle inboxStyle =
                new NotificationCompat.InboxStyle();
        String[] events = new String[6];
// Sets a title for the Inbox in expanded layout
        inboxStyle.setBigContentTitle("Event tracker details:");

// Moves events into the expanded layout
        for (int i=0; i < events.length; i++) {

            inboxStyle.addLine(events[i]+" : "+i);
        }
// Moves the expanded layout object into the notification object.
        mBuilder.setStyle(inboxStyle);
        mBuilder.setContentIntent(getPendingIntent());
        Notification notification=mBuilder.build();
      //  mBuilder.setAutoCancel(true);
        mNotificationManager.notify(++mNotificationId, notification);
        updateNumberOfNotifications();
    }
private void addBigImage()
{

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getActivity())
            .setSmallIcon(R.mipmap.ic_notification)
            .setContentTitle("Event tracker")
            .setContentText("Events received")
                      ;
    NotificationCompat.BigPictureStyle inboxStyle =
            new NotificationCompat.BigPictureStyle();
    String[] events = new String[6];

    inboxStyle.setBigContentTitle("Event tracker details:");
    inboxStyle.bigPicture(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher));
// Moves events into the expanded layout
    mBuilder.setAutoCancel(true);
// Moves the expanded layout object into the notification object.
    mBuilder.setStyle(inboxStyle);
    mBuilder.setContentIntent(getPendingIntent());
    Notification notification=mBuilder.build();

    mNotificationManager.notify(++mNotificationId, notification);
    updateNumberOfNotifications();
}
    private void addHeadsUpNotification()
    {
        Notification.Builder builder=new Notification.Builder(getActivity());
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setPriority(Notification.PRIORITY_HIGH);
        builder.setVibrate(new long[]{100,200,100});
        builder.setContentTitle("HeadsUpNotification");
        builder.setContentIntent(getPendingIntent());
        builder.setAutoCancel(true);
        mNotificationManager.notify(++mNotificationId,builder.build());
    }



    /**
     * Request the current number of notifications from the {@link NotificationManager} and
     * display them to the user.
     */
    protected void updateNumberOfNotifications() {
        // [BEGIN get_active_notifications]
        // Query the currently displayed notifications.
if(Build.VERSION.SDK_INT<Build.VERSION_CODES.M)
    return;
        final StatusBarNotification[] activeNotifications = mNotificationManager
                .getActiveNotifications();
        // [END get_active_notifications]
        final int numberOfNotifications = activeNotifications.length;
        mNumberOfNotifications.setText(getString(R.string.active_notifications,
                numberOfNotifications));
        Log.i(TAG, getString(R.string.active_notifications, numberOfNotifications));
    }
    private PendingIntent getPendingIntent()
    {

        Intent intent=new Intent(getActivity(),SeconActivity.class);
        PendingIntent pending=PendingIntent.getActivity(getActivity(),0,intent,PendingIntent.FLAG_CANCEL_CURRENT);
        return pending;
    }
    private void customNotification()
    {
        RemoteViews remoteview=new RemoteViews(getActivity().getPackageName(),R.layout.remoteview);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getActivity())
                .setContent(remoteview).setSmallIcon(R.mipmap.ic_launcher);
        notificationBuilder.setAutoCancel(true);
Notification notification=notificationBuilder.build();
        remoteview.setOnClickPendingIntent(R.id.img,PendingIntent.getActivity(getActivity(),0,new Intent(getActivity(),SeconActivity.class),PendingIntent.FLAG_CANCEL_CURRENT));
        notification.bigContentView = remoteview;
        notification.flags|=Notification.FLAG_AUTO_CANCEL;
        mNotificationManager.notify(++mNotificationId,notification);
    }
}

XML File
------------

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
    <Button
        android:id="@+id/add_notification"
        android:text="@string/add_a_notification"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

        <Button
            android:id="@+id/add_notification_big"
            android:text="BigText Notification"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/add_notification_big_image"
            android:text="BigImage Notification"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/add_notification_heads"
            android:text="HeadsUp notification"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/add_notification_action"
            android:text="Action notification"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />


    </LinearLayout>

    <TextView
        style="@android:style/TextAppearance.Material.Large"
        android:id="@+id/number_of_notifications"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>


remoteview layout
-----------------------

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@+id/img"
        android:orientation="vertical">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#d94cd9"
            android:text="Title"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#e10a23"
            android:text="Description"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#c4612c"
            android:text="Title"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#a7ab42"
            android:text="Description"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#701770"
            android:text="Title"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#5a51bc"
            android:text="Description"/>

    </LinearLayout>
    <ImageView android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher"
        android:layout_alignParentRight="true"/>

</RelativeLayout>





Migrate Android Eclipse project into Android studio

  1. Open Studio file->import new project
  2. Check all checkBoxes which will update the project with latest library’s submit finish button.
  3. If your project as external library projects It will add the External library projects as module.
  4. if library project are not added as module
    1. Go to library project and create build.gradle file
    2. Go to studio and import module, select modified file
    3. Now update the module gradle file.

Import Existing Eclipse Remote Application into Android Studio


  • Checkout existing project into local machine.
  • => svn co “remote path”
  • Delete ANT build related files (like .classpath,.project files)
  • Start studio and import project from local directory (Check VSC enabled or not, if not enable it).
  • Project is imported as Android studio project.
  • Now add manually necessary library project as module which it has previously.
  • Run the app.
  • Commit changes through terminal =>svn commit
  • Enable VCS for current project =>VCS =>Enable VCS
  • Commit Through IDE
  • VCS=>Subversion=>Commit file/Commit Directory

Few SVN Commands

  • svn checkout/co “repository path”
  • svn add “file/folder”
  • svn delete “file/folder”
  • svn status
  • svn update/up
  • svn commit/ci
  • svn diff
In Ubuntu install SVN by using this command in terminal
“sudo apt-get install subversion”
In Windows use Tortoise Subversion

Add new Project to SVN

In Studio
  • Enable VCS
  • Select Share Project To Subversion in VCS dialog
  • Add the repository in Dialog box
  • Commit
Through Command line
  • svn mkdir "Parent repositoryPath"+"/new project folder"
  • Go to parent folder of your project cd /
  • svn co "path of repository"(includes project folder which created)
  • svn add "project folder"(until commit your project it won't show in repository)
  • => by using svn st command we can check the files what we have to add.
  • svn commit