Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Created January 29, 2024 19:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sunmeat/5a3d59cc76b0f3e82001c9651b1cef02 to your computer and use it in GitHub Desktop.
Save sunmeat/5a3d59cc76b0f3e82001c9651b1cef02 to your computer and use it in GitHub Desktop.
live data android example
/* вместо AsyncTask был использован Thread для выполнения операций в фоновом режиме в MainViewModel.
также, для обновления UI с использованием LiveData, был использован Handler для отправки сообщений в основной поток */
MainActivity.java:
package com.sunmeat.async;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
private ProgressBar progressBar;
private MainViewModel viewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.btnProgressBar);
imageView = findViewById(R.id.my_image);
progressBar = findViewById(R.id.progressBar);
viewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication())).get(MainViewModel.class);
viewModel.getProgressLiveData().observe(this, progress -> {
progressBar.setProgress(progress);
});
viewModel.getImagePathLiveData().observe(this, imagePath -> {
imageView.setImageDrawable(Drawable.createFromPath(imagePath));
});
button.setOnClickListener(v -> viewModel.downloadFile(this));
}
}
===================================================================================================================
MainViewModel.java:
package com.sunmeat.async;
import android.content.Context;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Paths;
public class MainViewModel extends ViewModel {
private final MutableLiveData<Integer> progressLiveData = new MutableLiveData<>();
private final MutableLiveData<String> imagePathLiveData = new MutableLiveData<>();
LiveData<Integer> getProgressLiveData() {
return progressLiveData;
}
LiveData<String> getImagePathLiveData() {
return imagePathLiveData;
}
void downloadFile(Context context) {
new Thread(() -> {
try {
String fileUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/375px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg";
URL url = new URL(fileUrl);
URLConnection connection = url.openConnection();
connection.connect();
int lengthOfFile = connection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(), 8192);
OutputStream output = Files.newOutputStream(Paths.get(context.getFilesDir() + "/downloadedfile.jpg"));
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
int progress = (int) (total * 100 / lengthOfFile);
progressLiveData.postValue(progress);
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
String imagePath = context.getFilesDir() + "/downloadedfile.jpg";
imagePathLiveData.postValue(imagePath);
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
}
===================================================================================================================
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btnProgressBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Download Image" />
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp" />
<ImageView
android:id="@+id/my_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp" />
</LinearLayout>
===================================================================================================================
AndroidManifest.xml:
...
<uses-permission android:name="android.permission.INTERNET" />
...
===================================================================================================================
build.gradle.kts (Module:app):
dependencies {
...
implementation ("android.arch.lifecycle:extensions:1.1.1")
annotationProcessor ("android.arch.lifecycle:compiler:1.1.1")
implementation ("androidx.lifecycle:lifecycle-viewmodel:2.7.0")
implementation ("androidx.lifecycle:lifecycle-livedata:2.7.0")
implementation ("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.1")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment