Android interview – Telegram
Networking and Data Persistence

1. What is Retrofit and how does it work?
Answer: Retrofit is a type-safe HTTP client for Android and Java used to make network requests easier and more efficient. It allows developers to define interfaces with annotated methods specifying the HTTP request method, URL, request parameters, headers, and response type. These interfaces are then used to create and send HTTP requests, and to handle the responses. Retrofit also supports several conversion libraries for parsing the response data, including Gson, Jackson, and Moshi.


@GET("posts") Call<List<Post>> getPosts(
@Query("userId") int userId);


In the above example, a GET request is made to the URL “
https://example.com/posts" with a query parameter “userId”. The response is expected to be a List of Post objects.

2. What is the difference between Gson and Jackson libraries for JSON parsing in Android?

Answer: Gson and Jackson are two popular Java libraries for parsing JSON data. Gson is developed by Google and is known for its simplicity and ease of use, while Jackson is more powerful and feature-rich, but also more complex to use. Gson provides a set of APIs to convert Java objects to JSON and vice versa, while Jackson provides both streaming and databinding APIs for JSON processing.

Gson gson = new Gson(); String json = "{\"id\": 1, \"noscript\": \"Post Title\", \"body\": \"Post Body\"}"; Post post = gson.fromJson(json, Post.class);
In the above example, a Post object is created from a JSON string using the Gson library.


3. What is Room and how is it used for data persistence in Android? Answer: Room is a part of the Android Jetpack library used for local data storage in Android apps. It provides an abstraction layer over SQLite database operations, making it easier for developers to perform common database tasks such as querying, inserting, updating, and deleting data. Room uses annotations to define entities, which are objects representing tables in the database, and DAOs (Data Access Objects), which are interfaces providing methods for accessing the database.

@Entity(tableName = "posts")
public class Post {
@PrimaryKey public int id; public String noscript; public String body;
}

@Dao public interface PostDao {

@Query("SELECT * FROM posts")
List<Post> getAllPosts();

@Insert void insertPost(Post post);
}
In the above example, a Post entity is defined with annotations specifying its primary key and table name. A PostDao interface is also defined with methods for retrieving and inserting Post objects.


4. What is the difference between synchronous and asynchronous network requests in Android?

Answer: Synchronous network requests in Android are executed on the main thread, which can lead to application freezes and unresponsiveness. Asynchronous network requests, on the other hand, are executed on separate threads in the background, allowing the main thread to continue processing user interface events. Asynchronous requests are typically implemented using callbacks, interfaces, or Kotlin coroutines.

OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("
https://example.com/posts")
.build(); client.newCall(request)
.enqueue(new Callback() {

@Override public void onResponse(Call call, Response response) throws IOException {
String responseBody = response.body().string();
Log.d(TAG, responseBody);
}

@Override public void onFailure(Call call, IOException e) {
Log.e(TAG, e.getMessage());
}
});
In the above example, an asynchronous network request is made using the OkHttp library. The request is executed on a separate thread and the response is handled using a callback.
5. What is Retrofit in Android? How does it work?
Answer: Retrofit is a popular type-safe HTTP client library used for making API calls in Android applications. It simplifies the process of retrieving and sending JSON or XML data from a web service. It works by defining an interface that describes the HTTP endpoints of the API, and Retrofit takes care of creating the implementation of this interface during runtime. For example, the following code snippet shows how to define an interface using Retrofit:

public interface MyApi {
@GET("users") Call<List<User>> getUsers();
}

6. What is Room in Android? How is it different from SQLite?

Answer: Room is a database library in Android that provides an abstraction layer over SQLite, making it easier to work with local data storage in Android applications. It simplifies the process of defining database schemas, querying data, and managing database transactions. Room provides compile-time verification of SQL queries and makes it easier to migrate database schemas. It is different from SQLite in that it provides a more object-oriented approach to database operations and is integrated with other Android libraries like LiveData, making it easy to observe changes to the database.

7. What is the difference between REST and SOAP APIs?

Answer: REST (Representational State Transfer) and SOAP (Simple Object Access Protocol) are two different types of APIs used for web services. REST APIs are lightweight and rely on HTTP requests to perform operations like creating, reading, updating, and deleting data. REST APIs use HTTP methods like GET, POST, PUT, and DELETE to manipulate resources on the server. On the other hand, SOAP APIs are more heavyweight and rely on XML messaging to perform operations. SOAP APIs define a formal contract between the client and server, including the types of data that can be exchanged, and provide more security features.

8. How do you handle network requests in Android?

Answer: In Android, network requests can be handled using libraries like Retrofit, OkHttp, or Volley. These libraries provide HTTP clients that make it easy to make API requests and handle responses asynchronously. The request and response data can be serialized and deserialized using JSON or XML parsers like GSON or Jackson. Network requests should be performed on a separate thread or using an asynchronous mechanism like callbacks or coroutines to avoid blocking the main thread.
👍1🤩1
9. What is Okhttp?

Answer: OkHttp is a popular networking library used in Android app development to make HTTP requests. It’s built on top of the Java HttpURLConnection API and provides a simple API for sending and receiving HTTP requests and responses. OkHttp includes support for features such as caching, compression, timeouts, and authentication. It also supports synchronous and asynchronous requests.

Example: Here’s an example of using OkHttp to make a GET request and retrieve data from an API:

val client = OkHttpClient()
val request = Request.Builder()
.url("
https://api.example.com/users")
.build()
val response = client.newCall(request).execute()
val responseBody = response.body?.string() // Process the response body here


10. What is the purpose of the Cache-Control header in HTTP requests?
Answer: The Cache-Control header in HTTP requests specifies how the response should be cached by the client or intermediate caches like proxies. The header value can include directives like max-age, which indicates the maximum time the response can be cached, no-cache, which indicates that the response cannot be served from cache without validation, and no-store, which indicates that the response cannot be cached at all. The Cache-Control header is useful for controlling the caching behavior of responses and can help reduce the number of network requests and improve app performance.

11. What is JSON? How is it used in Android app development?

Answer: JSON (JavaScript Object Notation) is a lightweight data interchange format used for exchanging data between web services and clients. It consists of a collection of key-value pairs that can be nested to form complex data structures. In Android app development, JSON is commonly used for parsing data from web services and converting them into Java or Kotlin objects using libraries like GSON or Jackson. JSON data can also be sent as part of HTTP requests to web services to create or update resources.
👍2
Forwarded from Android frameworks
Which status code means unauthorized access?
Anonymous Quiz
80%
401 Unauthorized
14%
403 Forbidden
5%
404 Not Found
1%
400 Bad Request
Which modifier in Compose is used to add padding to a UI element?
Anonymous Quiz
3%
spacing()
5%
margin()
89%
padding()
4%
offset()
🔥1
Which component is used for displaying a vertical list of items in Compose?
Anonymous Quiz
11%
ListView
75%
LazyColumn
6%
RecyclerView
8%
ColumnList
👍1
What is the correct way to store UI state in Compose?
Anonymous Quiz
6%
LiveData
88%
remember { mutableStateOf(...) }
3%
ViewModelScope.launch { ... }
3%
setState()
1
Multithreading and Concurrency

1. What is the difference between a process and a thread in Android?

Answer: A process is a separate instance of an application that runs in its own memory space, while a thread is a separate execution path within a process. In Android, a process can contain multiple threads.

2. What are the different ways to implement multithreading in Android?

Answer: There are several ways to implement multithreading in Android, including using threads, handlers, AsyncTask, Loaders, and Executors.

3. What is the difference between AsyncTask and Thread in Android?

Answer: AsyncTask is an Android-specific class that provides a simple way to perform asynchronous operations on the UI thread, while Thread is a general-purpose class in Java that provides a way to perform concurrent operations in a separate thread.

4. What is synchronization in Android, and why is it important?

Answer: Synchronization is a mechanism that ensures that only one thread can access a shared resource at a time. In Android, synchronization is important to avoid race conditions and ensure thread safety when accessing shared data.

5. What is a deadlock in multithreading, and how can it be prevented?

Answer: A deadlock is a situation where two or more threads are blocked waiting for each other to release a resource, resulting in a system deadlock. Deadlocks can be prevented by using proper synchronization and avoiding nested locks.

6. What is a Handler in Android, and how does it work?

Answer: A Handler is a mechanism that allows you to send and process messages between different threads. It works by associating a Looper object with a thread and then creating a Handler object to send and receive messages.

7. What is a race condition in multithreading, and how can it be prevented?

Answer: A race condition is a situation where multiple threads access a shared resource in an unpredictable order, leading to incorrect results. Race conditions can be prevented by using proper synchronization techniques such as locks, semaphores, and atomic variables.

8. What is the difference between a synchronous and asynchronous operation in Android?

Answer: A synchronous operation blocks the current thread until the operation completes, while an asynchronous operation does not block the current thread and instead uses a callback or listener to notify when the operation completes.

9. What is a ThreadPoolExecutor in Android, and how does it work?

Answer: A ThreadPoolExecutor is a class in Android that provides a pool of worker threads to execute submitted tasks. It works by creating a pool of threads and assigning tasks to them based on their availability.

10. What is the role of a ContentProvider in Android, and how is it related to multithreading?

Answer: A ContentProvider is a class in Android that provides a standardized interface for accessing data from different applications. ContentProviders are related to multithreading in that they must handle concurrent access to shared data from multiple threads and processes in a thread-safe manner.
1🏆1
Forwarded from Android frameworks
Google's stable JavaScript engine for Android is out

The new stable Jetpack JavaScript Engine library will allow developers to run JS code in an isolated and limited environment.
Performance Optimization

1. What are the different types of performance issues you have encountered in Android apps? How did you identify and resolve them?

Answer: The candidate should be able to describe different types of performance issues such as slow UI rendering, slow network requests, memory leaks, and excessive CPU usage. They should also be able to explain how they identified these issues using tools like Android Profiler, and how they resolved them using techniques such as caching, improving network requests, optimizing memory usage, and using asynchronous operations.

Example: In one of my previous projects, we noticed that our app’s UI was taking a long time to load. We used Android Profiler to identify the cause and found that we were doing too much work on the main thread, which was causing the UI to freeze. To resolve this issue, we moved the heavy processing to a background thread using AsyncTask and also implemented caching for frequently used data to reduce the number of network requests.