Labels

Showing posts with label Development. Show all posts
Showing posts with label Development. Show all posts

Wednesday, 3 June 2020

Android keeping the same data after application orientation change.

This contains the sample code to show demo to keep the same data after changing the orientation of android application.

DemoActivity.java & DemoActivityViewModel.java: These 2 classes are demonstrating keeping data same after orientation change of android application using ViewModel library(Android Jetpack). To use this integration in your code you need to add the below dependencies.
    implementation 'android.arch.lifecycle:extensions:1.1.1'
  annotationProcessor 'android.arch.lifecycle:compiler:1.1.1'
Here I'm using version 1.1.1 but it may vary in future, please use the latest version always.

MainActivity.java:
This class is using onSaveInstanceState() method to save data before changing the orientation of application, then we can get the saved data in onCreate() method using savedInstanceState variable.

Source: video_1, video_2, link_1

Thursday, 21 May 2020

Preparing jar from Android studio library

Here is the code need to add in build gradle file to get jar file of your project module.

task makeJar(type: Copy) {    
    delete 'build/outputs/my-library-*.jar'    
    from('build/intermediates/aar_main_jar/release/')
    into('build/outputs/')
    include('classes.jar')
    rename('classes.jar', 'my-library-' + VERSION_NAME + '.jar')
}

makeJar.dependsOn(build)

Once you added the above code, sync the gradle file and click on Gradle option, which is there in right side and select the module project.
Tasks --> other --> makeJar(double click this)
Then it will start the process to generate and copy jar to "build/output/" folder.
Please go through the below images for better understanding.
* If you want to copy the jar to outside folder add "../" before the folder name
Example: into('../JarLibraryFolder/')
The above line will copy the jar file in "JarLibarayFolder" folder which is in project.



Wednesday, 15 April 2020

How to pass object using intent in Android

This is the most frequently asked question in the Android interview, and here is the sample code to pass the object using intent in Android.
We can pass the object by making it as Serializable. Serializing an object means converting its state into a byte stream so that it can be read to get the object back. To make a class Serializable, the class needs to implement it with the Serializable interface.
Here is an example.

//Object class
public class Student implements Serializable {
private String name;
private String address;
private String dateOfBirth;
private long rollNumber;
}


//First Activity
Student student = new Student();
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("objdata", student);
startActivity(intent);


//Second Activity
public class SecondActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
Student student = (Student) getIntent().getSerializableExtra()("objdata");
}
}

Monday, 13 April 2020

Coupling

Coupling: Coupling is the measure of the degree of interdependence between the modules. A good software will have low coupling.
A software project will be developed in module wise, and all modules are dependent on each other. So coupling will denote the interdependence/relation between the modules of a software. To maintain good software, there should be less coupling between modules.

Loose Coupling makes it possible to:
  • Understand one class without reading others
  • Change one class without effecting others
  • Improves maintainability
Example:
//Tightly Coupled 

class Volume 
{
     public static void main(String args[]) 
     {
         Box b = new Box(5,5,5);
         System.out.println(b.volume);
     }
}
class Box 
{
     public int volume;
     Box(int length, int width, int height) 
     {
         this.volume = length * width * height;
     }
}

//Loosely Coupled

class Volume 
{
     public static void main(String args[]) 
     {
         Box b = new Box(5,5,5);
         System.out.println(b.getVolume());
     }
}
final class Box 
{
     private int volume;
     Box(int length, int width, int height) 
     {
         this.volume = length * width * height;
     }
     public int getVolume() 
     { 
         return volume; 
           
     }

Categories of Coupling:

1) Data Coupling: If the dependency between the modules is based on the fact that they communicate by passing only data, then the modules are said to be data coupled. In data coupling, the components are independent of each other and communicating through data. Module communications don’t contain tramp data.
Example: Customer billing system.

Class Student {

private String getStudentAddress(){
return database.returnAddress(getStudentId())
}

private int getStudentId(){
return sudentId;
}
}

2) Stamp Coupling: In stamp coupling, the complete data structure is passed from one module to another module. Therefore, it involves tramp data. It may be necessary due to efficiency factors- this choice made by the insightful designer, not a lazy programmer.

Class Company {
private String getUserAddress(Employee e){
return e.getAddress();
}
}

class Employee {
private String name;
private String address;
private int id;

getters and setters..
}

3) Control Coupling: If the modules communicate by passing control information, then they are said to be control coupled. It can be bad if parameters indicate completely different behavior and good if parameters allow factoring and reuse of functionality. 
Example: Sort function that takes comparison function as an argument.

Class EvenNumber{
Array[] a = {1,3,4,5,7,8,9}

private Array[] getListOfEvenNumbers(a){
Array[] b;
for(a){
if(isEvenNumber()){
b[i] = a[i];
}
}

private boolean isEvenNumber(int number){
return number%2 == 0
}
}

4) External Coupling: In external coupling, the modules depend on other modules, external to the software being developed or to a particular type of hardware.
Example: protocol, external file, device format, etc.
H/w and S/W
Laptop and other company printers.

