Showing posts with label Android code sample: thread. Show all posts
Showing posts with label Android code sample: thread. Show all posts

Thursday, May 19, 2016

SwipeRefreshLayout, refresh in background thread


Last post show a basic example of SwipeRefreshLayout. But, normally refreshing involve some longtime task; such as loading data from Internet. This example show how to refresh with longtime task in background thread.


MainActivity.java
package com.blogspot.android_er.androidswiperefresh;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MainActivity extends AppCompatActivity {

SwipeRefreshLayout swipeRefreshLayout;
ListView swipeList;

List<String> myList;
ListAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.swiperefreshlayout);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
refresh();
}
});

swipeList = (ListView)findViewById(R.id.swipelist);

myList = new ArrayList<>();
adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1, myList);
swipeList.setAdapter(adapter);

swipeList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = (String) parent.getItemAtPosition(position);
Toast.makeText(MainActivity.this, item, Toast.LENGTH_LONG).show();
}
});
}

private void refresh(){

final int pos = myList.size();
myList.add(pos, "Refreshing...");
swipeList.invalidateViews();
swipeRefreshLayout.setRefreshing(true);

//refresh long-time task in background thread
new Thread(new Runnable() {
@Override
public void run() {
try {
//dummy delay for 2 second
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}

//update ui on UI thread
runOnUiThread(new Runnable() {
@Override
public void run() {
String currentDateTime =
DateFormat.getDateTimeInstance().format(new Date());
myList.set(pos, pos + " - " + currentDateTime);
swipeList.invalidateViews();
swipeRefreshLayout.setRefreshing(false);
}
});

}
}).start();
}
}


Keep using the layout in last post.

more:
SwipeRefreshLayout, work with RecyclerView

Wednesday, March 30, 2016

Load something from Internet using URLConnection and ReadableByteChannel, in Thread

Last example show "Load something from Internet using URLConnection and BufferedReader, in Thread". Here is another example using java.nio.channels.ReadableByteChannel.

Read operations are synchronous on a ReadableByteChannel, that is, if a read is already in progress on the channel then subsequent reads will block until the first read completes. It is undefined whether non-read operations will block.


MainActivity.java
package com.blogspot.android_er.androidinternet;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;

public class MainActivity extends AppCompatActivity {

TextView textResult;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textResult = (TextView)findViewById(R.id.tresult);

MyThread myThread = new MyThread("http://android-er.blogspot.com", textResult);
myThread.start();
}

class MyThread extends Thread{
String target;
TextView textviewResult;

private Handler handler = new Handler();

public MyThread(String target, TextView textviewResult) {
super();
this.target = target;
this.textviewResult = textviewResult;
}

@Override
public void run() {
String result = "";

URL url = null;
try {
url = new URL(target);
URLConnection urlConnection = url.openConnection();
InputStream inputStream = urlConnection.getInputStream();

ReadableByteChannel readableByteChannel = Channels.newChannel(inputStream);
ByteBuffer buffer = ByteBuffer.allocate(1024);

while (readableByteChannel.read(buffer) > 0)
{
result += new String(buffer.array());
buffer.clear();
}

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}


final String finalResult = result;
handler.post(new Runnable() {
@Override
public void run() {
textviewResult.setText(finalResult);
Toast.makeText(MainActivity.this,
"finished", Toast.LENGTH_LONG).show();
}
});
}
}
}


For layout and AndroidManifest.xml, refer to the previous post "Load something from Internet using URLConnection and BufferedReader, in AsyncTask".


Tuesday, March 29, 2016

Load something from Internet using URLConnection and BufferedReader, in Thread

Previous post show how to Load something from Internet using URLConnection and BufferedReader, in AsyncTask. This post show how to do it in Thread, and update UI using Handler.



MainActivity.java
package com.blogspot.android_er.androidinternet;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class MainActivity extends AppCompatActivity {

TextView textResult;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textResult = (TextView)findViewById(R.id.tresult);

MyThread myThread = new MyThread("http://android-er.blogspot.com", textResult);
myThread.start();
}

