Android: AsyncTask - doesn't seem to run asynchroneously - android

I'm trying to use AsyncTask to make a tas run apart from the main thread, thus prevent locking the thread while the task is running. Have I misunderstood the use for AsyncTask?
The calling code from the main thread:
public void onClick(View view) {
int input = Integer.parseInt(editInput.getText().toString());
String out = "";
try {
out = new RunAsyncTask().execute(Integer.toString(input)).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
From the AsyncTask class:
protected String doInBackground(String... params) {
long start, stop;
long result;
String out = "";
int input = Integer.parseInt(params[0]);
// Dalvik (Java) - Recursive:
start = System.currentTimeMillis();
result = FibLib.fibJR(input);
stop = System.currentTimeMillis();
out += String.format("Dalvik (Java) recursive: %d (%d msec)", result, stop - start);
// Dalvik (Java) - Iterative:
start = System.currentTimeMillis();
result = FibLib.fibJI(input);
stop = System.currentTimeMillis();
out += String.format("\nDalvik (Java) iterative: %d (%d msec)", result, stop - start);
return out
From the FibLib class (which is called by the AsyncTask):
public class FibLib {
public static long fibJR(long n) { //
if (n <= 0) {
return 0;
}
if (n == 1) {
return 1;
}
return fibJR(n - 1) + fibJR(n - 2);
}
// Java implementation - iterative:
public static long fibJI(long n) { //
long previous = -1;
long result = 1;
for (long i = 0; i <= n; i++) {
long sum = result + previous;
previous = result;
result = sum;
}
return result;
}
However, when running this, the main GUI thread is still locked and crashes if the task is more than just a small, quick one. What am I misunderstanding here?

You're calling the AsyncTask's get() method, which really turns an asynchronous call to synchronous, because it waits for the result of the operation. A better way to return the result of the AsyncTask to the calling Activity is to use a callback interface. Create a simple interface, e.g.:
interface OnTaskCompletedListener {
void onTaskCompleted(Object result);
}
Now implement that interface in your Activity class:
public class MainActivity extends Activity implements OnTaskCompletedListener {}
Now you should pass the MainActivity to the AsyncTask object:
AsyncTask task = new RunAsyncTask(onTaskCompletedListener).execute();
And inside the AsyncTask's onPostExecute() you return the result to the listener:
onTaskCompletedListener.onTaskCompleted(result);
Now you can use the result in your Activity's onTaskCompleted() method.
Hope the explanation was clear enough and it will help you.

Related

Edit an array with multiple callbacks and wait until they have all finished

I am replacing my Sqlite database with an online database (Firestore). For that each answer of the database comes back to me by callback.
The problem is that I have several calls to the database in a loop that filled a table and that the table is not accesible unless I declare it in the end and therefore I can not change it.
So I'm looking for a way to fill this table without completely modifying the code that already exists. I saw the ArrayBlockingQueue but I wonder if a simpler solution does not exist.
If possible I would like to keep all the variables inside the function but I have not yet found a solution for that.
I know that for this example we do not necessarily need a table but I want to keep it because it's just an example ;)
Before (SQLite)
public int player_in_x_game(int id_player) {
int gamesWherePlayerIsHere = 0;
ArrayList<Games> gamesArray = Database.getGamesArray();
for (Game game: gamesArray)
if(Utils.isPlayerPresentInGame(game.getId(), idPlayer))
gamesWherePlayerIsHere++;
return gamesWherePlayerIsHere;
}
After (with callbacks)
private static int counter= 0;
private static int resultNP = 0;
private static ArrayBlockingQueue<Integer> results;
public static void numberGamesWherePlayerIsPresent(final long idPlayer, final Callbacks.IntCallback callback){
Thread thread = new Thread() {
#Override
public void run() {
games(new Callbacks.ListGameCallback() {
#Override
public void onCallback(ArrayList<Game> gameArrayList) {
counterNumberGamesWherePlayerIsPresent= gameArrayList.size();
results = new ArrayBlockingQueue<>(gameArrayList.size());
for (Game game: gameArrayList){
Utils.isPlayerPresentInGame(game.getId(), idPlayer, new Callbacks.BooleanCallback() {
#Override
public void onCallback(boolean bool) {
if (bool)
results.add(1);
else
results.add(0);
}
});
}
int result;
try {
while (counter > 0) {
result = results.take();
counter--;
resultNP += result;
}
}catch (InterruptedException ie){
ie.fillInStackTrace();
Log.e(TAG,"results.take() failed");
}
callback.onCallback(resultNP);
}
});
}
};
thread.setName("Firestore - numberGamesWherePlayerIsPresent()");
thread.start();
}

The doInBackground() method in the AsyncTask gets executed only sometimes

I'm using the AsyncTask to render a graph from a list. Sometimes it works alright and the graph is rendered. However in some cases the graph is not being rendered, and the reason for this is that the doInBackground() method is not being triggered. Here's the code of the AsyncTask.
private class HistoryPlotAsync extends AsyncTask<Void, Void, Void> {
boolean isAnalysisMode = false;
List<Byte> listECG;
List<Byte> listHS;
HistoryPlotAsync(List<Byte> listECG, List<Byte> listHS, List<Byte> listMur, boolean isAnalysisMode) {
this.listECG = listECG;
this.listHS = listHS;
this.isAnalysisMode = isAnalysisMode;
HistoryPlot.this.multiHsRenderer.setPanEnabled(false, false);
HistoryPlot.this.multiEcgRenderer.setPanEnabled(false, false);
}
protected Void doInBackground(Void... params) {
if (HistoryPlot.this.pcgPlayer != null) {
HistoryPlot.this.pcgPlayer.start();
} else {
try {
HistoryPlot.this.startSound();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
int i = 0;
int loopCounter = 0;
if (this.listHS != null && this.listHS.size() > 0) {
loopCounter = this.listHS.size();
}
double xValue = 0.0d;
double xValueEcg = 0.0d;
do {
xValueEcg += 0.0015625d;
if (this.listHS != null && i % 2 == 0) {
xValue += 0.0032012d;
hsSeries.add(xValue,listHS.get((i/2)));
}
try {
if (this.listECG != null && i < this.listECG.size()) {
ecgSeries.add(xValueEcg, listECG.get(i));
}
} catch (Exception e) {
try {
Log.d("HistoryPlot -> ", "doInBackground: Exception " + e.getMessage());
} catch (Exception e2) {
Log.e("HistoryPlot -> ", "Error in Analysis mode point conversion");
}
}
if (i > HistoryPlot.this.refRange && i % 94 == 0) {
HistoryPlot.this.xMin = HistoryPlot.this.xMin + 0.15d;
HistoryPlot.this.xMax = HistoryPlot.this.xMax + 0.15d;
HistoryPlot.this.multiHsRenderer.setXAxisMin(HistoryPlot.this.xMin);
HistoryPlot.this.multiHsRenderer.setXAxisMax(HistoryPlot.this.xMax);
HistoryPlot.this.multiEcgRenderer.setXAxisMin(HistoryPlot.this.xMin);
HistoryPlot.this.multiEcgRenderer.setXAxisMax(HistoryPlot.this.xMax);
}
if (i % 16 == 0) {
publishProgress(new Void[0]);
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
i++;
if (i >= loopCounter) {
break;
}
} while (!HistoryPlot.this.taskHistoryPlot.isCancelled());
return null;
}
protected void onProgressUpdate(Void... values) {
HistoryPlot.this.mHsChart.repaint();
HistoryPlot.this.mEcgChart.repaint();
}
protected void onPostExecute(Void result) {
HistoryPlot.this.stopSound();
HistoryPlot.this.enableReplay();
HistoryPlot.this.multiHsRenderer.setPanEnabled(true, true);
HistoryPlot.this.multiEcgRenderer.setPanEnabled(true, true);
}
}
The AsyncTask is executed via the following code in the onCreate() method of the Activity.
protected void onCreate(Bundle savedInstance) {
...
this.taskHistoryPlot = new HistoryPlotAsync((List) mapData.get("fileEcg"), (List) mapData.get("fileHs"), (List) mapData.get("fileMur"), isAnalysisMode);
this.taskHistoryPlot.execute();
}
Instead of using the execute() method, I have also tried using the executeOnExecutor(THREAD_POOL_EXECUTOR) method with the same results.
I got the issue resolved using the following code. The problem was that I had simply tried using the execute() method and the executeOnExecutor() method as is. You need to define an Executor and a Blocking Queue variables and define pool sizes for this to work.
static int mCorePoolSize = 60;
static int mMaximumPoolSize = 80;
static int mKeepAliveTime = 10;
static BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>(mMaximumPoolSize);
static Executor mCustomThreadPoolExecutor = new ThreadPoolExecutor(mCorePoolSize, mMaximumPoolSize, mKeepAliveTime, TimeUnit.SECONDS, workQueue);
this.taskHistoryPlot = new HistoryPlotAsync((List) mapData.get("fileEcg"), (List) mapData.get("fileHs"), (List) mapData.get("fileMur"), isAnalysisMode);
this.taskHistoryPlot.executeOnExecutor(mCustomThreadPoolExecutor);
Asynctask methods will surely run, if you have have call to this class.
Please debug that, the conditions inside doInBackground(), for example
"if (HistoryPlot.this.pcgPlayer != null) "
because it may be possible that condition is not working well, or throws xception and led the function not being called.
If you want that code to execute multiple times, do not use the onCreate function. Create one that you can call everytime you want, onCreate() only runs once in the Activity lifecycle. That can be the cause.
You can call it from the onCreate as well, if you need ;)
Replace these two lines:
this.taskHistoryPlot = new HistoryPlotAsync((List) mapData.get("fileEcg"), (List) mapData.get("fileHs"), (List) mapData.get("fileMur"), isAnalysisMode);
this.taskHistoryPlot.execute();
with:
new HistoryPlotAsync((List) mapData.get("fileEcg"), (List) mapData.get("fileHs"), (List) mapData.get("fileMur"), isAnalysisMode).execute();
You dont need to pass context of activity here "this." will give the context of activity which you dont need it here so apply above mentioned changes.
OnCreate will run it one time only create another method in which you need to run your async task and call that new method wherever you want.You can also call that method in onCreate too.

Android: Main Thread blocked despite using AsyncTask

I have a Activity that contains over 100 complex views (with images, text views etc). Showing up these views is to hard to do it without a Thread that loads the views asynchronously. So I tried to do it with an AsyncTask. I am not sure whether this is the correct way because the "hard staff" is something that HAS to be done in the UI Thread.
Now I've got the problem that the UI freezes though I used the onProgressUpdate for adding the views in the to parent view. I thought that this would result in single loading views that appear successive in the parent view. But this is not the case.
doInBackground fires all publishProgress calls and after that the main thread is blocked (activity frozen, loadbar does not rotate anymore). Is there a way to achieve what I wanted to have? I looked for solutions but alway ended up with ideas of using AsyncTask and no one had to do view-stuff as "hard staff". I am not using "get" in the AsyncTask what seems to be a problem with AsyncTask.
Here is my code for this. If you need any further information please tell me!
Is there any other way to solute this problem? Is my AsyncTask implementation not correct? I am looking for a way to load these complex views asyncronous to the parent view without blocking the main thread.
Thanks in advance!
public class LoadKraut extends AsyncTask<Integer,Kraut,Void> {
private Context context;
private LinearLayout parent;
private HashMap<String,HeadlineAlphabet> headlinesAlphabet = new HashMap<String, HeadlineAlphabet>();
private long time;
private Integer kategorie;
private char letter = 'X';
private int counter = 0;
private ProgressDialog dialog;
public LoadKraut(Context context) {
/**
* Kategorie:
* 1 - A-Z
* 2 - Notiz
* 3 - Favorit
* 4 - Giftig
*/
Log.i("Kraut", "Start thread" + (System.currentTimeMillis()-time) + "ms");
this.context = context;
this.dialog = new ProgressDialog(context);
this.time = System.currentTimeMillis();
}
#Override
protected void onPreExecute() {
dialog.setMessage("Lade Kräuter. Dieser Vorgang kann einen Moment dauern.");
dialog.show();
}
#Override
protected Void doInBackground(Integer... params) {
this.kategorie = params[0];
//Create overview
try {
DatabaseHelper databaseHelper = new DatabaseHelper(context);
Dao<Kraut,Integer> dao = databaseHelper.getKrautDAO();
parent = (LinearLayout) ((Activity) context).findViewById(R.id.ll_conainter_sv_uebersicht_kraeuter);
//setKraeuter(list, linearLayout, giftig)
long test = System.currentTimeMillis();
List<Kraut> list = new ArrayList<>();
switch (kategorie) {
case 1:
list = dao.queryForAll();
break;
case 2:
list = dao.queryBuilder().where().ne("notiz","").query();
break;
case 3:
list = dao.queryBuilder().where().eq("favorit",true).query();
break;
case 4:
list = dao.queryBuilder().where().eq("toedlichBunny",true).query();
break;
}
Log.i("Kraut","Fetching duration: " + String.valueOf(System.currentTimeMillis() - test));
Iterator<Kraut> iterator = list.iterator();
while(iterator.hasNext()) {
Kraut kraut = iterator.next();
Log.i("Kraut","called pp for" + kraut.getName());
publishProgress(kraut);
}
} catch (SQLException e) {
e.printStackTrace();
}
Log.i("Kraut", "End " + (System.currentTimeMillis()-time) + "ms");
return null;
}
#Override
protected void onProgressUpdate(Kraut... value) {
//Set all Krauts and headlines A-Z
long test = System.currentTimeMillis();
Kraut kraut = value[0];
Log.i("Kraut", String.valueOf(counter));
if((kategorie==1 || kategorie==4) && kraut.getName().charAt(0)!=letter) {
letter = kraut.getName().charAt(0);
HeadlineAlphabet letterHeadline = new HeadlineAlphabet(context);
letterHeadline.setText(String.valueOf(kraut.getName().charAt(0)));
headlinesAlphabet.put(String.valueOf(letterHeadline.getText()),letterHeadline);
parent.addView(letterHeadline);
}
KrautView krautView=null;
if(kategorie==1 || kategorie==3) {
krautView = new KrautUebersicht(context,kategorie);
} else if(kategorie==2) {
krautView = new KrautUebersichtNotiz(context);
}
if(krautView!=null) {
krautView.setKraut(kraut);
parent.addView((LinearLayout) krautView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}
parent.getRootView().invalidate();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
counter++;
Log.i("Kraut","Kraut View creation duration: " + String.valueOf(System.currentTimeMillis() - test));
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(kategorie==1) {
//Set Alphabet Column right side
ArrayList<String> anfangsbuchstaben = Kraut.getAnfangsbuchstaben(context);
// Do this with an xml !
for (int i = 1; i <= 26; i++) {
//Log.i("Kraut", String.valueOf(i));
String currentLetter = Helper.getCharForNumber(i);
int id = context.getResources().getIdentifier("tv_"+currentLetter.toLowerCase(),"id",context.getPackageName());
TextView textView = (TextView) ((Activity) context).findViewById(id);
//If no Kraut contains Letter
if (!anfangsbuchstaben.contains(currentLetter)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
textView.setTextColor(context.getResources().getColor(R.color.darkgrey, context.getTheme()));
} else {
textView.setTextColor(context.getResources().getColor(R.color.darkgrey));
}
//Make clickable to jump to A-Z Headlines
} else {
textView.setOnClickListener(new JumpToLetterOnClickListener(headlinesAlphabet));
}
}
}
parent.invalidate();
if(dialog.isShowing()) {
dialog.dismiss();
}
}
}
Note that onProgressView() is called repeatedly as your AsyncTask runs. Therefore, it should be kept as short as possible. This also means that your current code is creating lots of views and adding them to the UI. Instead, you should add the view just once and then update its data in onProgressView().
Also, as Mike M. states in the comments, you should not call Thread.sleep() in onProgressView() since it runs on the UI thread. This is most likely the main reason your app is freezing.

AsyncTask displaying progress bar

I am very new to android. I got two activities A, B . Activity A parse the data from the sever and iterate through the levels. and calls the activity B through intent. Activity B takes some time to display the data so I am trying to display the progress bar. Here is my code.
public class Display extends Activity {
ProgressDialog dialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.attributequestions);
new asynctask().execute();
}
class asynctask extends AsyncTask<Context,Void,Void>{
Survey[] surveyque=null;
// i hace created seperated class forsurvey that has info about data
String list[];
private ProgressDialog Dialog;
#Override
protected void onPreExecute()
{
Dialog=ProgressDialog.show(Display.this, "Parsing Data", "Please wait..........");
}
#Override
protected void onPostExecute(Void unused)
{
try
{
if(Dialog.isShowing())
{
Dialog.dismiss();
}
Intent intent=getIntent();
}
catch(Exception e)
{
Log.d("Onsitev4", "error");
}
}
#Override
protected Void doInBackground(Context... params) {
try {
LinearLayout layout1 = (LinearLayout) findViewById(R.id.linearLayout1);
//getting exception here. I dont understant why
// I have declared layout params and displaying activities in another class
ButtonView c = new ButtonView();
c.layout=layout1;
c.context =getBaseContext();
DbCoreSqlSurveys surveys=new DbCoreSqlSurveys(getBaseContext());
Document doc =surveys.getSurveySet();
surveyquestions= GetSurveyLevels(doc,c );
} catch (TransformerFactoryConfigurationError e) {
e.printStackTrace();
}
return null;
}
}
public SurveyObject[] GetSurveyLevels(Document doc, ButtonView c) {
NodeList nlQuestions = doc.getElementsByTagName("Survey");
SurveyObject[] allsurveys = new SurveyObject[nlQuestions.getLength()];
for (int i = 0; i < nlQuestions.getLength(); i++){
Node survey = nlQuestions.item(i);
String f =survey.getNodeName();
Log.d("OnsiteV4", "survey " + f);
NodeList surveyChildNodes = survey.getChildNodes();
SurveyObject s=new SurveyObject();
for (int j = 0; j < surveyChildNodes.getLength(); j++){
Node surveyChild = surveyChildNodes.item(j);
String h =surveyChild.getNodeName();
Log.d("OnsiteV4", "survey child node = " + h);
if (h !="#text"){
Surveys t = Surveys.valueOf(h);
switch(t){
case KeySurvey:
s.KeySurvey=surveyChild.getTextContent();
displaySurveyLink(s.SurveyDescription,"",c,0,s.SurveyDescription,"","","","");
break;
case SurveyDescription:
s.SurveyDescription=surveyChild.getTextContent();
displaySurveyLink(s.SurveyDescription,"",c,0,s.SurveyDescription,"","","","");
break;
case SurveyUserCode:
s.SurveyUserCode=surveyChild.getTextContent();
break;
case Level1:
if(surveyChild.hasChildNodes()){
s.Level1= processLevel1Nodes(surveyChild,c,s.SurveyDescription);
}
break;
default:
break;
}
}
allsurveys[i]=s;
}
}
return allsurveys;
}
// methods iterating through levels that is not showed
private void displaySurveyLink(final String description, String tag, ButtonView c, int indentation, final String surveyDescription, final String level1description, final String level2description, final String level3description, final String level4description)
{
if (description == null || tag == null){
return;
}
final TextView tv = c.addButton(description,tag,indentation);
tv.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
final Intent intent = new Intent();
intent.setClass(v.getContext(),ActivityB.class);
intent.putExtra("KeyLevel",tv.getTag().toString());
intent.putExtra("SurveyDescription",surveyDescription);
intent.putExtra("level1description",level1description);
intent.putExtra("level2description",level2description);
intent.putExtra("level3description",level3description);
intent.putExtra("level4description",level4description);
intent.putExtra("Description",description);
if (tv.getTag() != null){
if (tv.getTag().toString() != ""){
startActivity(intent);
}
}
}
});
}
}
I am getting exception in doinbackground. I am confused . please help me..
You are getting an exception because you are accessing UI elements on a non-UI thread. The main thread that the application creates is the UI thread, and that's where all of your visual elements are created and therefore the only thread in which you should access them.
To appropriately use AsyncTask, you run your long-running operations in doInBackground, and you use onPreExecute, onPostExecute and onProgressUpdated to work with the UI (show/hide progress dialogs, update views, etc). Whenever I use an AsyncTask and I want to show progress, I override onProgressUpdated giving it parameter type Integer and I call publishProgress from doInBackground. This would require a change of the base class signature from AsyncTask<Context,Void,Void> to AsyncTask<Context,Integer,Void>. You can use other object types for this as well...I just use Integer as an example if you want to show the percentage of the task that is complete, for example.
It's becoz your code should throwing exception as you are doing UI stuff in the doinbackgound of asyc task. Please remove all the UI related work from doingbackgound method.

AsyncTask return value

My android app connects to my website to retrieve and upload information so I use an AsyncTask thread.
In one instance, I need my thread to return a true or a false value to my main thread.
Is there a way to get this return value from an AsyncTask execute function?
When I do the following:
Toast.makeText(Locate.this, "Testing : "+locationUpdate.execute(location), Toast.LENGTH_LONG).show();
I just get alot of gibberish.
I think what I need is a means to pause the main thread until the second thread completes. The second thread calls a function in the main thread to set my return value.
So when the second thread completes, the main thread can unpause and access the return value as set by the second thread
If this logic is sound, please offer suggestions ... thanks!
You can use AsyncTask get() method for this. It waits if necessary for the computation to complete, and then retrieves its result:
Toast.makeText(Locate.this, "Testing : " + locationUpdate.execute(location).get(), Toast.LENGTH_LONG).show();
But be sure to not block the main thread for a long period of time, as this will lead to unresponsive UI and ANR.
UPDATE
I missed the point that question was about async web download/upload. Web/network operation should considered as a long one and thus the approach "pause UI thread and wait till download finishes" is always a wrong one. Use usual result publishing approach intstead (e.g.: AsyncTask.onPostExecute, Service + sendBroadcast, libraries like Volley, RoboSpice, DataDroid etc).
Handler is the best way to do this
in onPostExcecute() method simply do
#Override
protected void onPostExecute(Boolean bool) {
super.onPostExecute(bool);
Message msg=new Message();
msg.obj=bool;
mHandler.sendMessage(msg);
}
}
and your message handler will be
mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
bool i=(String)msg.obj;
}
};
public class RunWebScript {
String mString;
public RunWebScript(String url){
try {
URL updateURL = new URL(url);
URLConnection conn = updateURL.openConnection();
// now read the items returned...
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while((current = bis.read()) != -1){
baf.append((byte)current);
}
String s = new String(baf.toByteArray());
mString = s;
} catch (Exception e) {
Log.e("ANDRO_ASYNC", "exception in callWebPage",e);
mString = "error";
}
}
public String getVal(){
return mString;
}
}
this is executed as... (showing teh end of a method in teh calling class
asyncWebCall (url1,CONSTANT);
}
private void asyncWebCall(String url,int actionPostExecute){
new WebCall().execute(url,String.format("%d",actionPostExecute));
}
The Async part of the business is ... Note the case statement in onPostExecute this is the key to getting the returned value ito your program again. Note that the call new WebCall().execute(url,String.format("%d",actionPostExecute)); is the last thing done in a thread, no further statements can be executed, control returns through the onPostExecute.
class WebCall extends AsyncTask<String, String, String>{
int chooser = -1;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
chooser = Integer.parseInt(params[1]);
} catch(NumberFormatException nfe) {
Log.d("ANDRO_ASYNC",String.format("asyncReturn() mString numberformatexception = %s",params[1]));
chooser = 0;
}
return(new RunWebScript(params[0])).getVal();
}
protected void onProgressUpdate(String... progress) {
}
#Override
protected void onPostExecute(String gotFromDoInBkgnd) {
Log.d("ANDRO_ASYNC",String.format("chooser = %s",chooser));
switch (chooser){
case CONSTANT:
printStringx(gotFromDoInBkgnd);
asyncWebCall(url2,5);
break;
case 0:
Log.d("ANDRO_ASYNC",String.format("case 0 = %s",gotFromDoInBkgnd));
break;
case 5:
Log.d("ANDRO_ASYNC",String.format("case 5 = %s",gotFromDoInBkgnd));
asyncWebCall(url3,7);
break;
default:
Log.d("ANDRO_ASYNC",String.format("man we got problems = %s",gotFromDoInBkgnd));
break;
}
}
} // end of class
Here is a complete example of the issue of returning values from an async task. It may occur that there are many tasks to be done one after the other asynchronously.
Basics.
1. get a return value from a class.
public class Snippet {
int computVal;
public Snippet(){
computVal = 17*32;
}
public int getVal(){
return computVal;
}
}
this is called as...
int hooray = (new Snippet()).getVal();

Categories

Resources