I am Calling a Asynctask from Mainactivity Using alarm manager Every 5 minutes
My Asynctask is kept in a New Service Class.
Using that Asynctask I'm retrieving String values from Web service.
Retrieving from web Service Saving in String Array Works fine.
Problem:
I want pass that String Array value from Web service doInBackground to Mainactivity is Getting Null.
Help me how to achieve this.
link i refered ,but no success
private class AsyncCallWSfor_SERVICE extends AsyncTask<String, Void, Void>
{
#Override
protected Void doInBackground(String... params)
{
Log.i(TAG1, "doInBackground");
try
{
getdatafromWeb();
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(),
"error caught in do in background", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute()
{
/* //progress.setTitle("Progress");
progress.setMessage("Please Wait Loading Data...");
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setIndeterminate(true);
progress.show();*/
Log.i(TAG1, "onPreExecute");
}
#Override
protected void onPostExecute(Void result)
{
// To dismiss the dialog
// progress.dismiss();
Log.i(TAG1, "onPostExecute");
}
}
public void getdatafromWeb() {
// Create request
SoapObject request = new SoapObject(NAMESPACE1, METHOD_NAME1);
// Create envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
// Set output SOAP object
envelope.setOutputSoapObject(request);
// Create HTTP call object
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL1);
try {
// Invole web service
androidHttpTransport.call(SOAP_ACTION1, envelope);
// Get the response
SoapPrimitive response1 = (SoapPrimitive) envelope.getResponse();
//Converting string to Array list
ArrayList<String> KitDistributedString_array= new ArrayList<String>();
if ((response1.toString()).contains("{")) {
SoapObject rep = (SoapObject) envelope.bodyIn;
JSONArray jr = new JSONArray(rep.getPropertyAsString(0)
.toString());
for (int i = 0; i < jr.length(); i++) {
JSONObject jb = (JSONObject) jr.get(i);
KitValueString = jb.getString("KitValue");
Log.d(TAG1 +"MY Data" , KitValueString);
KitDistributedString_array.add(KitValueString);
}
STRING_ARRAY = new String[KitDistributedString_array.size()];
STRING_ARRAY = KitDistributedString_array.toArray(STRING_ARRAY);
}
else
{
Status_Response_Service = response1.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
}
I want to pass this STRING_ARRAY to MainActivity
For getting the response to the caller activity, I suggest to write a interface Which you need to implement to caller activity
e.g
public interface WebCallable {
public void response(String[] result);
}
implement interface to activity as below
public class MainActivity extends Activity implements WebCallable
Now extend service class from AsyncTask<String, Void, String[]> and pass activity object as paramenter by 'this'. You can save this object at class level.
e.g.
public AsyncCallWSfor_SERVICE(Context context){
this.context = context
}
In onPostExecute write
context.response(STRING_ARRAY)
Better, return string response from doInBackground and get it in onPostExecute as bekow
protected void onPostExecute(String result)
and create array in onPostExecute.
Or cretae STRING_ARRAY object class level.
Related
I'm connecting to API with the async task. I need to pass two values from the API to the app, in onResponse I have logged the values and got them right. But in onPostExecute one of them keep turning into null
I have already tried to check different values from API and logs to see if the value that I'm looking for is there or if the connection is valid, everything went alright until it hits the onPostExecute where I'm getting only one value
public class ChooseLocationTask extends AsyncTask<String, Void, Void> {
OkHttpClient client = new OkHttpClient.Builder()
//default timeout for not annotated requests
.readTimeout(15000, TimeUnit.MILLISECONDS)
.connectTimeout(15000, TimeUnit.MILLISECONDS)
.writeTimeout(15000, TimeUnit.MILLISECONDS)
.build();
Request request;
private TextView location;
private TextView value;
String state;
Number probability;
String probablityString;
public ChooseLocationTask(TextView location, int selected, TextView value){
this.location = location;
this.value = value;
}
#Override
protected void onProgressUpdate(Void...values){
super.onProgressUpdate(values);
}
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected Void doInBackground(String... urls) {
request = new Request.Builder().url(urls[0]).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
Log.d("CallMsg", String.valueOf(call));
}
#Override
public void onResponse(Call call, Response response) throws IOException {
Log.d("Response", String.valueOf(response));
try {
JSONObject jsonObject = new JSONObject(response.body().string());
JSONObject weather = jsonObject.getJSONObject("weather");
JSONObject location = weather.getJSONObject("location");
state = location.getString("state");
JSONObject percentage = jsonObject.getJSONObject("probability");
JSONObject calculated = percentage.getJSONObject("highest");
probability = calculated.getInt("value");
probablityString = probability.toString();
Log.d("percentage", probability.toString());
Log.d("String",probablityString);
Log.d("location",state);
} catch (JSONException e){
e.printStackTrace();
}
}
});
return null;
}
#Override
protected void onPostExecute(Void voids){
if(isCancelled()){
voids= null;
} else {
location.setText(state);
value.setText("your chance to see Northern lights today is" + probablityString);
Log.d("value", "onPostExecute: " + probablityString);
}
Log.d("post", "onPostExecute: " + probability);
}
}
Basically, all I need is advice on how to get this value, I feel like maybe I made mistake when converting it into a string, but in logs, in onResponse it shows quite alright, so I don't know. Thank you for all the advice
Retrofit has two techniques for performing requests, one synchronous (execute()) and another asynchronous (enqueue()). You are using the asynchronous technique, and as a result, when you go to execute your AsyncTask, your doInBackground() method immediately calls enqueue(), completes, and calls onPostExecute() before your request has completed.
You have two options. First, you can keep your current AsyncTask, but replace enqueue() for execute(). This will look a little like:
public class ChooseLocationTask extends AsyncTask<String, Void, Void> {
private final OkHttpClient client = new OkHttpClient.Builder()
//default timeout for not annotated requests
.readTimeout(15000, TimeUnit.MILLISECONDS)
.connectTimeout(15000, TimeUnit.MILLISECONDS)
.writeTimeout(15000, TimeUnit.MILLISECONDS)
.build();
private final Request request;
private final TextView location;
private final TextView value;
String state;
Number probability;
String probablityString;
public ChooseLocationTask(TextView location, int selected, TextView value){
this.location = location;
this.value = value;
}
#Override
protected Void doInBackground(String... urls) {
request = new Request.Builder().url(urls[0]).build();
try {
final Response<?> response = client.newCall(request).execute();
if(response.isSuccessful()) {
final JSONObject jsonObject = new JsonObject(response.body().string());
//etc...
}
} catch (IOException e) {
//...
}
//I'd recommend you return values as well, rather than assigning them to
//instance variables
return null;
}
#Override
protected void onPostExecute(Void voids){
if(isCancelled()){
voids= null;
} else {
location.setText(state);
value.setText("your chance to see Northern lights today is" + probablityString);
Log.d("value", "onPostExecute: " + probablityString);
}
Log.d("post", "onPostExecute: " + probability);
}
Or, you can get rid of your AsyncTask entirely, and just call enqueue()
I'm very new at programming for Android - please bear with me.
I'm building an app that requires network access, using OKHttp. Since I will be making many similarly structured requests from my server, I created a class that handles all network-related tasks, as I like to keep things compartmentalized.
One method I'm working on is createNetworkThread from within my NetworkManager class. This particular method takes three arguments:
Context context, final String requestURI, final RequestBody formParameters
What I need assistance with is how to return the data received from this method so I can use and manipulate it in the calling Activity.
Here is the method in question:
public void createNetworkThread(Context context, final String requestURI, final RequestBody formParameters) {
if (!this.isConnected(context)) return;
Runnable runnable = new Runnable() {
#Override
public void run() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(requestURI).post(formParameters).build();
Response response = null;
// Send login request, get response //
try {
response = client.newCall(request).execute();
String stringResponse = response.body().string();
JSONObject jsonResponse = new JSONObject(stringResponse);
Log.d("Net", "Request send and received!");
} catch (IOException e) {
Log.d("Net", "Failed");
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
};
Thread thread = new Thread(runnable);
thread.start();
}
Here is the call from the Activity:
final NetworkManager Net = new NetworkManager(this);
...
final String requestURI = "http://192.168.1.111/videonow.club/apprequest/signup/thread.php";
final RequestBody formVars = new FormBody.Builder().add("email", strEmail).add("password", strPass1).add("first_name", strNameFirst).add("last_name", strNameLast).build();
Net.createNetworkThread(SignupActivity.this, requestURI, formVars);
What I need to know is how to get the JSON data from jsonResponse returned from the method (I know void doesn't allow this) so I can use the data.
Would it be better to have the jsonObject returned so I can use something like this:
SomeType response = Net.createNetworkThread(...);
Or, to have a class variable within NetworkManager that would be set by the method so it would be called to and referenced like this:
Net.createNetworkThread(...);
SomeType response = Net.someVariable;
Or is there some much more reasonable way to receive this data?
I'm also calling new OkHttpClient() twice - once in the activity, so I can build the requestBody post variables, as well as in the NetworkManager class itself. My instincts tell me this is redundant... if so, is there a way to make this more efficient?
Thanks in advance!
You can use OkHttp with AysncTask like this:
public class Webservice extends AsyncTask<String, String, UserResponse> {
private String TAG = Webservice.class.getSimpleName();
private static final String ENDPOINT = "YOUR_URL";
private static final Moshi MOSHI = new Moshi.Builder().build();
private static final JsonAdapter<UserResponse> CONTRIBUTORS_JSON_ADAPTER_RESPONSE = MOSHI.adapter(Types.newParameterizedType(UserResponse.class, UserResponse.class));
UserResponse webResponse;
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
String postBody = "postBody\n";
#Override
protected UserResponse doInBackground(String... parmas) {
OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();
Call call = okHttpClient.build().newCall(new Request.Builder()
.url(ENDPOINT)
.post(RequestBody.create(JSON, postBody))
.addHeader("Content-Type", "application/json")
.build());
try {
Response response = call.execute();
adModelResponse = CONTRIBUTORS_JSON_ADAPTER_RESPONSE.fromJson(response.body().source());
} catch (IOException e) {
e.printStackTrace();
}
return webResponse;
}
#Override
protected void onPostExecute(UserResponse adModelResponse) {
}
}
And then in Activity call like this:
Webservice webservice = new Webservice();
webservice.execute("YOUR_PARAMETER");
Libraries Used:
okhttp-3.2.0, moshi-1.1.0, okio-1.8.0
Make NetworkManager Abstract and add one abstract method say public abstract void onResult(JSONObject response); and override this method like
final NetworkManager Net = new NetworkManager(this){
#Override
public void onResult(JSONObject response){
//do whatever you want here
}
};
And from the createNetworkThread when finished call this method as
.....
response = client.newCall(request).execute();
String stringResponse = response.body().string();
JSONObject jsonResponse = new JSONObject(stringResponse);
onResult(jsonResponse);
......
You can use callback interface to get your data back to your activity. Consider the example below:
public interface JsonResponse {
onResponseReceived(JSONObject response);
}
Then your createNetworkThread will looks like this:
public void createNetworkThread(Context context, final String requestURI, final RequestBody formParameters, JsonResponse responseCallback) {
if (!this.isConnected(context)) return;
Runnable runnable = new Runnable() {
#Override
public void run() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(requestURI).post(formParameters).build();
Response response = null;
// Send login request, get response //
try {
response = client.newCall(request).execute();
String stringResponse = response.body().string();
JSONObject jsonResponse = new JSONObject(stringResponse);
responseCallback.onResponseReceived(jsonResponse); // This line will return to your caller
Log.d("Net", "Request send and received!");
} catch (IOException e) {
Log.d("Net", "Failed");
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
};
Thread thread = new Thread(runnable);
thread.start();
}
And finally the caller:
Net.createNetworkThread(SignupActivity.this, requestURI, formVars, new JsonResponse() {
#Override
public void onResponseReceived(JSONObject response) {
// Do stuff in your activity
// eventually use runOnUiThread for your UI operations
}
});
I have a MainActivity class from which I am calling an instance of my JsonObj class.
JsonObj extends AsynchTask. It's pasted below:
public class JsonObj extends AsyncTask<String, Void, JSONObject>{
int tid;
String term;
#Override
protected JSONObject doInBackground(String... url) {
// TODO Auto-generated method stub
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost(url[0]);
JSONObject jsonObject = null;
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null){
sb.append(line + "\n");
}
result = sb.toString();
// Log.e("JSON-Test [RESULT]: ", result);
jsonObject = new JSONObject(result);
} catch (Exception e) {
Log.e("JSON-Test [exception]: ", e.toString());
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return jsonObject;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
What I am trying to achieve is an AsyncTask class which I can call from any activity that will fetch and return JSON from my server.
My problem is my AsyncTask class successfully fetches my JSON but I am struggling to pass it back to my Activity.
I know the OnPostExecute function returns data on completion of my AsyncTask but all my attempts to access the data in my Activity class are not working.
I'm using new JsonObj().execute("http://myserver/json"); to call my JsonObj class.
How do I call OnpostExecute to directly access data my AsynchTask fetches from my server OR what is a better solution to this problem?
Create an Interface that has a method called something like "onServiceFinished" which your activities that make this call implement. Then when you call your AsyncTask, pass it (this) and in your onPostExectue, call FinishedListener.onServiceFinished(var1, var2) or whatever data your passing.
Code Example: This example uses an AsyncTask to retrieve a message from the server, and when that is finished, pass back that message to the class that requested it
Interface:
public interface ServiceHandler {
public abstract void onServiceFinished(JSONObject jsonObject);
}
Activity:
public class YourActivity extends Activity implements ServiceHandler {
#Override
public void onCreate(Bundle savedInstanceState) {
//Activity stuff
new JsonObj(this).execute("http://myserver/json");
}
#Override
public void onServiceFinished(JSONObject jsonObject) {
// Do something with the message
}
}
Asynctask:
public class JsonObj extends AsyncTask<String, Void, JSONObject> {
ServiceHandler handler;
public ChatAsync(ServiceHandler serviceHandler) {
handler = serviceHandler;
}
#Override
protected JSONObject doInBackground(String...params) {
// fetch messages from service and parse JSON
}
#Override
protected void onPostExecute(JSONObject json) {
handler.onServiceFinished(json);
}
}
The basic model is there, you'll have to modify it to fit what you're doing! Hope this helps
If you doing all network operation in a separate class and you want the result on the calling Activity class.
Create a method onTaskComplete(JsonObject result) on the calling Activity class.
public void onTaskComplete(JsonObject result) {
//Do You Operation
}
And now you need to call this method on OnPostExecute()
public class JsonObj extends AsyncTask<String, Void, JSONObject>{
Activity _context;
public JsonObj(Activity _context) {
this._context = _context;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
this._context.onTaskComplete(result);
}
}
At last call the AsyncTask
new JsonObj(this).execute("YOUR URL");
The best way to do this is with a Callback. With this pattern, you create an interface that you implement in your Activity. You then set a method in this interface callback to be run in your onPostExecute() method. For example, this basic AsyncTask will call the callback function when complete:
public class JsonObj extends AsyncTask<Void, Void, JSONObject> {
private OnSuccessListener listener;
private String url;
public JsonObj(String url, OnSuccessListener listener) {
this.url = url;
this.listener = listener;
}
#Override
protected JSONObject doInBackground(Void... params) {
//handle url getter. returning the JSONObject here will send it to the onPostExecute method.
}
#Override
protected void onPostExecute(JSONObject json) {
if (listener != null)
listener.onSuccess(json);
}
public interface OnSuccessListener {
public void onSuccess(JSONObject json);
}
}
Then to use this properly, just do this in your Activity:
new JsonObj("http://myserver/json", new OnSuccessListener() {
#Override
public void onSuccess(JSONObject json) {
//TODO: handle new JSONObject.
}
}).execute();
If you want a simpler, already coded solution, consider the droidQuery library that I wrote. Apart from simplifying animations and common UI tasks, it can simplify this sort of network call immensely. The above code can be compressed down to this in your Activity:
$.ajax(new AjaxOptions().url("http://myserver/json")
.type("POST")
.dataType("JSON")
.headers(new Headers().content_type("application/json"))
.success(new Function() {
#Override
public void invoke($ d, Object... args) {
JSONObject json = (JSONObject) args[0];
//TODO: handle json
}
});
I was just wondering if my code is ok in terms of downloading. My app needs a lot of data from a database so quick download times are crucial. The download time is ok but I think it can be programmed more efficient. Can you have a look at this? This class downloads many different companies and when downloaded they are put in a HashMap corresponding to their category. When finished downloading this class return a HashMap which contains multiple Hashmaps(categories) and in these Hashmaps the downloaded data. Dont mind the actual workflow but please concentrate on the way this class downloads data. Is there a way to do this faster?
public class CompanyDAO {
private static Controller delegate;
private static String companyUrl = "http:// URL HERE";
private Map<Object, Object> companyMap = new HashMap<Object, Object>();
private Map<String, Integer> pinMap = new HashMap<String, Integer>();
public CompanyDAO (Controller _delegate, Map<String, Integer> map) {
delegate = _delegate; //reference to controller
pinMap = map;
}
public void getCompanyData(ArrayList<Object> categoriesArray) {
for (int i = 0; i < categoriesArray.size(); i++) {
Map<String, Object> categoriesInMap = new HashMap<String, Object>();
//ArrayList<Object> categoriesInMapArray = new ArrayList<Object>();
companyMap.put(categoriesArray.get(i), categoriesInMap);
}
this.downloadCompanyData();
}
private void downloadCompanyData() {
companyUrl = companyUrl + delegate.ID;
try {
new DownloadCompanyData().execute(companyUrl).get(10000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private class DownloadCompanyData 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;
}
#SuppressWarnings("unchecked")
#Override
protected void onPostExecute(String result) {
JSONArray companyDataArray;
try {
companyDataArray = new JSONArray(result);
for(int i=0;i<companyDataArray.length();i++){
JSONObject id = companyDataArray.getJSONObject(i);
String catName = id.getString(Controller.CAT_NAME);
if (companyMap.get(catName) != null) {
Markers marker = new Markers(new LatLng(id.getDouble("latitude"), id.getDouble("longitude")), id.getString(Controller.CAT_NAME), id.getString(Controller.ID), id.getString(Controller.SUBSCRIPTION), pinMap.get(catName), id.getString(Controller.TITLE), id.getString(Controller.COMPANY_NAME), id.getString(Controller.WWW), id.getString(Controller.STREET), id.getString(Controller.HOUSE_NUMBER), id.getString(Controller.HOUSE_ADD));
((Map<String,Object>) companyMap.get(catName)).put(id.getString(Controller.TITLE), marker.markerInformationMap);
}
}
delegate.setCompanyHashMap(companyMap);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
I guess you're missing the point of the AsyncTask
it's supposed to do all the work in doInBackground() and then use the onPostExecute to deliver it to the UI.
But what you're doing is doing the network operation on doInBackground and doing data parsing on onPostExecute.
Furthermore, a JSON object is a raw data that needs further parsing. You should do all the parsing on the background. For example, let's say your companyData is address, phone number, size and name. You could have a class like this (p.s. I'm writing all this without testing, there will be a little mistake here in there, but you'll get the idea):
public class CompanyData{
private String name, address, phone;
private int size;
public CompanyData(JsonObject jo){
name = jo.getString("name");
address = jo.getString("address");
phone = jo.getString("phone");
size = jo.getInt("size");
}
// put a bunch of get methods here...
// getName(), getAddress(), etc.
}
then on your 'protected Map doInBackground(String... urls) ' you complete the network operation, create the JsonArray, create a Map<String,CompanyData>, loop through the array creating CompanyData objects and placing them into the Map and return the map to your protected void onPostExecute(Map<String,CompanyData> result) and inside the post execute it's just pass this result to the UI.
happy coding.
I always doing something like this..
...
private ProgressDialog pDialog;
ArrayList<HashMap<String, String>> CompanyList;
JSONParser jParser = new JSONParser();
JSONArray Company = null;
static String url_all_company = "http://your_site/files.php";
....
private class CompanyData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Load data..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
CompanyList = new ArrayList<HashMap<String, String>>();
// Building Parameters if any.. to fetching all data, don't declare any param
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("uid", uid));
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_company, "POST", param);
// Check your log cat for JSON reponse
Log.d("All Company: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// Company found
// Getting Array of Company
Company = json.getJSONArray(TAG_COMPANIES);
// looping through All Company
for (int i = 0; i < Company.length(); i++) {
JSONObject json = Company.getJSONObject(i);
// Storing each json item in variable
String id = json.getString(TAG_GID);
String name = json.getString(TAG_NAME);
String jml = json.getString(TAG_EMPLOYEE);
String deskripsi = json.getString(TAG_DESKRIPSI);
String logo = json.getString(TAG_LOGO);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_GID, id);
map.put(TAG_NAME, name);
map.put(TAG_EMPLOYEE, jml);
map.put(TAG_DESKRIPSI, deskripsi);
map.put(TAG_LOGO, logo);
// adding HashList to ArrayList
CompanyList.add(map);
}
} else {
// no CompanyList found
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing data ArrayList
adapter=new LazyAdapter(MainActivity.this, CompanyList);
list.setAdapter(adapter);
pDialog.dismiss();
}
}
I'm just learning about AsyncTask and want to use it as a separate class, rather then a subclass.
For example,
class inetloader extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(urls[0]);
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) {
Log.e("xx",result);
// how do I pass this result back to the thread, that created me?
}
}
and the main(ui) thread:
inetloader il = new inetloader();
il.execute("http://www.google.com");
//il.onResult()
//{
///do something...
//}
Thanks!
Use a interface. Something like:
interface CallBackListener{
public void callback();
}
Then do this in your UI thread:
inetloader il = new inetloader();
li.setListener(this);
il.execute("http://www.google.com");
In inetloader, add:
CallBackListener mListener;
public void setListener(CallBackListener listener){
mListener = listener;
}
then In postExecute(), do:
mListener.callback();
you can pass the activity instance to constructor and call activity function from there...
Like use interface :
public interface ResultUpdatable {
public void setResult(Object obj);
}
Implement this in the Activity and pass in the constructor of Async task and update the result from onPostExecute using setResult function.
inetloader il = new inetloader();
il.execute("http://www.google.com");
String result = il.get();//put it in try-catch
^^^^^^^^
here you get result which is in onPostExecute(String result)