5) Common Coupling: The modules have shared data such as global data structures. The changes in global data mean tracing back to all modules which access that data to evaluate the effect of the change. So it has got disadvantages like difficulty in reusing modules, reduced ability to control data accesses and reduced maintainability.
Example: Bank balance with ATM and Bank.

6) Content Coupling: In a content coupling, one module can modify the data of another module or control flow is passed from one module to the other module. This is the worst form of coupling and should be avoided.
Example:
https://stackoverflow.com/questions/27188180/what-is-content-coupling

Cohesion

Cohesion:Cohesion is a measure of the degree to which the elements of the module are functionally related.

High Cohesion makes it easier to:

  • Understand what a class or method does
  • Use descriptive names
  • Reuse classes or methods
Example:
//Example for Low Cohesion
class Utils {
                public static Time getSystemTime(){
                                return Time;
                }
               
                public static String captilizeName(String useName) {
                                return userName;
                }
               
                public static boolean validateEmail(String email) {
                                return isValidEmail;
                }
}

//Example for High Cohesion

class EmailUtils {
                public static boolean validateEmail(String email) {
                                return isValidEmail;
                }
}

class TimeUtils {
                public static Time getSystemTime(){
                                return Time;
                }
}

class NameUtils {
                public static String captilizeName(String useName) {
                                return userName;
                }
}

Categories of Cohesion:


1) Functional Cohesion: Functional cohesion is when parts of a module are grouped because they all contribute to a single well-defined task of the module.
Functional Cohesion is said to exist if the different elements of a module, cooperate to achieve a single function.

2) Sequential Cohesion: if the element of a module form the components of the sequence, where the output from one component of the sequence is input to the next.
Example: A function which reads data from a file and processes the data.

3) Communicational Cohesion: Tow elements operate on the same input data or contribute towards the same output data.
Example: Module determines customer details like the use customer account no to find and return customer name and loan balance

4) Procedural Cohesion: A module is said to possess procedural cohesion, if the set of functions of the module are all part of a procedure (algorithm) in which a certain sequence of steps have to be carried out for achieving an objective
Example: A function which checks file permissions then opens the file

5) Temporal Cohesion: When a module includes functions that are associated by the fact that all the methods must be executed in the same time, the module is said to exhibit temporal cohesion
Example: a function which is called after catching an exception which closes open files, creates an error log, and notifies the user.

6) Logical Cohesion: Elements are logically related not functionally
Logical cohesion is when parts of a module are grouped because they are logically categorized to do the same thing, even if they are different by nature (e.g. grouping all mouse and keyboard input handling routines).
Example: Print Functions: An example of logical cohesion is the case where a set of print functions generating different output reports are arranged into a single module.

class Calculate {
int a, b;
void Calculate(int a, int b){
this.a  = a;
this.b = b;
}
void printAddition(){
print(a+b);
}
void printSub(){
print(a-b);
}

void printMul(){
print(a*b);
}
}

7) Coincidental Cohesion: Coincidental cohesion is when parts of a module are grouped arbitrarily; the only relationship between the parts is that they have been grouped together.
A module is said to have coincidental cohesion if it performs a set of tasks that are associated with each other very loosely, if at all.
Ex: Utils example.

Friday, 18 May 2018

Tuesday, 17 April 2018

Thursday, 26 October 2017

Getting JSON using Retrofit in Android

In the previous post I explained how to build RecyclerView in Android, now here is the same example with Included Retrofit library. for that add the below lines in build.gradle under dependencies block and also add Internet permission in manifest file.
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'

Tuesday, 24 October 2017

Android RecyclerView Example using Kotlin

In the previous post I explained how to build RecyclerView using Java, Now here is the same RecyclerView example using Kotlin with item click.

Wednesday, 1 March 2017

Monday, 26 December 2016

Getting signatures from apk

Here is the command to get the signatures of apk to know the apk is generated with which keystore..

- Open the command prompt
- goto JDK bin location
cd Program Files\Java\jdk\bin
- Now use the below command.
keytool -list -printcert -jarfile &lt &gt

Wednesday, 16 November 2016

Sharing Image with Instagram using Android Intents

The Instagram API Platform can be used to build non-automated, authentic, high-quality apps and services that:

Help individuals share their own content with 3rd party apps.
Help brands and advertisers understand, manage their audience and media rights.
Help broadcasters and publishers discover content, get digital rights to media, and share media with proper attribution.

Instagram did not open their sharing API. You have to use Intents ...Here is the example for sharing images with Instagram using intents.

Resource Link_1  Resource Link_2  Resource Link_3
package com.example.instagramshare;