class MyThread extends Thread{
String target;
TextView textviewResult;

private Handler handler = new Handler();

public MyThread(String target, TextView textviewResult) {
super();
this.target = target;
this.textviewResult = textviewResult;
}

@Override
public void run() {
String result = "";

try {
URL url = new URL(target);
URLConnection urlConnection = url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader inputStreamReader =
new InputStreamReader(inputStream);
BufferedReader buffReader = new BufferedReader(inputStreamReader);

String line;
while ((line = buffReader.readLine()) != null) {
result += line;
}

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

final String finalResult = result;
handler.post(new Runnable() {
@Override
public void run() {
textviewResult.setText(finalResult);
Toast.makeText(MainActivity.this,
"finished", Toast.LENGTH_LONG).show();
}
});
}
}
}


For layout and AndroidManifest.xml, refer to the previous post "Load something from Internet using URLConnection and BufferedReader, in AsyncTask".

Related:
Load something from Internet using URLConnection and ReadableByteChannel, in Thread

Thursday, March 24, 2016

AsyncTask vs Thread + Handler


This post show how to implement using AsyncTask and Thread/Handler to perform the same function: doing something in background and update UI elements (ProgressBar and TextView).

This video show how it run on Android Emulator running Android N, in Multi-Window.


AsyncTask

MainActivity.java
package com.blogspot.android_er.androidasynctask;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

Button btnStart;
ProgressBar progressBar;
TextView textMsg;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

progressBar = (ProgressBar)findViewById(R.id.progress);
textMsg = (TextView)findViewById(R.id.msg);

btnStart = (Button)findViewById(R.id.start);
btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MyAsyncTask myAsyncTask = new MyAsyncTask(progressBar, textMsg);
myAsyncTask.execute();
}
});
}

class MyAsyncTask extends AsyncTask<Void, Integer, Void>{

ProgressBar pBar;
TextView tMsg;

public MyAsyncTask(ProgressBar pBar, TextView tMsg) {
super();
this.pBar = pBar;
this.tMsg = tMsg;
}

@Override
protected Void doInBackground(Void... params) {
for(int i=0; i<=10; i++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

publishProgress(i);
}
return null;
}

@Override
protected void onProgressUpdate(Integer... values) {
pBar.setProgress(values[0]);
}

@Override
protected void onPostExecute(Void aVoid) {
tMsg.setText("finished");
}
}
}


layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:orientation="vertical"
tools:context="com.blogspot.android_er.androidasynctask.MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="http://android-er.blogspot.com/"
android:textStyle="bold" />

<Button
android:id="@+id/start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Start"/>

<ProgressBar
android:id="@+id/progress"
style="?android:attr/progressBarStyleHorizontal"
android:indeterminate="false"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="10"
android:progress="0"/>
<TextView
android:id="@+id/msg"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>



Thread + Handler

MainActivity.java
package com.blogspot.android_er.androidthreadhandler;

import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import org.w3c.dom.Text;

public class MainActivity extends AppCompatActivity {

Button btnStart;
ProgressBar progressBar;
TextView textMsg;

private Handler handler = new Handler();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

progressBar = (ProgressBar)findViewById(R.id.progress);
textMsg = (TextView)findViewById(R.id.msg);

btnStart = (Button)findViewById(R.id.start);
btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MyThread myThread = new MyThread(progressBar, textMsg);
myThread.start();
}
});
}

class MyThread extends Thread{

ProgressBar pBar;
TextView tMsg;

public MyThread(ProgressBar pBar, TextView tMsg) {
super();
this.pBar = pBar;
this.tMsg = tMsg;
}

@Override
public void run() {

for (int i = 0; i <= 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

//is accessed from within inner class, needs to be declared final
final int finalI = i;
handler.post(new Runnable() {
@Override
public void run() {
pBar.setProgress(finalI);
}
});
}

handler.post(new Runnable() {
@Override
public void run() {
tMsg.setText("finished");
}
});
}
}
}


layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:orientation="vertical"
tools:context="com.blogspot.android_er.androidthreadhandler.MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="http://android-er.blogspot.com/"
android:textStyle="bold" />

<Button
android:id="@+id/start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Start"/>

<ProgressBar
android:id="@+id/progress"
style="?android:attr/progressBarStyleHorizontal"
android:indeterminate="false"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="10"
android:progress="0"/>
<TextView
android:id="@+id/msg"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>



next:
- HandlerThread example

related:
Load something from Internet using URLConnection and BufferedReader, in AsyncTask
Load something from Internet using URLConnection and BufferedReader, in Thread