Asynchronous Data Handling, Networking and Files
Asynchronous Data Handling
Performing tasks in the background (non-UI thread) to keep UI smooth.
Why Needed?
- Avoid UI freezing (ANR – Application Not Responding)
- Handle network & database operations efficiently
Synchronous vs Asynchronous
| Feature | Synchronous | Asynchronous |
|---|---|---|
| Execution | One after another | Parallel/background |
| UI Blocking | Yes | No |
| Speed | Slow | Faster |
AsyncTask
Performs background operations and updates UI.
Lifecycle of AsyncTask
onPreExecute()
↓
doInBackground()
↓
onProgressUpdate()
↓
onPostExecute()
Example
private class MyTask extends AsyncTask<Void, Void, String> {
protected void onPreExecute() {
// Before execution
}
protected String doInBackground(Void... params) {
return "Data loaded";
}
protected void onPostExecute(String result) {
textView.setText(result);
}
}
Coroutines (Modern Approach)
Lightweight threads used in Kotlin for async programming.
Features
- Easy to read/write
- Less memory usage
- Structured concurrency
Coroutine Flow
Main Thread
|
launch{}
|
suspend function
|
Background Work
Example (Kotlin)
GlobalScope.launch {
val data = fetchData()
withContext(Dispatchers.Main) {
textView.text = data
}
}
Coroutine Dispatchers
| Dispatcher | Use |
|---|---|
| Main | UI thread |
| IO | Network/DB |
| Default | CPU tasks |
API Handling
Fetching data from server using HTTP methods.
Common Methods
| Method | Purpose |
|---|---|
| GET | Retrieve data |
| POST | Send data |
| PUT | Update data |
| DELETE | Remove data |
API Flow
App → HTTP Request → Server → JSON Response → UI
JSON Parsing
Converting JSON data into usable objects.
Example JSON
{
"name": "Jay",
"age": 25
}
Parsing Example (Java)
JSONObject obj = new JSONObject(jsonString);
String name = obj.getString("name");
JSON Types
| Type | Example |
|---|---|
| Object | { } |
| Array | [ ] |
| Key-Value | "name":"Jay" |
Volley Library
Library for network requests.
Features
- Automatic caching
- Easy API calls
- Request queue
Volley Architecture
Request → Queue → Network → Response → UI
Example
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.GET, url,
response -> textView.setText(response),
error -> error.printStackTrace()
);
queue.add(request);
Retrofit Library
Type-safe HTTP client for Android.
Features
- Converts JSON to objects
- Easy API interface
- Supports coroutines
Retrofit Flow
Interface → Retrofit → API Call → Response → Model Class
Example
public interface ApiService {
@GET("users")
Call<List<User>> getUsers();
}
Volley vs Retrofit
| Feature | Volley | Retrofit |
|---|---|---|
| Ease of Use | Medium | Easy |
| JSON Parsing | Manual | Automatic |
| Performance | Good | Excellent |
File Handling in Android
Types
- Internal storage
- External storage
Write File
FileOutputStream fos = openFileOutput("file.txt", MODE_PRIVATE);
fos.write("Hello".getBytes());
fos.close();
Read File
FileInputStream fis = openFileInput("file.txt");
HTML Parsing
Extracting data from HTML content.
Example
Spanned html = Html.fromHtml("<b>Hello</b>");
textView.setText(html);
XML Parsing
Reading XML structured data.
Types
| Parser | Description |
|---|---|
| DOM | Loads full XML |
| SAX | Event-based |
| Pull Parser | Efficient |
Example (XML Pull)
XmlPullParser parser = Xml.newPullParser();
Broadcast Receivers
Responds to system-wide events.
Examples
- Battery low
- Network change
Flow
System Event → Broadcast Receiver → App Action
Example
public class MyReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Event Received", Toast.LENGTH_SHORT).show();
}
}
Services
Runs in background without UI.
Types
| Type | Description |
|---|---|
| Foreground | Visible to user |
| Background | Hidden |
| Bound | Linked to component |
Service Lifecycle
onCreate()
↓
onStartCommand()
↓
Running
↓
onDestroy()
Example
public class MyService extends Service {
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
}
Combined Architecture Diagram
UI
|
Coroutine / AsyncTask
|
API Call (Retrofit/Volley)
|
JSON Parsing
|
Database/File
|
LiveData → UI
Important Exam Questions
Short Questions
- What is AsyncTask?
- Define Retrofit.
- What is Broadcast Receiver?
Long Questions
- Explain coroutines with example.
- Compare Volley and Retrofit.
- Describe Service lifecycle.
Practical Questions
- Write API call using Retrofit.
- Parse JSON data.
- Create Broadcast Receiver.
Final Summary
- AsyncTask → Old async method
- Coroutines → Modern async
- Retrofit/Volley → Networking
- JSON/XML → Data formats
- BroadcastReceiver → Events
- Service → Background tasks