Hi and thanks for your help.
I have a method that calls an AsyncTask to retrieve some data from the net.
The method is called several times in sequence and therefore launches several AsyncTasks.
From each launch of the method I need to get back the correct result from the relative AsyncTask (and not from some other AsyncTask which was called before or after).
Any help very much appreciated.
EDIT EDIT EDIT EDIT
Added rest of code.
Please Note: the whole process runs inside a Service.
public static class UpdateService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
int[] appWidgetIds = intent.getIntArrayExtra("widgetsids");
final int N = appWidgetIds.length;
AppWidgetManager manager = AppWidgetManager.getInstance(this);
for (int i = 0; i < N; i++) {
int appWidgetId = appWidgetIds[i];
Log.e("","i="+Integer.toString(i)+ " di "+Integer.toString(N));
RemoteViews view = buildUpdate(getApplicationContext(),
appWidgetIds);
manager.updateAppWidget(appWidgetId, view);
}
return (START_NOT_STICKY);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
private static RemoteViews buildUpdate(Context ctxt, int[] appWidgetIds) {
RemoteViews updateViews = new RemoteViews(ctxt.getPackageName(),
R.layout.widget);
updateViews.setTextViewText(R.id.price1, getPrice(list.get(0)
.getSymbol()));
}
//THIS METHOD IS CALLED SEVERAL TIMES IN SEQUENCE <----
private static String getPrice(String symbol) {
String result="";
UpdateTaskPrice up = new UpdateTaskPrice();
up.execute(symbol, null, null);
//HERE I WANT THE RESULT FROM onPostExecute() <----
return result;
}
//THIS IS THE ASYNCTASK WHICH IS LAUNCHED SEVERAL TIMES
public class UpdateTaskPrice extends AsyncTask<String, Void, String> {
#Override
protected void onProgressUpdate(Void... progress) {
}
#Override
protected void onPostExecute(String result) {
//HERE I RECEIVE THE RESULT FROM doInBackground <----
//I NEED TO PASS IT BACK TO getPrice() <----
}
#Override
protected String doInBackground(String... symbol) {
String result = "";
DefaultHttpClient client = new DefaultHttpClient();
String srt = "";
String url = context.getString(R.string.urlaternativo).concat(
symbol[0]);
HttpGet getMethod = new HttpGet(url);
try {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
srt = client.execute(getMethod, responseHandler);
int inizio = srt.indexOf("<last data=\"");
int fine = srt.indexOf("\"/>", inizio + 12);
result = srt.substring(inizio + 12, fine);
} catch (Throwable t) {
// Log.e("ERROR", "ERROR", t);
}
//HERE I GET THE RESULT I WANT, AND PASS IT TO onPostExecute() <----
return result;
}
}
AsyncTask is asynchronous and run in a separate thread. So it is not possible to get the result of AsyncTask in very next statement after you execute it.
To get the relative results from AsyncTask, add a member variable "mRequestId" in your UpdateTaskPrice class and before calling UpdateTaskPrice.execute, set unique request ID.
in "onPostExecute" method of your UpdateTaskPrice class, you can return and process result using this Request Id.
public class UpdateTaskPrice extends AsyncTask<String, Void, String> {
protected int mRequestId;
public void setRequestId (int requestId)
{
this.mRequestId = requestId;
}
#Override
protected void onProgressUpdate(Void... progress) {
}
#Override
protected void onPostExecute(String result) {
// do whatever with result using mRequestId
}
#Override
protected String doInBackground(String... symbol) {
String result = "";
DefaultHttpClient client = new DefaultHttpClient();
String srt = "";
String url = context.getString(R.string.urlaternativo).concat(
symbol[0]);
HttpGet getMethod = new HttpGet(url);
try {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
srt = client.execute(getMethod, responseHandler);
int inizio = srt.indexOf("<last data=\"");
int fine = srt.indexOf("\"/>", inizio + 12);
result = srt.substring(inizio + 12, fine);
} catch (Throwable t) {
// Log.e("ERROR", "ERROR", t);
}
//HERE I GET THE RESULT I WANT, AND PASS IT TO onPostExecute() <----
return result;
}
}
You can get the data from multiple asynctask, but the place you want the result is not possible
with the asyctask, you need to use more encapsulation to structure this problem.
the problem with your structure is...
private static String getPrice(String symbol) {
String result="";
UpdateTaskPrice up = new UpdateTaskPrice();
up.execute(symbol, null, null);
//HERE I WANT THE RESULT FROM onPostExecute() <----
return result;
}
when you are starting the new thread it will first execute the statement which is return after task.execute(symbol); in your case it is return statement and then it will exucute pre.. doin.. and post...
Hear is the pattern which you can use to retrieve the data from multiple AsycTask
//Calling to the method callAsyncTask;
callAsyncTask(new AsyncResultCallback(){
public void onResult(String result, String symbol){
//TODO dosomthing with the result
}
});
public void callAsyncTask(AsyncResultCallback callback){
new UpdateTaskPrice(callback).execurte(symbol);
}
public interface AsyncResultCallback{
public void onResult(String result, String symbol);
}
public class UpdateTaskPrice extends AsyncTask<String, Void, String> {
AsyncResultCallback callback;
String symbol;
UpdateTaskPrice(AsyncResultCallback callback){
this.callback = callback;
}
#Override
protected void onProgressUpdate(Void... progress) {
}
#Override
protected void onPostExecute(String result) {
callback.onResult(result, symbol);
}
#Override
protected String doInBackground(String... symbol) {
this.symbol = symbol;
String result = "";
DefaultHttpClient client = new DefaultHttpClient();
String srt = "";
String url = context.getString(R.string.urlaternativo).concat(symbol[0]);
HttpGet getMethod = new HttpGet(url);
try {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
srt = client.execute(getMethod, responseHandler);
int inizio = srt.indexOf("<last data=\"");
int fine = srt.indexOf("\"/>", inizio + 12);
result = srt.substring(inizio + 12, fine);
} catch (Throwable t) {
// Log.e("ERROR", "ERROR", t);
}
//HERE I GET THE RESULT I WANT, AND PASS IT TO onPostExecute() <----
return result;
}
}
hope that help.
Well, I think you can pass the unique request id in the constructor of the AsyncTask. Then in the postExecute() method, update the UI with the result and the unique request id -
public class UpdateTaskPrice extends AsyncTask<String, Void, String> {
private int mIdentifier;
private Service mService;
public UpdateTaskPrice(Service service, int identifier) {
this.mIdentifier = identifier;
}
#Override
protected void onProgressUpdate(Void... progress) {
}
#Override
protected void onPostExecute(String result) {
((UpdateService) mService).informPrice(mIdentifier, result);
}
#Override
protected String doInBackground(String... symbol) {
String result = "";
DefaultHttpClient client = new DefaultHttpClient();
String srt = "";
String url = context.getString(R.string.urlaternativo).concat(
symbol[0]);
HttpGet getMethod = new HttpGet(url);
try {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
srt = client.execute(getMethod, responseHandler);
int inizio = srt.indexOf("<last data=\"");
int fine = srt.indexOf("\"/>", inizio + 12);
result = srt.substring(inizio + 12, fine);
} catch (Throwable t) {
// Log.e("ERROR", "ERROR", t);
}
//HERE I GET THE RESULT I WANT, AND PASS IT TO onPostExecute() <----
return result;
}
}
Related
My scenario is i have 5 threads parallel call to happen in splash activity but i need to wait for one specific thread( which is DashBoardCallable) exectuion so that i can load dashboard data, show the splash screen untill dashboard data gets loaded and once dashboard data get loaded change the activity meanwhile in parallel i load some more data related to that user in background(which is thread util class will do ).
or you can understand this way i have a ExecutorService of 5 threads for parallel calls and Splashscreen is based on one thread execution out of 5. Once this thread execution is done change the activity leaving rest other thread execution in background.
below is splash activity code :
ExecutorService executor = Executors.newFixedThreadPool(5);
SharedPreferences sharedpreferences = getSharedPreferences(getResources().getString(R.string.mypreference_key), Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = sharedpreferences.edit();
ThreadUtil datatype1 = new ThreadUtil(editor,3504,"URL","DATATYPE1","DATATYPE1");
ThreadUtil datatype2 = new ThreadUtil(editor,3504,"URL","DATATYPE2","DATATYPE2");
ThreadUtil datatype3 = new ThreadUtil(editor,3504,"URL","DATATYPE3","DATATYPE3");
ThreadUtil datatype4 = new ThreadUtil(editor,3504,"Different URL","DATATYPE1","DATATYPE1");
DashBoardCallable dashBoardCallable = new DashBoardCallable(SplashScreenActivity.this,3504);
FutureTask<String> dashboardFuture = new FutureTask<String>(dashBoardCallable);
executor.execute(datatype1);
executor.execute(datatype2);
executor.execute(datatype3);
executor.execute(datatype4);
executor.execute(dashboardFuture);
String response =dashboardFuture.get();
This is dashboaord callable :
public class DashBoardCallable implements Callable<String> {
private Context context;
private int user_id;
public DashBoardCallable(Context context,int user_id){
this.context = context;
this.user_id = user_id;
}
#Override
public String call() throws Exception {
HttpUtil httpUtil = new HttpUtil();
httpUtil.setUrl("URL");
httpUtil.setType("GET");
return httpUtil.getStringResponse();
}
}
this is threadUtil class:
public class ThreadUtil implements Runnable {
private int user_id;
private String url,type,stored_name;
private SharedPreferences.Editor editor;
public ThreadUtil( SharedPreferences.Editor editor, int user_id, String url, String type,String stored_name){
this.editor = editor;
this.user_id = user_id;
this.url = url;
this.type = type;
this.stored_name = stored_name;
}
#Override
public void run() {
HttpUtil httpUtil = new HttpUtil();
httpUtil.setUrl(url);
httpUtil.setType("GET");
String jsonresponse =httpUtil.getStringResponse();
Gson gson = new Gson();
switch (type){
case "DATATYPE1":
saveDATATYPE1(jsonresponse,gson,editor);
break;
case "DATATYPE2":
saveDATATYPE2(jsonresponse,gson,editor);
break;
case "DATATYPE3":
saveDATATYPE3(jsonresponse,gson,editor);
break;
}
}
private void saveDATATYPE1(String jsonresponse, Gson gson,SharedPreferences.Editor editor) {
if(!jsonresponse.equalsIgnoreCase("null")){
editor.putString(stored_name, jsonresponse);
editor.apply();
editor.commit();
}
}
private void saveDATATYPE2(String jsonresponse, Gson gson, SharedPreferences.Editor editor) {
try {
Type listType = new TypeToken<List<AssessmentPOJO>>() {}.getType();
ArrayList<AssessmentPOJO> dashboardCards = (ArrayList<AssessmentPOJO>) gson.fromJson(jsonresponse, listType);
for(AssessmentPOJO assessmentPOJO:dashboardCards){
System.out.println("XXBBXBXBXBXB -> "+assessmentPOJO.getName());
if(assessmentPOJO != null){
editor.putString(stored_name+assessmentPOJO.getId(), gson.toJson(assessmentPOJO));
editor.apply();
editor.commit();
}
}
}catch (JsonSyntaxException jse){
jse.printStackTrace();
}catch (Exception e){
}
}
private void saveDATATYPE3(String jsonresponse, Gson gson,SharedPreferences.Editor editor) {
if(!jsonresponse.equalsIgnoreCase("null")) {
Type listType = new TypeToken<List<CoursePOJO>>() {}.getType();
ArrayList<CoursePOJO> coursePOJOs = (ArrayList<CoursePOJO>)gson.fromJson(jsonresponse, listType);
for(CoursePOJO coursePOJO:coursePOJOs){
if(coursePOJO != null){
editor.putString(stored_name+coursePOJO.getId(), gson.toJson(coursePOJO));
editor.apply();
editor.commit();
}
}
}
}
}
this is HttpUtil class:
public class HttpUtil {
private String url;
private String type;
private HashMap<String,String> param;
private String postrequest;
public HttpUtil(){}
private int socketTimeOut=0, connectionTimeOut=0;
public HttpUtil(String url, String type, HashMap<String, String> param,String postrequest) {
this.url = url;
this.type = type;
this.param = param;
this.postrequest = postrequest;
}
public String getStringResponse(){
String jsonresponse="";
try {
System.out.println("url "+url);
System.out.println("type "+type);
HttpResponse httpResponse = getHttpResponse();
if (httpResponse != null && httpResponse.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
HttpEntity httpEntity = httpResponse.getEntity();
jsonresponse = EntityUtils.toString(httpEntity);
if(jsonresponse.equalsIgnoreCase("[]")){
jsonresponse="";
}
System.out.println("HttpUtil Response is .... " + jsonresponse);
} else {
return "null";
}
} catch (IOException e) {
e.printStackTrace();
}
return jsonresponse;
}
public void getVoidResponse(){
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public HashMap<String, String> getParam() {
return param;
}
public void setParam(HashMap<String, String> param) {
this.param = param;
}
private HttpResponse getHttpResponse(){
HttpResponse httpResponse = null;
HttpClient httpclient = new DefaultHttpClient();
try{
switch(type){
case "GET":
if(socketTimeOut != 0 && connectionTimeOut != 0){
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, connectionTimeOut);
HttpConnectionParams.setSoTimeout(httpParameters, socketTimeOut);
httpclient = new DefaultHttpClient(httpParameters);
}
httpResponse = httpclient.execute(new HttpGet(url));
break;
case "POST":
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
if(param != null) {
for (String key : param.keySet()) {
nameValuePairs.add(new BasicNameValuePair(key, param.get(key)));
}
}
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpResponse = httpclient.execute(httpPost);
break;
case "PUT":
HttpPut httpPut = new HttpPut(url);
if(postrequest != null){
StringEntity se = new StringEntity(postrequest);
se.setContentType("application/json;charset=UTF-8");//text/plain;charset=UTF-8
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
httpPut.setEntity(se);
httpPut.setHeader("Accept", "application/json");
httpPut.setHeader("Content-type", "application/json");
}
httpResponse = httpclient.execute(httpPut);
break;
default:
httpResponse = httpclient.execute(new HttpGet(url));
break;
} }catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}catch (JsonSyntaxException jse) {
jse.printStackTrace();
return null;
}catch (Exception e){
e.printStackTrace();
return null;
}
return httpResponse;
}
public String getPostrequest() {
return postrequest;
}
public void setPostrequest(String postrequest) {
this.postrequest = postrequest;
}
public int getSocketTimeOut() {
return socketTimeOut;
}
public void setSocketTimeOut(int socketTimeOut) {
this.socketTimeOut = socketTimeOut;
}
public int getConnectionTimeOut() {
return connectionTimeOut;
}
public void setConnectionTimeOut(int connectionTimeOut) {
this.connectionTimeOut = connectionTimeOut;
}
}
Based on the use of your threads I can tell you should be better to use AsyncTask.
Every AsyncTask must have a Callback and the Activity implement them so, after the task was completed, the Activity can keep control of the operations and take decisions.
For the tasks:
public class SplashScreenTask extends AsyncTask<Void, Void, Void> {
private Context context;
private SplashScreenTaskCallback listener = null;
public SplashScreenTask (Context context) {
this.context = context;
}
#Override
protected Void doInBackground (Void... params) {
// Do your tasks
return null;
}
#Override
public void onPreExecute () {
}
#Override
public void onPostExecute (Void v) {
if (listener != null) {
listener.OnSplashScreenTaskCompleted ();
}
}
public void setListener (SplashScreenTaskCallback listener) {
this.listener = listener;
}
public interface SplashScreenTaskCallback {
void OnSplashScreenTaskCompleted ();
}
}
And your activity:
public class SplashScreenActivity extends Activity implements SplashScreenTask.SplashScreenTaskCallback {
protected Runnable postDelayedAction;
private final Handler handler = new Handler();
#Override
public void onCreate (Bundle savedInstanceState) {
Log.d(TAG, "onCreate");
super.onCreate(savedInstanceState);
handler.postDelayed(startBackgroundTasks, splashScreenDelay);
}
private Runnable startBackgroundTasks = new Runnable() {
#Override
public void run () {
// Do initial background tasks like sounds load
SplashScreenTask task = new SplashScreenTask (SplashScreenActivity.this);
task.setListener (SplashScreenActivity.this);
task.execute ();
}
};
#Override
public void OnSplashScreenTaskCompleted () {
// Here you take decisions
}
}
I would use the Rx zip operator to determine when all of your backgrounds tasks have completed. Determining the completion of multiple parallel jobs is a huge headache with the Android framework.
There is a best practice for showing a splash screen with no initial delay wherein you set the background drawable using themes. In order to do that and transition into your Activity (not your splash screen) where you can actually fire off all of this logic, simply duplicate the visuals of your splash screen in your Activity, and transition out of showing those visuals once your jobs have completed.
I am uploading an image on server by using async task and in the end I want to return value of uploaded file url. How can I do that
I am calling asynctask as
new Config.UploadFileToServer(loginUserInfoId, uploadedFileURL).execute();
and my asynctask function is as:
public static final class UploadFileToServer extends AsyncTask<Void, Integer, String> {
String loginUserInfoId = "";
String filePath = "";
long totalSize = 0;
public UploadFileToServer(String userInfoId, String url){
loginUserInfoId = userInfoId;
filePath = url;
}
#Override
protected void onPreExecute() {
// setting progress bar to zero
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
// updating progress bar value
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.HOST_NAME + "/AndroidApp/AddMessageFile/"+loginUserInfoId);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(filePath);
// Adding file data to http body
entity.addPart("file", new FileBody(sourceFile));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
responseString = responseString.replace("\"","");
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
Try my code as given below.
public Result CallServer(String params)
{
try
{
MainAynscTask task = new MainAynscTask();
task.execute(params);
Result aResultM = task.get(); //Add this
}
catch(Exception ex)
{
ex.printStackTrace();
}
return aResultM;//Need to get back the result
}
You've almost got it, you should do only one step. As I can see, you are returning the result at the doInBackground method (as a result of calling uploadFile). Now, this value is passed to the onPostExecute method, which is executed on the main thread. In its body you should notify components, which are waiting for result, that result is arrived. There are a lot of methods to do it, but if you don't want to used 3rd party libs, the simplest one should be to inject listener at the AsyncTask constructor and call it at the onPostExecute. For example, you can declare the following interface:
public interface MyListener {
void onDataArrived(String data);
}
And inject an instance implementing it at the AsyncTask constructor:
public UploadFileToServer(String userInfoId, String url, MyListener listener){
loginUserInfoId = userInfoId;
filePath = url;
mListener = listener;
}
Now, you can simply use it at the onPostExecute:
#Override
protected void onPostExecute(String result) {
listener.onDataArrived(result);
super.onPostExecute(result); //actually `onPostExecute` in base class does nothing, so this line can be removed safely
}
If you are looking for a more complex solutions, you can start from reading this article.
I am facing an issue in Async task, can anyone please suggest me any solution.
I have downloaded this example from this link :
Source
My Current Structure is
Main Class extends MyTask and implements AsyncTaskCompleteListener interface.
AsyncTaskCompleteListener is an Interface contains the onTaskComplete Method .
MyTask extends Async Task and onPostExcute contains CallBackMethod which will return the result-set got from the doInBackground.
Http Class(Utils) contains the Http connection and returns the Result-set to AsyncTaskComleteListner from PostExecute.
I am trying to get my result-set Value in the main class from the interface method to perform my further operation.
I tried to get the value from static variables, static method but non of them worked, and also tried with creating a new class object to send and receive the result but every time it gives me NullPointerException . Because the statement written after the AsyncTask gets executes before getting the result.
I have also tried to get the Status of asyncTask from its method getStaus(), but it returns only Running and dose not notify when the task is completed or finished.
Here is the code sample:
Main Class Code :
package com.example.androidasynctask;
public class MainActivity extends Activity implements AsyncTaskCompleteListener {
public static String[] asyncResult;
String res[] = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void btnclick(View view) {
/*MyTask asyncTask = new MyTask(this);
String [] asyncTaskResult = asyncTask.execute("fetchCategory.php","1%Id%1");*/
//AsyncTask<String, Void, String[]> asyncTaskRes = new MyTask(this).execute("fetchCategory.php","1%Id%1");
//new MyTask(this).execute("fetchCategory.php","1%Id%1");
MyTask asyncTask = (MyTask) new MyTask(this).execute("fetchCategory.php","1%Id%1");
if(asyncTask.getStatus().equals(AsyncTask.Status.FINISHED) || asyncTask.getStatus().equals(AsyncTask.Status.PENDING)) {
asyncTask.execute();
}
else {
Log.v("In Else","Get Value");
}
}
#Override
public void onTaskComplete(String[] result) {
Log.v("IN ON TASK COMPLETE","VALUE = "+result[1]);
}
/*#Override
public void onTaskComplete(String result) {
System.out.println("calling onTaskComplete SIMPLE....");
System.out.println("result :: "+ result);
}*/
public static class GetAsyncResult
{
static String[] returnValues;
public GetAsyncResult()
{}
public GetAsyncResult(String[] res)
{
returnValues = res;
Log.v("getResultSetValues","returnValues"+returnValues[1]);
}
public void getResultSetValues()
{
Log.v("getResultSetValues","returnValues"+returnValues[1]);
}
}
}
Async Task Code :
public class MyTask extends AsyncTask<String, Void, String[]> {
private Activity activity;
private ProgressDialog dialog;
private AsyncTaskCompleteListener callback;
public String[] asyncResultSetValue = null;
public MyTask(Activity act) {
Log.v("MY TASK","ACTIVITY"+act);
this.activity = act;
this.callback = (AsyncTaskCompleteListener)act;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.v("MY TASK","in ON PRE EXECUTE");
dialog = new ProgressDialog(activity);
dialog.setMessage("Loading...");
dialog.show();
}
#Override
protected String[] doInBackground(String... params) {
Log.v("MY TASK","DO IN BACKGROUND");
Log.v("PARAMS"," params[0] = "+params[0]+ "| params[1]"+params[1]);
asyncResultSetValue = Utils.process_query(params[0],params[1]);
return asyncResultSetValue;
}
#Override
protected void onPostExecute(String[] result) {
super.onPostExecute(result);
Log.v("MY TASK","in ON POST EXECUTE");
if (null != dialog && dialog.isShowing()) {
dialog.dismiss();
}
callback.onTaskComplete(result);
}
}
HTTP CLASS CODE :
public class Utils {
static String result = null;
String endResult;
static java.io.InputStream is = null;
static StringBuilder sb=null;
static String delimiter = "\\|";
static String delimiter1 = "\\%";
static String[] temp = null;
static String[] temp1 = null;
static ArrayList<NameValuePair> nameValuePairs;
static Context context;
static ProgressDialog mDialog;
static HttpResponse response;
static String[] resultset_value = null;
//static String url = "http://fortuneworkinprogress.in/News_App/"; //Global URL
static String url = "http://10.0.2.2/News_App/"; //Global URL
static String query_type,parameter;
/*************** PROCESS QUERY START ***************/
public static String[] process_query(String str_url, String parameter) {
// String strval = select_parameter;
String ret_val[] = null;
String get_sel_val[] = null;
int loopcount =0;
url = url+str_url; //!!!! ######### CONCATINATING AND CREATING FULL URL ######## !!!!!!//
Log.v("PROCESS QUERY PARAMETER","URL = "+url+" | PARAMTER = "+parameter);
nameValuePairs = new ArrayList<NameValuePair>();
//Log.i("STR VAL",""+strval); //To Check which values are recieved
try
{
String strval = parameter;
get_sel_val=strval.split(delimiter1);
for(int i =0; i < get_sel_val.length ; i++)
{
loopcount = Integer.parseInt(get_sel_val[0]); // First Delimeted Value which tells the number of count
Log.i("Loopcount","cnt = "+loopcount);
}
for(int j=1;j<=(loopcount*2);j=j+2) //For Loop for making Name Values Pares Dynamic
{
nameValuePairs.add(new BasicNameValuePair(get_sel_val[j],get_sel_val[j+1]));
//Log.i("J = ["+j+"]","pairvalue1 = "+get_sel_val[j]+"pairvalue2 ="+get_sel_val[j+1]);
}
}
catch(Exception e)
{
Log.w("Exception in the getting value","Exp = "+e);
}
//nameValuePairs.add(new BasicNameValuePair("id","1"));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
Log.v("CONNECT URL ","Final url "+url);
Log.w("CONNECTION STATUS ",httppost.toString());
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.w("PAERSE VALUE ",nameValuePairs.toString());
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.w("1", "Connection establised succesfuly");
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection"+e.toString());
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
Log.v("SB VALUE = ","sb = "+sb.toString());
String line="0";
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result=sb.toString();
// Toast.makeText(getBaseContext(), result ,Toast.LENGTH_LONG).show();
Log.w("result", result);
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
Toast.makeText(null, "error converting response to string" ,Toast.LENGTH_LONG).show();
}
String[] temp = null;
String[] tempResult = null;
if(result!=null)
{
tempResult = result.split(delimiter); //Split the entire return string into "rows"
for(int i =0; i < tempResult.length-1 ; i++)
{
temp = null;
temp = tempResult[i].split(delimiter1); //Find columns for each row
ret_val = temp;
resultset_value=ret_val;
}
}
else
{
Toast.makeText(null, "Cannot Find Routes" ,Toast.LENGTH_LONG).show();
}
Log.v("BEFORE RETUNR = ","ret_val = "+ret_val.toString());
return ret_val; //Returning the result value array
}
/*************** PROCESS QUERY ENDS ***************/
public static boolean isNetworkAvailable(Activity activity)
{
ConnectivityManager connectivity = (ConnectivityManager) activity
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null)
{
return false;
}
else
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
{
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
}
}
return false;
}
}
Thanks in advance.
Because the statement written after the AsyncTask gets executes before getting the result.
the reason is AsyncTask runs on separate thread,not on your Main(UI) thread.
MyTask extends Async Task and onPostExcute contains CallBackMethod which will return the result-set got from the doInBackground.
you will be getting result values on this method
#Override
public void onTaskComplete(String[] result) {
Log.v("IN ON TASK COMPLETE","VALUE = "+result[1]);
}
Comment following piece of code,
if(asyncTask.getStatus().equals(AsyncTask.Status.FINISHED) || asyncTask.getStatus().equals(AsyncTask.Status.PENDING)) {
asyncTask.execute();
}
else {
Log.v("In Else","Get Value");
}
Make change,
public static String[] asyncResult; to public String[] asyncResult = null;
Change following,
asyncResultSetValue = Utils.process_query(params[0],params[1]); to asyncResult = Utils.process_query(params[0],params[1]);
and return asyncResultSetValue; to return asyncResult ;
look at value by adding one more log,you will be getting result values on this method
#Override
public void onTaskComplete(String[] result) {
Log.v("IN ON TASK COMPLETE","VALUE = "+result[1]);
Log.v("IN ON TASK COMPLETE","VALUE = "+asyncResult[1]);
}
I am running into a problem. I need to use asynctask to retrieve JSON data and I need that data before I moved to the next part of the program. However, when using the get() method of AsyncTask I have 5 to 8 sec black screen before I see the data is displayed. I would like to display a progress dialog during the data retrieval but I cannot do this due to the black screen. Is there a way to put into another thread? here is some code
AsyncTask
public class DataResponse extends AsyncTask<String, Integer, Data> {
AdverData delegate;
Data datas= new Data();
Reader reader;
Context myContext;
ProgressDialog dialog;
String temp1;
public DataResponse(Context appcontext) {
myContext=appcontext;
}
#Override
protected void onPreExecute()
{
dialog= new ProgressDialog(myContext);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCancelable(false);
dialog.setMessage("Retrieving...");
dialog.show();
};
#Override
protected Data doInBackground(String... params) {
temp1=params[0];
try
{
InputStream source = retrieveStream(temp1);
reader = new InputStreamReader(source);
}
catch (Exception e)
{
e.printStackTrace();
}
Gson gson= new Gson();
datas= gson.fromJson(reader, Data.class);
return datas;
}
#Override
protected void onPostExecute(Data data)
{
if(dialog.isShowing())
{
dialog.dismiss();
}
}
private InputStream retrieveStream(String url) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(url);
try {
HttpResponse getResponse = client.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w(getClass().getSimpleName(),
"Error " + statusCode + " for URL " + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
return getResponseEntity.getContent();
}
catch (IOException e) {
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
}
return null;
}
}
DisplayInfo
public class DisplayInfo extends Activity implements AdverData {
public static Data data;
public ProjectedData attup;
public ProjectedData attdown;
public ProjectedData sprintup;
public ProjectedData sprintdown;
public ProjectedData verizionup;
public ProjectedData veriziondown;
public ProjectedData tmobileup;
public ProjectedData tmobiledown;
public ProjectedAll transfer;
private ProgressDialog dialog;
public DataResponse dataR;
Intent myIntent; // gets the previously created intent
double x; // will return "x"
double y; // will return "y"
int spatial; // will return "spatial"
//public static Context appContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
dialog= new ProgressDialog(DisplayInfo.this);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCancelable(false);
dialog.setMessage("Retrieving...");
dialog.show();
myIntent= getIntent(); // gets the previously created intent
x = myIntent.getDoubleExtra("x",0); // will return "x"
y = myIntent.getDoubleExtra("y", 0); // will return "y"
spatial= myIntent.getIntExtra("spatial", 0); // will return "spatial"
String URL = "Some URL"
dataR=new DataResponse().execute(attUp).get();
#Override
public void onStart()
{more code}
When you are using get, using Async Task doesn't make any sense. Because get() will block the UI Thread, Thats why are facing 3 to 5 secs of blank screen as you have mentioned above.
Don't use get() instead use AsyncTask with Call Back check this AsyncTask with callback interface
I'm working on one project and I need to call one AsyncTask, but the onPostExecute method is not called.
This is my class:
public class WebService extends AsyncTask<String, String, String> {
private ArrayList<SimpleObserver> listeners;
private int responseCode;
private String message;
private String response;
private String URL;
public WebService() {
listeners = new ArrayList<SimpleObserver>();
}
public void addListener(SimpleObserver obs) {
listeners.add(obs);
}
public void removeListener(SimpleObserver obs) {
listeners.remove(obs);
}
public void notifyListener(String s) {
for (SimpleObserver listener : listeners)
listener.onChange(s);
}
public String getResponse() {
return response;
}
public String getErrorMessage() {
return message;
}
public int getResponseCode() {
return responseCode;
}
#Override
protected void onPreExecute() {
//notifyListener("A calcular");
}
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
HttpParams my_httpParams = new BasicHttpParams();
final String proxyHost = android.net.Proxy.getDefaultHost();
final int proxyPort = android.net.Proxy.getDefaultPort();
if(proxyPort != -1)
{
my_httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, proxyPort));
}
DefaultHttpClient client = new DefaultHttpClient(my_httpParams);
HttpGet httpGet = new HttpGet(url);
Log.d("URL serviço 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;
}
Log.d("RESPOSTA do web service", response);
} catch (Exception e) {
e.printStackTrace();
response = e.getMessage();
Log.e("ERRO de respota", e.getMessage());
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
Log.d("onPostExecute Serviço", result);
notifyListener(result);
}
}
I have created this method:
public void executeService(String param) {
try {
Log.d("Entrar", "no serviço");
s.execute(new String [] {URL+param});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Erro ao aceder ao web service", e.getMessage());
}
}
to call the task.
these are the results of Log
08-28 17:47:21.936: D/URL serviço HttpGet(2055): http://192.168.56.1:8080/pt.Agile21.Acerola.WebService/rest/acerola?id=g;ana#eu.com
08-28 17:47:22.456: D/RESPOSTA do web service(2055): ana;ana#eu.com;pass;0
08-28 17:47:22.456: D/RESPOSTA do web service(2055): ana;ana#eu.com;pass;0
As you can see I have all the results of doInBackground(). :S
Someone can help me to understand which is the problem?
Something that I saw now looking for the Log files.. my onPostExeute method returns when I finish my app on purpose.. it is not normal.. :S can someone help me?