In this video it shows how to use thread.join to wait for the thread to complete before proceeding with the next steps/ execution in the code of your Android App.
To demonstrate it uses parts of the code from the below page: https://programmerworld.co/android/ho...
I hope you like this video. For any questions, suggestions or appreciation please contact us at: https://programmerworld.co/contact/ or email at: programmerworld1990@gmail.com
Complete source code and other details/ steps of this video are posted in the below link:
https://programmerworld.co/android/ho...
However, the main Java code is copied below also for reference:
package com.programmerworld.waitforthreadtocomplete;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private StringBuilder stringBuilder = new StringBuilder();
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
}
public void buttonThreadWithoutWait(View View){
stringBuilder.setLength(0); // resetting the StringBuilder
stringBuilder.append("NULL");
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
HTTPConnect();
}
});
thread.start();
textView.setText(stringBuilder.toString());
}
public void buttonThreadWithWait(View View){
stringBuilder.setLength(0); // resetting the StringBuilder
stringBuilder.append("NULL");
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
HTTPConnect();
}
});
thread.start();
try { // Waiting for the thread to complete
thread.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
textView.setText(stringBuilder.toString());
}
private void HTTPConnect(){
try {
HttpURLConnection httpURLConnection = null;
URL url = new URL("https://www.google.com/");
httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int intInputStreamData = inputStreamReader.read();
while (intInputStreamData != -1){
stringBuilder.append((char) intInputStreamData);
intInputStreamData = inputStreamReader.read();
}
if (httpURLConnection!=null){
httpURLConnection.disconnect();
}
} catch (Exception e){
textView.setText(e.toString());
}
}
}
--
In questa pagina del sito puoi guardare il video online How to wait for a Thread to complete in Android App java code? della durata di ore minuti seconda in buona qualità , che l'utente ha caricato Programmer World 13 febbraio 2024, condividi il link con amici e conoscenti, su youtube questo video è già stato visto 279 volte e gli è piaciuto 7 spettatori. Buona visione!