Thursday 1 August 2019

Custom SeekBar with Zoom-In and Zoom-Out Feature

1. Gradle :- (build.gradle):implementation 'com.android.support:design:27.1.1'
2.  activity_main.xml :-
<?xml version="1.0" encoding="utf-8"?>
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"    
xmlns:app="http://schemas.android.com/apk/res-auto"   
 android:id="@+id/horiontal"   
 android:layout_width="match_parent"   
 android:layout_height="wrap_content"   
 android:background="@color/greay_bg"   
 android:fillViewport="true"  
  android:orientation="horizontal"   
 android:padding="10dp"   
 android:scaleType="matrix"   
 android:scrollbars="horizontal">

    <LinearLayout        
android:id="@+id/mainView"        
android:layout_width="match_parent"        
android:layout_height="wrap_content"       
 android:layout_marginLeft="5dp"        
android:gravity="center"       
 android:orientation="vertical">
        <ProgressBar           
 style="?android:attr/progressBarStyleHorizontal"           
 android:layout_width="match_parent"            
android:layout_height="wrap_content"           
 android:id="@+id/progress"           
 android:layout_centerHorizontal="true"            
android:layout_centerVertical="true"            
android:max="100"            
android:layout_marginBottom="30dp"            
android:progress="45"/>

        <com.warkiz.tickseekbar.TickSeekBar            
android:id="@+id/seekbar_video"            
android:layout_width="match_parent"            
android:layout_height="wrap_content"            
app:tsb_show_tick_marks_type="square"            
app:tsb_show_tick_texts="below"            
android:padding="4dp"            
app:tsb_thumb_color="@color/colorAccent"            
app:tsb_thumb_drawable="@drawable/ic_launcher_background"           
 app:tsb_thumb_size="9dp"            
app:tsb_tick_marks_color="@color/colorAccent"            
app:tsb_tick_marks_drawable="@drawable/ic_launcher_background"           
 app:tsb_tick_marks_size="3dp"            
app:tsb_tick_texts_color="@color/white_seekbar"           
 app:tsb_tick_texts_size="13sp"            
app:tsb_ticks_count="7"            
app:tsb_max="24"            
app:tsb_min="0"            
app:tsb_progress="0"            
android:scrollbars="horizontal"           
 app:tsb_track_background_color="@color/white_seekbar"           
 app:tsb_track_background_size="2dp"            
app:tsb_track_progress_color="@color/white_seekbar"           
 app:tsb_track_progress_size="1dp" />
    </LinearLayout>
</HorizontalScrollView>
3.  MainActivity.java:-
public class MainActivity extends AppCompatActivity {
    private TickSeekBar tickSeekBar;
    private float oldDist = 1f;
    private static float newDist;
    private String[] seekText = {"1.00", "2.00", "3.00", "4.00", "5.00", "6.00", "7.00", "8.00", "9.00",
            "10.00", "11.00", "12.00", "13.00", "14.00", "15.00", "16.00", "17.00", "18.00", "19.00", "20.00",
            "21.00", "22.00", "23.00", "24.00"};
    private String[] seekText2 = {"1.00", "3.00", "5.00", "7.00", "9.00", "11.00", "13.00", "15.00", "17.00", "19.00",
            "21.00", "23.00"};
    private String[] seekText4 = {"1.00", "5.00", "9.00", "13.00", "17.00", "24.00"};

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tickSeekBar = findViewById(R.id.seekbar_video);
        tickSeekBar.setMax(24);
        tickSeekBar.setMin(0);
        tickSeekBar.setScrollContainer(true);
        tickSeekBar.computeScroll();
        tickSeekBar.getScrollX();
        //tickSeekBar.customTickTexts(seekText);        tickSeekBar.setOnTouchListener(new View.OnTouchListener() {
            @Override            public boolean onTouch(View view, MotionEvent motionEvent) {
                Log.d(view.getTransitionName() + "ActionMove ", " onTouch");
                handleTouch(motionEvent);
                return true;
            }
        });
    }

    void handleTouch(MotionEvent m) {

        int action = m.getActionMasked();
        switch (action) {
            case MotionEvent.ACTION_POINTER_DOWN:
                Log.d("ActionMove ", " ACTION_POINTER_DOWN");
                oldDist = spacing(m);
                break;
            case MotionEvent.ACTION_POINTER_UP:
                Log.d("ActionMove ", " ACTION_POINTER_UP :: ");
                if (m.getPointerCount() == 2) {
                    if (newDist > oldDist) {
                        Log.d("ActionMove ", "ZOOM IN ");
                        if (tickSeekBar.getTickCount() == 7) {
                            tickSeekBar.setTickCount(12);
                        } else if (tickSeekBar.getTickCount() == 12) {
                            tickSeekBar.setTickCount(24);
                        }
                    } else if (newDist < oldDist) {
                        Log.d("ActionMove ", "ZOOM OUT  ");
                        if (tickSeekBar.getTickCount() == 24) {
                            tickSeekBar.setTickCount(12);
                        } else if (tickSeekBar.getTickCount() == 12) {
                            tickSeekBar.setTickCount(7);
                        }
                    }
                }
                break;
            case MotionEvent.ACTION_MOVE:
                // Log.d("ActionMove ", " ACTION_MOVE");                if (m.getPointerCount() == 2)
                    newDist = spacing(m);
                break;
            default:
        }
    }

    /**     * Determine the space between the first two fingers     */    private float spacing(MotionEvent event) {
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);
        return (float) Math.sqrt(x * x + y * y);
    }
}

