I can't resolve this error. Please help me. I have this two methods:
public boolean isEmailValid(String email) {
boolean flag;
CharSequence inputStr = email.trim();
Pattern pattern = Pattern.compile(EXPRESSION,
Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches())
flag = true;
else {
flag = false;
}
return flag;
}
public boolean isFieldsEmpty(String login, String mdp) {
Boolean result = true;
if (login.equals("") || mdp.equals("")) {
result = true;
} else {
result = false;
}
return result;
}
class LoginUser extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute(){
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
prefs = getSharedPreferences("PFE_Prefs",MODE_PRIVATE);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressBar.setVisibility(View.GONE);
switch (s) {
case "Champs_vides":
Toast.makeText(getApplicationContext(), "Merci de bien vouloir remplir tous les champs, svp", Toast.LENGTH_SHORT).show();
EmailEditText.setText("");
MdpEditText.setText("");
break;
case "Email_incorrect":
Toast.makeText(getApplicationContext(),"Merci de bien vouloir verifier votre adresse email, svp", Toast.LENGTH_SHORT ).show();
EmailEditText.setText("");
MdpEditText.setText("");
break;
case "Success": //Appel a l'activité Tableau de bord
Intent toDashBord = new Intent(getApplicationContext(), DashBoardActivity.class);
startActivity(toDashBord);
LoginActivity.this.finish();
break;
case "Echoué" :
Toast.makeText(getApplicationContext(),"Merci de bien vouloir verifier votre connexion, svp", Toast.LENGTH_SHORT ).show();
EmailEditText.setText("");
MdpEditText.setText("");
break;
}
}
And in the method doInBackground:
protected String doInBackground(String... params) {
int success = 0;
String result = "";
JSONObject json ;
WebCalls webCalls = new WebCalls();
JSONObject jsonUser;
User tempUser ;
if (isFieldsEmpty(EmailEditText.getText().toString(),MdpEditText.getText().toString())){
result = "Empty_Field";
return result ;
}else if (!isEmailValid(EmailEditText.getText().toString().trim())){
result = "Wrong_mail";
return result ;
}
return null;
}
My problem is in EmailEditText.getText().toString(), I'm getting the following error:
Method getText() must called from UI thread, currently inferred thread is worker
Call all your getText() functions in onCreate or somewhere before AsyncTask and assign the return values to the public values. So you can reach them.
public String MyeMail;
public String MyMDP;
onCreate()...
{
MyeMail= EmailEditText.getText().toString();
MyMDP = MdpEditText.getText().toString()
.
.
.
}
It doesn't have to be in onCreate but it must be after the user entered the EditText fields. You can do these after a button click maybe. Anyways, now in your AsyncTask's doInBackground:
doInBackground...
{
if (isFieldsEmpty(MyeMail,)) {
result = "Empty_Field";
return result ;
.
.
.
}
So hope it helps! Let me know if it works.
getText() must be called on the main application thread. doInBackground() is being called on a background thread.
Get the values out of the EditText and provide them to the AsyncTask (e.g., via a constructor) before executing the task.
AsyncTask's doInBackground() always runs in a non-UI worker thread which means that you cannot access UI elements like EditText,TextView in doInBackground(). SO, if you want to access these in doInBackground(), then you can either pass those in your AsyncTask's constructor and use them or the best approach would be to pass EmailEditText.getText().toString() and MdpEditText.getText().toString() as params in the execute() method of AsyncTask.
So, let's say if your AsyncTask name is "ProcessTask", then while you start your AsyncTask, write this :
new ProcessTask().execute(EmailEditText.getText().toString(), MdpEditText.getText().toString());
In this case your AsyncTask should change to look like :
class ProcessTask extends AsyncTask<String,Void,Void >{
#Override
protected File doInBackground(String... params) {
String emailEditText = params[0];
String mdpEditText = params[1];
int success = 0;
String result = "";
JSONObject json ;
WebCalls webCalls = new WebCalls();
JSONObject jsonUser;
User tempUser ;
if (isFieldsEmpty(emailEditText,mdpEditText)){
result = "Empty_Field";
return result ;
}else if (!isEmailValid(emailEditText.trim())){
result = "Wrong_mail";
return result ;
}
return null;
}
Your error lies in the method doInBackground()
You are calling 2 objects EmailEditText and MdpEditText which are part of the UI Thread inside another thread.
And hence you are being asked to call "EmailEditText.getText().toString()" from UI thread.
What you are trying to do is'nt exactly clear form the snippets you have posted.
But this example might help:
In your OnCreate() have something like this
protected void onCreate(Bundle savedInstanceState) {
...
String parameters= new String[2];//make this global if you aren't calling your AsyncTask in onCreate()
parameters[1]=EmailEditText.getText().toString();
parameters[2]=MdpEditText.getText().toString();
...
}
and call your AsyncTask like this:
new YourTask().execute(parameters);
while declaration for your AsyncTask would be like this:
private class YourTask extends AsyncTask<String, Void, String> {
...
#Override
protected String doInBackground(String... params) {
String email = params[0];
String mdp= params[1];
int success = 0;
String result = "";
JSONObject json ;
WebCalls webCalls = new WebCalls();
JSONObject jsonUser;
User tempUser ;
if (isFieldsEmpty(email,mdp)){
result = "Empty_Field";
return result ;
}else if (!isEmailValid(email.trim())){
result = "Wrong_mail";
return result ;
}
return null;
}
...
}
Hope this helps!!
Related
I want to check if a user is registered or not in a database, and if it is get the information of the user.
Normally, when I retrieve the information from the server, I put in the Json a variable saying if the user exists or not. Then in onPostExecute(Void result) i treat the Json, so i don't need the AsyncTask to return any value.
Before I was calling the AsyncTask as follows:
task=new isCollectorRegistered();
task.execute();
But now i'm trying a different approach. I want my asynktask to just return a boolean where i called the AsyncTask.
the AsyncTask looks as follows:
public class isCollectorRegistered extends AsyncTask<Void, Void, Void> {
private static final String TAG_SUCCESS = "success";
int TAG_SUCCESS1;
private static final String TAG_COLLECTOR = "collector";
public String collector;
JSONArray USER = null;
JSONObject jObj = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// Checks on the server if collector is registered
try {
jObj = ServerUtilities.UserRegistered(context, collector);
return null;
} finally {
return null;
}
}
#Override
protected void onPostExecute(Void result) {
try {
String success = jObj.getString(TAG_SUCCESS);
Log.d(TAG_COLLECTOR, "Final Info: " + success);
//This if sees if user correct
if (Objects.equals(success, "1")){
//GOOD! THE COLLECTOR EXISTS!!
}
} catch (JSONException e) {
e.printStackTrace();
Log.d(TAG_COLLECTOR, "JSON parsing didn't work");
}
}
}
I have checked several posts, but I still havent found out the way to retrieve the boolean where I call the Asynktask, something like this :
task=new isCollectorRegistered();
task.execute();
boolean UserRegistered = task.result();
What would be the right approach? Any help would be appreciated
To use AsyncTask you must subclass it. AsyncTask uses generics and varargs. The parameters are the following AsyncTask <TypeOfVarArgParams , ProgressValue , ResultValue> .
An AsyncTask is started via the execute() method.
The execute() method calls the doInBackground() and the onPostExecute() method.
TypeOfVarArgParams is passed into the doInBackground() method as input, ProgressValue is used for progress information and ResultValue must be returned from doInBackground() method and is passed to onPostExecute() as a parameter.
In your case you are passing Void to your AsyncTask : isCollectorRegistered extends AsyncTask<Void, Void, Void> so you can't get your result from the thread.
please read this tutorial to a deep understand of the AsyncTask in Android
I think the following is exactly what you were looking for, Alvaro...NOTE: I tweaked your code to make it more sensible, but I tried to stick to as much of your original code as possible...
public class RegisterCollector extends AsyncTask<String, Void, Boolean> {
private static final String TAG_SUCCESS = "success";
private static final String TAG_COLLECTOR = "collector";
int TAG_SUCCESS1;
String[] strArray;
JSONArray USER = null;
JSONObject jObj = null;
public String collector;
private AppCompatActivity mAct; // Just incase you need an Activity Context inside your AsyncTask...
private ProgressDialog progDial;
// Pass data to the AsyncTask class via constructor -> HACK!!
// This is a HACK because you are apparently only suppose to pass data to AsyncTask via the 'execute()' method.
public RegisterCollector (AppCompatActivity mAct, String[] strArray) {
this.mAct = mAct;
this.strArray = strArray;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// AHAH!! - So we do need that Activity Context after all...*TISK* *TISK* # Google **sigh**.
progDial = ProgressDialog.show(mAct, "Please wait...", "Fetching the strawberries & cream", true, false);
}
#Override
protected Boolean doInBackground(String... params) {
// Checks on the server if collector is registered
try {
jObj = ServerUtilities.UserRegistered(context, collector);
return true; // return whatever Boolean you require here.
} finally {
return false; // return whatever Boolean you require here.
}
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
progDial.dismiss();
try {
String success = jObj.getString(TAG_SUCCESS);
Log.d(TAG_COLLECTOR, "Final Info: " + success);
// This 'if' block checks if the user is correct...
if (Objects.equals(success, "1")){
//GOOD! THE COLLECTOR EXISTS!!
}
// You can then also use the Boolean result here if you need to...
if (result) {
// GOOD! THE COLLECTOR EXISTS!!
} else {
// Oh my --> We need to try again!! :(
}
} catch (JSONException e) {
e.printStackTrace();
Log.d(TAG_COLLECTOR, "JSON parsing didn't work");
Toast.makeText(mAct, "JSON parsing FAILED - Please try again.", Toast.LENGTH_LONG).show();
}
}
}
...then if you want to use the generated Boolean data outside the AsyncTask class try the following:.
RegisterCollector regisColctr = new RegisterCollector((AppCompatActivity) this, String[] myStrArry);
AsyncTask<String, Void, Boolean> exeRegisColctr = regisColctr.execute("");
Boolean isColctrRegistered = false;
try {
isColctrRegistered = exeRegisColctr.get(); // This is how you FINALLY 'get' the Boolean data outside the AsyncTask...-> VERY IMPORTANT!!
} catch (InterruptedException in) {
in.printStackTrace();
} catch (ExecutionException ex) {
ex.printStackTrace();
}
if (isColctrRegistered) {
// Do whatever tasks you need to do here based on the positive (i.e. 'true') AsyncTask Bool result...
} else {
// Do whatever tasks you need to do here based on the negative (i.e. 'false') AsyncTask Bool result...
}
There you go - I think this is what you were looking for (originally). I always use this approach whenever I need Async data externally, and it has yet to fail me....
So i'm trying to call a string, the call:
EditText EditTextSearch = (EditText)findViewById(R.id.editText1);
if(!isEmpty(EditTextSearch)){
Toast.makeText(this, "Getting Information", Toast.LENGTH_LONG).show();
Log.v("checkText =>", EditTextSearch.getText().toString());
getComics getComicInfo = new getComics(EditTextSearch.getText().toString(), 1);
getComicInfo.execute();
}
after that i'm calling asynctask
class getComics extends AsyncTask<Void, Void, Void>{
private String comicName;
private String comicNameForSearch;
private int getOptionNumber;
String jsonString = "";
String result = "";
getComics(String comicName, int getOptionNumber)
{
Log.v("Check name A =>", comicName); //show name
}
//set option for search
public void SetOptionNumber(int getOptionNumber){
this.getOptionNumber = getOptionNumber;
}
public int getOptionNumber(){
return this.getOptionNumber;
}
//the data that the user searching for
public void SetComicName(String comicName){
this.comicName = comicName;
}
public String GetComicName(){
return this.comicName;
}
/*the request to the API, include fixing space and getting information about the main object, data, later on i'll call
the object I got to show the the results array */
#Override
protected Void doInBackground(Void... params) {
Log.v("is callingB =>", "Yes");
comicNameForSearch = GetComicName();
Log.v("check name=>", comicNameForSearch ); // make the app crash
anyway, if i'm trying to Log.v, the app crash, what make me think that the DoInBackground doesn't recive the comicName for some reason, guess it because of the execute way, any ideas?
edit: first time going with API so sorry if any dumb problems
the error message:Caused by: java.lang.nullPointerException: println needs a message
You are missing Assinging the value in Constructor so which results in a NullPointerException
Change this
getComics(String comicName, int getOptionNumber)
{
Log.v("Check name A =>", comicName); //show name
}
into
getComics(String comicName, int getOptionNumber)
{
this.comicName = comicName;
this.getOptionNumber = getOptionNumber;
Log.v("Check name A =>", comicName); //show name
}
Your app is getting exception because your data in Asynctask is null which you are printing and passing in doInBackground.
Change you Asynctask to this:
class getComics extends AsyncTask<Void, Void, Void>{
private String comicName;
private String comicNameForSearch;
private int getOptionNumber;
String jsonString = "";
String result = "";
getComics(String comicName, int getOptionNumber)
{
this.comicName = comicName;
this.getOptionNumber = getOptionNumber;
Log.v("Check name A =>", comicName); //show name
}
//set option for search
public void SetOptionNumber(int getOptionNumber){
this.getOptionNumber = getOptionNumber;
}
public int getOptionNumber(){
return this.getOptionNumber;
}
//the data that the user searching for
public void SetComicName(String comicName){
this.comicName = comicName;
}
public String GetComicName(){
return this.comicName;
}
/*the request to the API, include fixing space and getting information about the main object, data, later on i'll call
the object I got to show the the results array */
#Override
protected Void doInBackground(Void... params) {
Log.v("is callingB =>", "Yes");
comicNameForSearch = GetComicName();
Log.v("check name=>", comicNameForSearch ); // make the app crash
And Another way is by calling the setter method you have made inside your class like this:
getComics getComicInfo = new getComics(EditTextSearch.getText().toString(), 1);
getComicInfo .SetComicName(EditTextSearch.getText().toString());
getComicInfo .SetOptionNumber(1);
getComicInfo.execute();
I need to pass the async task result to the calling class. I have created a separate ASync class which is called from other classes. I am passing the response from Async task in "Post Execute" method to calling class method but getting null point exception. Below is my calling method in
public boolean getCategories() {
serUri = "categories.json";
WebServiceAsyncTask webServiceTask = new WebServiceAsyncTask();
webServiceTask.execute(serUri,this);
return true;
}
The method to be executed with result from below aysnc task is
public void writeJSONArray(final JSONArray result)
{
try {
for (int i=0; i<result.length();i++){
JSONObject c = result.getJSONObject(i);
String name = c.getString("catname");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
WebServiceAsyncTask Class:
public class WebServiceAsyncTask extends AsyncTask<Object,Void,JSONArray> {
ROMSjson roms;
private static JSONArray json = null;
private Context context = null;
protected JSONArray doInBackground(Object... params) {
// TODO Auto-generated method stub
String serviceUrl = (String) params[0];
final HTTPHelper httph = new HTTPHelper(serviceUrl,context);
if(serviceUrl.equalsIgnoreCase("categories.json")) {
json = httph.fetch();
}else if(serviceUrl.equalsIgnoreCase("categories/create"))
{
}
return json;
}
#Override
protected void onPostExecute(JSONArray result) { // invoked on the ui thread
roms.writeJSONArray(result);
super.onPostExecute(result);
}
I am getting null point exception when roms.writeJSONArray(result) is called. The result is correctly received before this command. I checked with Log statement. Also if I write the writeJSONArray method in my Async class instead of calling class, all works fine.
I am not sure if I am missing something in passing the result or while calling methods. Please advise. Thanks.
null pointer exception
because roms is null
you are declaring ROMSjson roms; inside WebServiceAsyncTask but not initializing it !
and using it inside `onPostExecute(JSONArray result)
roms.writeJSONArray(result);` // here roms in null
so initialize roms before using it !
Here is the problem:
else if(serviceUrl.equalsIgnoreCase("categories/create"))
{
// if it falls to this condition then your json object appears to be null
}
Hope this helps.
Interface is the best way for passing data between classes.
create a public interface
public interface WebCallListener{
void onCallComplete(JSONArray result);
}
what to do in your class?
public class WebServiceAsyncTask extends AsyncTask<Object,Void,JSONArray> {
ROMSjson roms;
private static JSONArray json = null;
private Context context = null;
//update
private WebCallListener local;
public WebServiceAsyncTask(WebCallListener listener){
local=listener;
}
/////
protected JSONArray doInBackground(Object... params) {
// TODO Auto-generated method stub
String serviceUrl = (String) params[0];
final HTTPHelper httph = new HTTPHelper(serviceUrl,context);
if(serviceUrl.equalsIgnoreCase("categories.json")) {
json = httph.fetch();
}else if(serviceUrl.equalsIgnoreCase("categories/create"))
{
}
return json;
}
#Override
protected void onPostExecute(JSONArray result) { // invoked on the ui thread
//update
super.onPostExecute(result);
local.onCallComplete(result);
}
From Your Calling class.
public class CallingClass extends Activity{
protecte void oncreate(Bundle b){
new WebServiceAsyncTask(new WebCallListener() {
#Override
public void onCallComplete(JSONArray result) {
//play with your response
}
});
}
}
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.
I have an application that does some long calculations, and I would like to show a progress dialog while this is done. So far I have found that I could do this with threads/handlers, but didn't work, and then I found out about the AsyncTask.
In my application I use maps with markers on it, and I have implemented the onTap function to call a method that I have defined. The method creates a dialog with Yes/No buttons, and I would like to call an AsyncTask if Yes is clicked. My question is how to pass an ArrayList<String> to the AsyncTask (and work with it there), and how to get back a new ArrayList<String> like a result from the AsyncTask?
The code of the method looks like this:
String curloc = current.toString();
String itemdesc = item.mDescription;
ArrayList<String> passing = new ArrayList<String>();
passing.add(itemdesc);
passing.add(curloc);
ArrayList<String> result = new ArrayList<String>();
new calc_stanica().execute(passing,result);
String minim = result.get(0);
int min = Integer.parseInt(minim);
String glons = result.get(1);
String glats = result.get(2);
double glon = Double.parseDouble(glons);
double glat = Double.parseDouble(glats);
GeoPoint g = new GeoPoint(glon, glat);
String korisni_linii = result.get(3);
So, as you see, I would like to send the string array list "passing" to the AsyncTask, and to get the "result" string array list back from it. And the calc_stanica AssycTask class looks like this:
public class calc_stanica extends AsyncTask<ArrayList<String>, Void, ArrayList<String>> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(baraj_mapa.this);
dialog.setTitle("Calculating...");
dialog.setMessage("Please wait...");
dialog.setIndeterminate(true);
dialog.show();
}
protected ArrayList<String> doInBackground(ArrayList<String>... passing) {
//Some calculations...
return something; //???
}
protected void onPostExecute(Void unused) {
dialog.dismiss();
}
So my question is how to get the elements of the "passing" array list in the AsyncTask doInBackground method (and use them there), and how to return an array list to use in the main method (the "result" array list)?
Change your method to look like this:
String curloc = current.toString();
String itemdesc = item.mDescription;
ArrayList<String> passing = new ArrayList<String>();
passing.add(itemdesc);
passing.add(curloc);
new calc_stanica().execute(passing); //no need to pass in result list
And change your async task implementation
public class calc_stanica extends AsyncTask<ArrayList<String>, Void, ArrayList<String>> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(baraj_mapa.this);
dialog.setTitle("Calculating...");
dialog.setMessage("Please wait...");
dialog.setIndeterminate(true);
dialog.show();
}
protected ArrayList<String> doInBackground(ArrayList<String>... passing) {
ArrayList<String> result = new ArrayList<String>();
ArrayList<String> passed = passing[0]; //get passed arraylist
//Some calculations...
return result; //return result
}
protected void onPostExecute(ArrayList<String> result) {
dialog.dismiss();
String minim = result.get(0);
int min = Integer.parseInt(minim);
String glons = result.get(1);
String glats = result.get(2);
double glon = Double.parseDouble(glons);
double glat = Double.parseDouble(glats);
GeoPoint g = new GeoPoint(glon, glat);
String korisni_linii = result.get(3);
}
UPD:
If you want to have access to the task starting context, the easiest way would be to override onPostExecute in place:
new calc_stanica() {
protected void onPostExecute(ArrayList<String> result) {
// here you have access to the context in which execute was called in first place.
// You'll have to mark all the local variables final though..
}
}.execute(passing);
Why would you pass an ArrayList??
It should be possible to just call execute with the params directly:
String curloc = current.toString();
String itemdesc = item.mDescription;
new calc_stanica().execute(itemdesc, curloc)
That how varrargs work, right?
Making an ArrayList to pass the variable is double work.
I sort of agree with leander on this one.
call:
new calc_stanica().execute(stringList.toArray(new String[stringList.size()]));
task:
public class calc_stanica extends AsyncTask<String, Void, ArrayList<String>> {
#Override
protected ArrayList<String> doInBackground(String... args) {
...
}
#Override
protected void onPostExecute(ArrayList<String> result) {
... //do something with the result list here
}
}
Or you could just make the result list a class parameter and replace the ArrayList with a boolean (success/failure);
public class calc_stanica extends AsyncTask<String, Void, Boolean> {
private List<String> resultList;
#Override
protected boolean doInBackground(String... args) {
...
}
#Override
protected void onPostExecute(boolean success) {
... //if successfull, do something with the result list here
}
}
I dont do it like this. I find it easier to overload the constructor of the asychtask class ..
public class calc_stanica extends AsyncTask>
String String mWhateveryouwantToPass;
public calc_stanica( String whateveryouwantToPass)
{
this.String mWhateveryouwantToPass = String whateveryouwantToPass;
}
/*Now you can use whateveryouwantToPass in the entire asynchTask ... you could pass in a context to your activity and try that too.*/ ... ...
You can receive returning results like that:
AsyncTask class
#Override
protected Boolean doInBackground(Void... params) {
if (host.isEmpty() || dbName.isEmpty() || user.isEmpty() || pass.isEmpty() || port.isEmpty()) {
try {
throw new SQLException("Database credentials missing");
} catch (SQLException e) {
e.printStackTrace();
}
}
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
this.conn = DriverManager.getConnection(this.host + ':' + this.port + '/' + this.dbName, this.user, this.pass);
} catch (SQLException e) {
e.printStackTrace();
}
return true;
}
receiving class:
_store.execute();
boolean result =_store.get();
Hoping it will help.