import java.io.File;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
Button mButtonWhatsappShare;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mButtonWhatsappShare = (Button) findViewById(R.id.button_share);
mButtonWhatsappShare.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

String type = "image/*";
String filename = "/Capture.png";
String mediaPath = Environment.getExternalStorageDirectory() + filename;

createInstagramIntent(type, mediaPath);
}
});
}

private void createInstagramIntent(String type, String mediaPath){

   // Create the new Intent using the 'Send' action.
   Intent share = new Intent(Intent.ACTION_SEND);
    share.setPackage("com.instagram.android");
   // Set the MIME type
   share.setType(type);

   // Create the URI from the media
   File media = new File(mediaPath);
   Uri uri = Uri.fromFile(media);

   // Add the URI to the Intent.
   share.putExtra(Intent.EXTRA_STREAM, uri);
   share.putExtra(Intent.EXTRA_TEXT, "This is my text to send Instagram.");//Instagram will not take text as input..
   
   try {
startActivity(share);
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(MainActivity.this, "Instagram application not found..", Toast.LENGTH_SHORT).show();
}

}
}

Here is the link to download the source code
Note: Before executing the above code you should keep one image with the name as Capture.png (InternalStorage/Capture.png)or you can use your image path..

Monday, 17 October 2016

Android SpannableString Example

here is the example to customise the TextView and String in Android using custom fonts.

package com.syntax.spannablestring_demo;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.style.BackgroundColorSpan;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StrikethroughSpan;
import android.text.style.StyleSpan;
import android.text.style.SubscriptSpan;
import android.text.style.SuperscriptSpan;
import android.text.style.URLSpan;
import android.text.style.UnderlineSpan;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
String title2 = "developed by Google";
String stringNormal = "Android is a mobile operating system developed by Google, based on the Linux kernel";
SpannableString styledTitle, styledBody;

TextView text_Title, text_Title2, text_Body;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

text_Title = (TextView) findViewById(R.id.text_title);
text_Title2 = (TextView) findViewById(R.id.text_title2);
text_Body = (TextView) findViewById(R.id.text_body);

Typeface typeface_Google = Typeface.createFromAsset(getAssets(),"product-sans.ttf");
Typeface typeface_Android = Typeface.createFromAsset(getAssets(),"IDroid.otf");

text_Title.setText("android");
text_Title.setTypeface(typeface_Android);
text_Title.setTextColor(Color.parseColor("#34A853"));
text_Title.setTextSize(30);

text_Title2.setTypeface(typeface_Google);
styledTitle = new SpannableString(title2);
styledTitle.setSpan(new RelativeSizeSpan(1f), 0, 12, 0);//to increase the font size
styledTitle.setSpan(new RelativeSizeSpan(1.5f), 13, 19, 0);
styledTitle.setSpan(new ForegroundColorSpan(Color.parseColor("#4285F4")), 13, 14, 0);//to change the foreground color of text
styledTitle.setSpan(new ForegroundColorSpan(Color.parseColor("#EA4335")), 14, 15, 0);
styledTitle.setSpan(new ForegroundColorSpan(Color.parseColor("#FBBC05")), 15, 16, 0);
styledTitle.setSpan(new ForegroundColorSpan(Color.parseColor("#4285F4")), 16, 17, 0);
styledTitle.setSpan(new ForegroundColorSpan(Color.parseColor("#34A853")), 17, 18, 0);
styledTitle.setSpan(new ForegroundColorSpan(Color.parseColor("#EA4335")), 18, 19, 0);
text_Title2.setText(styledTitle);

styledBody = new SpannableString(stringNormal);
styledBody.setSpan(new StyleSpan(Typeface.BOLD), 0, 7, 0);//to make the text BOLD
styledBody.setSpan(new StyleSpan(Typeface.ITALIC), 7, 12, 0);//to make the text ITALIC
styledBody.setSpan(new UnderlineSpan(), 13, 36, 0);//to make underline
styledBody.setSpan(new StrikethroughSpan(), 37, 49, 0);//to strike the text
styledBody.setSpan(new BackgroundColorSpan(Color.YELLOW), 50, 56, 0);//to change the background color
styledBody.setSpan(new SuperscriptSpan(), 57, 63, 0);//to add superscript
styledBody.setSpan(new SubscriptSpan(), 64, 70, 0);//to add subscript
styledBody.setSpan(new URLSpan("http://www.google.com"), 50, 56, 0);//URL
ClickableSpan clickableSpan = new ClickableSpan() {
   
  @Override
  public void onClick(View widget) {
   Toast.makeText(MainActivity.this, "Clicked", Toast.LENGTH_SHORT).show();
  }
};
styledBody.setSpan(clickableSpan, 71, 83, 0);//for clickable text
text_Body.setMovementMethod(LinkMovementMethod.getInstance());
text_Body.setText(styledBody);

}

}




Here is the link to download the source code