4. drawable:-
line.xml:-
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"    android:shape="rectangle">
    <stroke        android:width="1dp"        android:color="@color/white_seekbar" />
    <size        android:width="1dp"        android:height="200dp" />
</shape>

circle.xml:-
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"    android:shape="rectangle">
    <stroke        android:width="1dp"        android:color="@color/white_seekbar" />
    <size        android:width="1dp"        android:height="200dp" />
</shape>

Friday 19 July 2019

How to do Producer and Consumer problem in java .

ProducerThread :-


ConsumerThread:-

SharedBuffer :-
MainClass:-

BlockingQueue : is a special synchronised queue where no need to write wait and notify.

Using BlockingQueue we can write produce and consumer SharedBuffer Class:-


Friday 5 July 2019

MVVM Design Pattern with data saving on orientation change.

Here is a simple basic  example that how in MVVM design patter we can save the data on orientation change.

Here i am calling a API which will give me the data using Retrofit,LiveData,RxJava and MVVM pattern.

1. app-Gradle :-
// to use retrofit2 notation like @SerializedName("") @Expose    
implementation 'com.squareup.retrofit2:retrofit:2.5.0'    
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'    
implementation 'com.squareup.retrofit2:adapter-rxjava:2.3.0'
//to use viewModelProviders.of    
def lifecycle_version = "1.1.1"    
implementation "android.arch.lifecycle:extensions:$lifecycle_version"    
annotationProcessor "android.arch.lifecycle:compiler:$lifecycle_version"   
 implementation 'com.android.support:recyclerview-v7:28.0.0'
// For using AndroidSchedulers for io    
implementation 'io.reactivex:rxandroid:1.2.1'    
// for the using of HttpLoggingInterceptor    
implementation 'com.squareup.okhttp3:okhttp:3.10.0'    
implementation 'com.squareup.okhttp3:logging-interceptor:3.10.0'
implementation 'com.github.bumptech.glide:glide:4.9.0'
2. Create model with your aPI response like following  :-
API name:- https://jsonplaceholder.typicode.com/photos
@SerializedName("albumId")
private int albumId;

@SerializedName("id")
private int id;

@SerializedName("title")
private String title;

@SerializedName("url")
private String url;

@SerializedName("thumbnailUrl")
private String thumbnailUrl;
3. Create interface name as APIService :-
public interface APIServices {
    @GET("{photos}")
    Observable<List<PhotoResponse>> getPhotos(@Path("photos") String photos);
}

4. Create NetworkManager  :-
public class NetworkManager {
    private static final String BASE_URL = "https://jsonplaceholder.typicode.com/";

    public static APIServices getRetrofitServices() {
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(httpLoggingInterceptor).build();
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();

        return retrofit.create(APIServices.class);
    }

}

5. MainActivityRepository :-
public class MainActivityRepository {
    private MutableLiveData<List<PhotoResponse>> mutableLiveData = new MutableLiveData<>();
    private static MainActivityRepository repository;

    public static MainActivityRepository getInstance() {
        if (repository == null) {
            repository = new MainActivityRepository();
        }
        return repository;
    }

    public MutableLiveData<List<PhotoResponse>> getPhotoAPI() {
        Observable<List<PhotoResponse>> observable = NetworkManager.getRetrofitServices().getPhotos("photos");
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<PhotoResponse>>() {
                    @Override                    public void onCompleted() {

                    }

                    @Override                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override                    public void onNext(List<PhotoResponse> photoResponses) {
                        mutableLiveData.setValue(photoResponses);
                    }
                });
        return mutableLiveData;
    }
}
6. MainActivityViewModel :-
public class MainActivityViewModel extends ViewModel {
    private MutableLiveData<List<PhotoResponse>> mutableLiveData;

    public void init() {
        if (mutableLiveData != null)
            return;
        else            mutableLiveData = MainActivityRepository.getInstance().getPhotoAPI();
    }

    public LiveData<List<PhotoResponse>> getDataFromRepo() {
        return mutableLiveData;
    }
}
7. MyAdapter:-
Glide
        .with(context)
        .load(responseList.get(i).getThumbnailUrl())
        .centerCrop()
        .placeholder(R.drawable.ic_launcher_background)
        .into(myViewHolderClass.imageView);

8. MainActivity:-
Important thing:-
If we are showing data or calling api on any button click and after getting data if
we rotate the screen than we will lost the data to overcome this problem we have
to do slightly changes in the code like below:-

Tuesday 18 June 2019

Fragment Navigation Component Graph in Android.


Steps:-
Dependencies:-
implementation 'android.arch.navigation:navigation-fragment:1.0.0'
1. Create a new Project.
2. Create a directory name "navigation" inside res folder like below

3. Right click on navigation directory and add  Navigation Resource File like below :-




4.Click on MainActivity's XML file and do following :-
activity_main:-
here we have to take one fragment which will hold the fragment. And this will be also my hostFragment , 3 important thing don't forget to add:-

android:name="androidx.navigation.fragment.NavHostFragment"
app:navGraph="@navigation/login_nav_graph"
app:defaultNavHost="true"


5.Click on navigation folder and click on login_nav_graph.xml and go to design and click on + button and click  "create new designation" and create LoginFragment like below :-
6. be continue to add all classes like that and than the graph will like below:-
7. 

Main Import is:-
import static androidx.navigation.Navigation.findNavController;
code that on click of various button how to write code for navigation:-
public class LoginFragment extends Fragment {
    Button btnMobile, btnFacebook;

    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment        return inflater.inflate(R.layout.fragment_login, container, false);
    }

    @Override    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        btnMobile = view.findViewById(R.id.btnMobile);
        btnFacebook = view.findViewById(R.id.btnFacebook);

        btnMobile.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                findNavController(getActivity(), R.id.btnMobile).navigate(R.id.mobileFragment, null);
            }
        });
        btnFacebook.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                findNavController(getActivity(), R.id.btnFacebook).navigate(R.id.facebookFragment, null);
            }
        });
    }
}








Wednesday 12 June 2019

Interview Question of Android

1. Android architecture explains all the layer 
2. Where share preferences data is Saving in android 
3. How to make our own app launcher 
4.what is bound service.. how it’s working

5. What is intent filter
Ans:- An Intent filter is an expression in app's manifest file that specifies the type of intent that the component would like to receive  would like to receive . Its like directly start an activity with certain kind of intent.

6. What is component/element of intent filter :-
There are 3 element of intent :-
1. action:- This is mandatory part of the Intent object. Here we r giving predefine action to performed by target activity.
2. data:- this specifies the data type expected by the activity.
3.category:- It is optional part, its like a additional information about the action.

7. How to create table in SQLite.
SQLiteDatabase db = db=openOrCreateDatabase("MyDatabase", Context.MODE_PRIVATE,null);db.execSQL("create table if not exists student(ID integer PRIMARY KEY AUTOINCREMENT NOT NULL,NAME varchar(20),PHONE varchar(11))"); Insert:ContentValues cv=new ContentValues();cv.put("ID",Integer.parseInt(edtId.getText().toString().trim()));
9. What is retrofit :-
8.  How to make todo app in android write steps and flow 

Ans:- Retrofit is REST client for java and android. Its make easy to retrive and upload JSON or other structure data via REST base services. In Retrofit we can configure that which converters factory can use to parsing of data. Typically in Retrofit we are using GSON , but we can also add custom converter factory to process XML or other protocols. Retrofit using IkHttp library for HTTPS request.

10. How to call retrofit
Ans:-  To call Retrofit we basically require 3 things :-
A. Model class of request and response which is used as a JSON model.
B. Interfaces that define the possible HTTPS operations.
C. Retrofit.Builder class :- This class will return the instance of the Interface class , it will also allow to define Base url for HTTP request.
Every method of interface represent  one possible API call.It must have HTTP annotation (GET,POST, etc) which specify the request type and relative URL.
Source:- https://www.journaldev.com/13639/retrofit-android-example-tutorial

11. How R.java is creating in android 
Ans:- Android R.java is an auto-generated file by aapt (Android Asset Packaging Tools) that contain resource IDs for all the resource of res/directory. If we create a XML file than the id for the corresponding component is automatically created in this file, this id use to perform any action on the component.
12. Who is creating r. Java in  android studio :-
aapt (Android Asset Packaging Tool)

13. How  apk in android  creating .

14. What is garbage collection :-
Ans:- It will free unreferenced memory. Internally GC maintaining a tree , in that if any node  not refer  any root than GC will collect that memory and become free that node from memory.
There are 3 steps for the G.C:-
A). Mark:- It will mark all the unreferenced memory.
B). Sweep:- It will delete/free all marked memory.
C). Compaction:- It will compact all free memory to make a bigger chunks.
Types of G.C:-
a. Serial GC :-
When mark and sweep will run all task will stop.
It is bad user experience.
Single threaded process.
b.Parallel GC:-
In this also when mark and sweep run no other thread of application will run.
But in this mark will be multithreaded so mark will completed very fast.
c. Hybrid GC:-
It use CMS (Concurrent mark and sweep Algorithm).
It is same like parallel but in this application thread can run during mark and sweep.

15. What to do when ur app is saying out of memory.
Ans:-
Q. What is Memory leaks.
 A memory leak happen when memory is allocated but never freed.It means memory are out of GC reach.
Its like if we did not free our home for 2 Weeks than imagine what will happen it may smell right? Same way if user keep on using app than memory also keeps on increasing ,if memory leak are not plugged than than unused memory never will free by GC. In this case we will get popup ANR which will crashed the application.

Q. How we can check that our app is leaking?
Ans:- there is an awesome library called "LeakyCabary" which we can use to see leking of memory in app along with stack trace.
Q. Common mistakes that leads to memory leaks.
Ans:-
1. Broadcast Receivers:-  we use a broadcast receiver but we didn't unregister the broadcast receiver then it will holds the reference of activity even if we close the activity. To fix this always we have to call unregister receiver inStop() of activity.Good practice is like always try to call or register a receiver in inStart() or onResume() of activity.
2. Static Activity or View Reference :-
If we reference any view like: TextView,Button as static than the activity would not be garbage collected after it destroyed. So Always remember to Never use static variable for view or activity or contexts.
3. Inner class reference.
Ans:- Never make any static variable inside inner class.  The class should be set to static. Use weak reference of any view and activity.
4. Use applicationContext() instead of activity context if possible.
source:- https://android.jlelse.eu/9-ways-to-avoid-memory-leaks-in-android-b6d81648e35e

16. Screen orientation .. when we change screens orientation where to write toast that screen orientation changes 
17 . How many thing we can call on configuration changed methods 

18. What is AAPT (Android Asset Packaging Tool)) :-
AAPT is a build tool that Android Studio and Android Gradle Plugin use to compile and package your app’s resources. AAPT2 parses, indexes, and compiles the resources into a binary format that is optimized for the Android platform.

19. From which layer of android architecture app will communicate hardware .

20. What is monkey test .
Random test done by QA

21. What is single top which use in android activity 

22. In what format data is saving in shared preference.
Key and value

23. Sensor in android.
24. What is service and its type explain.
25. What is difference between process,thread,task and service.
25. What is component of Android.
26. OOPS concept .
27. Explain following:-
Static,Abstract,Interface,final,synchronized,thread.
28. Write multithreading program.

29. What is RetroLambada.

Retrolambda is a library which allows to use Java 8 lambda expressions, method references and try-with-resources statements on Java 7, 6 or 5.
In earlier versions of Android, Java 8 was not supported. Retrolambda provides a way to use "lambda expressions" on Java versions below 8.
Common examples of lambdas in Android are for click listeners

The Gradle Retrolambda Plug-in allows to integrate Retrolambda into a Gradle based build. This allows for example to use these constructs in an Android application, as standard Android development currently does not yet support Java 8.
TextView textView = (TextView) findViewById(R.id.text_view);
textView.setOnLongClickListener(v -> System.out.println("Long Click"));
30. What is ThreeTenAbp?
https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project