I have a main class, a worker thread class and it separated. In main thread, I pass input to worker thread and ask for it to work. When it finish, I want it to send back result
Maybe you should try AsynTask
, it is designed for just that:
private class MyThread extends AsyncTask<Params, Progress, Result> {
protected Long doInBackground(URL... urls) {
// Calculate and return retulst
}
protected void onPostExecute(Long result) {
// This is executed in main Thread, use the result
}
}
You execute this thread like this:
new MyThread().execute(params, ...);
See http://developer.android.com/reference/android/os/AsyncTask.html
You can post a runnable to be executed on the main UI thread using the following code at the end of your thread's run()
method:
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO: modify the text view, other UI elements, etc.
}
});
use AsyncTask instead to avoid any multi-threading issues example code:
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
@Override
protected void onPostExecute(String result) {
textView.setText(result);
}}
Use it as an inner class in your adapter Also you can use many APIs like volly if you are into networking.