I tried to add button dinamically inside async task (i've choose to send view and context to async task constructor) but not works.
can you help me?
here is the code:
on create void i have this
View content = getWindow().findViewById(Window.ID_ANDROID_CONTENT);
GetTokenRequest getToken = new GetTokenRequest(this.getApplicationContext(),content );
String[] params = new String[]{"","","http://"};
getToken.execute(params);
then i've create async task:
public static final class GetTokenRequest extends AsyncTask<String, Void, String> {
private Context context;
private View view;
public GetTokenRequest(Context ctx, View vw) {
context = ctx;
view=vw;
}
#Override
protected String doInBackground(String... params) {
String Username = params[0];
String PassWord = params[1];
String URL = params[2];
String data = sendHttpPostRequest(Username, PassWord,URL);
return data;
}
#Override
protected void onPostExecute(String result) {
if (result !=null){
try {
JSONObject jsonObj = new JSONObject(result);
// Getting JSON Array node
TokenList = jsonObj.getJSONArray(TAG_tokenlist);
// looping through All Contacts
for (int i = 0; i < TokenList.length(); i++) {
JSONObject c = TokenList.getJSONObject(i);
String deviceporttoken = c.getString("a");
String PortName = c.getString("b");
String IMageUrl = c.getString("c");
ImageButton imgToken=new ImageButton(context);
final RelativeLayout.LayoutParams paramsimgToken = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
paramsimgToken.addRule(RelativeLayout.ALIGN_LEFT);
paramsimgToken.addRule(RelativeLayout.CENTER_VERTICAL);
paramsimgToken.width=100;
paramsimgToken.width=50;
imgToken.setId(i);
imgToken.setLayoutParams(paramsimgToken);
imgToken.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
}
});
View rootView = ((Activity)context).getWindow().getDecorView().findViewById(android.R.id.content);
linearLayout1= (LinearLayout) rootView.findViewById(R.id.linearLayout1);
linearLayout1.addView(imgToken);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
//parsing json
}
}}
the problem is that linearLayout1.addView(imgToken); get null point exception.
thank you in advance.
Is your AsyncTask an inner class?
Because, if you write the AsyncTask class as inner class of your activity, you can easily acces the views of you activity in onPostExecute.
Just declare your LinearLayout as global value of the activity, call 'findById' in the onCreate of your activity and you're good to go.
Now in the onPostExecute, just call myLinearLayout.addView
Let me know if it worked :)
Related
I know this question has been asked a lot but I still can't figure out how on my code. I'm trying to get values out of this block of code:
private void getAnswerKey(){
class GetAnswerKey extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
JSON_STRING = s;
showAnswerKey();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(Configuration.URL_GET_ANSWER);
return s;
}
}
GetAnswerKey gA = new GetAnswerKey();
gA.execute();
}
private void showAnswerKey () {
correctAnswers = new ArrayList<Integer>();
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(Configuration.TAG_JSON_ARRAY);
for (int i = 0; i < result.length(); i++) {
JSONObject jo = result.getJSONObject(i);
int answerKey = jo.getInt(Configuration.TAG_ANSWERKEY);
correctAnswers.add(answerKey);
System.out.println((i + 1) + "a. " + options[correctAnswers.get(i)]); //data are there
}
} catch (JSONException e) {
e.printStackTrace();
}
}
How do I access correctAnswers arrayList on my main activity? correctAnswers itself isn't empty in this code, but when I tried accessing it on other method, it's null. I've tried passing data to other method. Still return null. I have the arrayList as global variable. Any ideas how??
Like suvojit_007 might have correctly assumed, you may be attempting to access the arraylist before it is populated..
You can use interfaces. Create your interface...
public interface ResponseInterface {
public void getResponse(String data);
}
In your AsyncTask declare your interface
private ResponseInterface responseInterface;
Create a constructor within the AsyncTask with the interface as a parameter
public GetAnswerKey(ResponseInterface responseInterface) {
this.responseInterface = responseInterface;
}
Within your onPostExecute, call the interface
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
responseInterface.getResponse(s);
}
... and finally when executing your AsyncTask, do this...
new GetAnswerKey(new ResponseInterface() {
#Override
public void getResponse(String data) {
// do whatever you want with your answers here.
// Also, whatever function that is accessing the
// arrayList, call it here, that way you avoid any
// possibility of the arrayList being null
}
}).execute();
I have this recyclerview that is running but problem is, it's not populating anything out. So it's a blank fragment. I was follow this tutorial on how to do it and I twitched it to fit my own. Of course, it went wrong.
Tutorial I was following: http://androidcss.com/android/fetch-json-data-android/#comment-56
tutorial was going on a main activity asynctask adapter. I switched it up to fragment asynctask and adapter.
public class FragmentGlobalfeed extends android.support.v4.app.Fragment {
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private android.support.v7.widget.RecyclerView mRVProfile;
private com.example.admin.quoteme.AdapterProfile mAdapter;
private android.widget.LinearLayout llLayout;
#Override
public void onCreate(android.os.Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//background doesn't seem to be able to launch so i am gonna take an alt step and try methods to update
//BackgroundFeed backgroundFeed = new BackgroundFeed(getActivity());
//backgroundFeed.execute();
/*AsyncLogin asyncLogin = new com.example.admin.quoteme.FragmentGlobalfeed.AsyncLogin();
asyncLogin.execute();*/
new com.example.admin.quoteme.FragmentGlobalfeed.AsyncLogin().execute();
}
#Override
public android.view.View onCreateView(android.view.LayoutInflater inflater, android.view.ViewGroup container, android.os.Bundle savedInstanceState) {
// Inflate the layout for this fragment
android.view.View view = inflater.inflate(com.example.admin.quoteme.R.layout.fragmentglobalfeed, null);
java.util.List<Profile> data = new java.util.ArrayList<>();
//recyclerview
mRVProfile = (android.support.v7.widget.RecyclerView) view.findViewById(com.example.admin.quoteme.R.id.recyclerViewGlobal);
mRVProfile.setLayoutManager(new android.support.v7.widget.LinearLayoutManager(getActivity()));
mAdapter = new AdapterProfile(getActivity(), data);
mRVProfile.setAdapter(mAdapter);
return view;
}
private class AsyncLogin extends android.os.AsyncTask<String, String, String> {
java.net.HttpURLConnection conn;
java.net.URL url = null;
#Override protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try{
//enter url address where ur json file is
url = new java.net.URL("http:http://192.168.0.100/Quoteme/getfeed.php");
} catch (java.net.MalformedURLException e){
e.printStackTrace();
return e.toString();
}
try {
conn = (java.net.HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
conn.setDoOutput(true);
} catch (java.io.IOException e1) {
e1.printStackTrace();
return e1.toString();
}
try{
int response_code = conn.getResponseCode();
if(response_code == java.net.HttpURLConnection.HTTP_OK){
//read data
java.io.InputStream input = conn.getInputStream();
java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
return (result.toString());
} else {
return("unsuccessful");
}
} catch (java.io.IOException e){
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result){
java.util.List<Profile> data = new java.util.ArrayList<>();
try {
org.json.JSONArray jArray = new org.json.JSONArray(result);
//extraction
for(int i= 0; i<jArray.length(); i++){
org.json.JSONObject json_data = jArray.getJSONObject(i);
Profile profile = new Profile();
profile.setUser_id(json_data.getString("user_id"));
profile.setQuote_points(json_data.getInt("quote_points"));
profile.setQuote(json_data.getString("quote_description"));
data.add(profile);
}
//setup and hand data over to rv // adapter
/*mRVProfile = (android.support.v7.widget.RecyclerView)llLayout.findViewById(com.example.admin.quoteme.R.id.recyclerViewGlobal);
mAdapter = new AdapterProfile(getActivity(), data);
mRVProfile.setAdapter(mAdapter);
mRVProfile.setLayoutManager(new android.support.v7.widget.LinearLayoutManager(getActivity()));*/
} catch (org.json.JSONException e){
android.widget.Toast.makeText(getActivity(),e.toString(), android.widget.Toast.LENGTH_LONG);
}
}
}
There are also some commented out codes that are my past experiments. Please ignore the commented out ones. Also i have tried to initialise the adapters both in asyncTask and also in onCreate, both did not work. I wonder.
And my adapter class.
public class AdapterProfile extends android.support.v7.widget.RecyclerView.Adapter<android.support.v7.widget.RecyclerView.ViewHolder>{
private android.content.Context context;
private android.view.LayoutInflater inflater;
java.util.List<Profile> data = java.util.Collections.emptyList();
com.example.admin.quoteme.Profile current;
int currentPos = 0;
public AdapterProfile(android.content.Context context, java.util.List<com.example.admin.quoteme.Profile> data){
this.context=context;
inflater= android.view.LayoutInflater.from(context);
this.data=data;
}
#Override
public android.support.v7.widget.RecyclerView.ViewHolder onCreateViewHolder(android.view.ViewGroup parent, int viewType){
android.view.View view = inflater.inflate(com.example.admin.quoteme.R.layout.feed_layout_v2, parent, false);
MyHolder holder = new com.example.admin.quoteme.AdapterProfile.MyHolder(view);
return holder;
}
#Override
public void onBindViewHolder(android.support.v7.widget.RecyclerView.ViewHolder holder, int position) {
// Get current position of item in recyclerview to bind data and assign values from list
MyHolder myHolder= (MyHolder) holder;
com.example.admin.quoteme.Profile current=data.get(position);
myHolder.name.setText(current.getUser_id());
myHolder.quote.setText(current.getQuote());
myHolder.points.setText(current.getQuote_points() + "Points");
// load image into imageview using glide
/*Glide.with(context).load("http://192.168.1.7/test/images/" + current.fishImage)
.placeholder(R.drawable.ic_img_error)
.error(R.drawable.ic_img_error)
.into(myHolder.ivFish);*/
}
#Override
public int getItemCount() {
return data.size();
}
class MyHolder extends android.support.v7.widget.RecyclerView.ViewHolder{
private android.widget.TextView name;
private android.widget.TextView quote;
private android.widget.TextView points;
// create constructor to get widget reference
public MyHolder(android.view.View itemView) {
super(itemView);
name = (android.widget.TextView)itemView.findViewById(com.example.admin.quoteme.R.id.name);
quote = (android.widget.TextView)itemView.findViewById(com.example.admin.quoteme.R.id.quote);
points = (android.widget.TextView)itemView.findViewById(com.example.admin.quoteme.R.id.points);
}
}
I think these two class will suffice to fish out the error. I am stuck trying to populate this recyclerview out.
In onCreateView you have-> mAdapter = new AdapterProfile(getActivity(), data);
But data is just empty varibale there. Later in the Async task you build up new local data variable that you dont use. The commented block in the post execute should be working- is there error messages in the log?
You're populating the data ArrayList in the AsyncTasks' onPostExecute method but you never set it to the adapter...
Uncomment the creation of the adapter and setting it to the recyclerview. Why is it commented out? Any errors?
Hey your data object size must be null as seeing your code
#Override
protected void onPostExecute(String result){
java.util.List<Profile> data = new java.util.ArrayList<>();
try {
org.json.JSONArray jArray = new org.json.JSONArray(result);
//extraction
for(int i= 0; i<jArray.length(); i++){
org.json.JSONObject json_data = jArray.getJSONObject(i);
Profile profile = new Profile();
profile.setUser_id(json_data.getString("user_id"));
profile.setQuote_points(json_data.getInt("quote_points"));
profile.setQuote(json_data.getString("quote_description"));
data.add(profile);
}
//setup and hand data over to rv // adapter
/*mRVProfile = (android.support.v7.widget.RecyclerView)llLayout.findViewById(com.example.admin.quoteme.R.id.recyclerViewGlobal);
mAdapter = new AdapterProfile(getActivity(), data);
mRVProfile.setAdapter(mAdapter);
mRVProfile.setLayoutManager(new android.support.v7.widget.LinearLayoutManager(getActivity()));*/
} catch (org.json.JSONException e){
android.widget.Toast.makeText(getActivity(),e.toString(), android.widget.Toast.LENGTH_LONG);
}
}
}
Here you are creating a local data ArrayList . But you set a different list named the same data to the adapter with instantiated but with zero size.
You should execute the AssyncTask from onCreateView() method and set the adapter from onPostExecute() method.
* Also use the same data variable to be set in Adapter. Better to make it field of Fragment class.
I am working on android ListView and i am getting one issue.I created one list view into the XML file installation.xml and i want to use that list view into my Searchdata.java. so basically what i want that when i click on searchdata button than data is fetched from web service and after parsing, it will saved into the listview.and when i click on Installation View button than new window will be appear where i could see that list data.
SearchData.java
public class SearchData extends Activity {
EditText Keyword;
JSONParser jsonparser = new JSONParser();
ListView Datalist;
HorizontalScrollView VideoDatalist;
ArrayList<HashMap<String, String>> DataList;
ArrayList<HashMap<String, String>> VideoDataList;
JSONArray contacts = null;
private ProgressDialog pDialog;
ImageButton searchdata,InstallationView;
String Keyvalue = new String();
private static final String TAG_InnerText = "InnerText";
private static final String TAG_Title = "Title";
private static final String TAG_URL = "URL";
private static final String TAG_VIDEO_URL = "URL";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_data);
InstallationView=(ImageButton)findViewById(R.id.InstallationView);
Keyword = (EditText) findViewById(R.id.KeyData);
Datalist=(ListView)findViewById(R.layout.activity_installation);
VideoDatalist=(HorizontalScrollView)findViewById(R.id.Horizontallist);
searchdata=(ImageButton)findViewById(R.id.searchicon);
String Keyvalue = new String();
DataList = new ArrayList<HashMap<String, String>>();
VideoDataList = new ArrayList<HashMap<String, String>>();
searchdata.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new ReadData().execute();
}
});
InstallationView.setOnClickListener(new View.OnClickListener(){
public void onClick(View v)
{
startActivity(new Intent(SearchData.this, Installation.class));
}
});
}
public class ReadData extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchData.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
protected Void doInBackground(Void... arg0) {
try{
Keyvalue=Keyword.getText().toString();
String Jsonstr = jsonparser.makeHttpRequest("http://10.47.93.26:8080/Search/api/Search/"+Keyvalue);
try {
if (Jsonstr != null) {
JSONArray jsonObj = new JSONArray (Jsonstr);
for (int i = 0; i < jsonObj.length(); i++) {
JSONObject c = jsonObj.getJSONObject(i);
String name = c.optString(TAG_Title);
String url = c.optString(TAG_URL);
HashMap<String, String> info = new HashMap<String, String>();
if( !name.isEmpty() )
{
info.put(TAG_Title, name);
}
else
{
info.put(TAG_Title,"User Manual");
}
if(url.contains("youtube"))
{
info.put(TAG_URL, url);
VideoDataList.add(info);
}
else
{
info.put(TAG_URL, url);
DataList.add(info);
}
}
}
else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
SimpleAdapter adapter = new SimpleAdapter(
SearchData.this, DataList,
R.layout.list_item, new String[]
{
TAG_Title
}, new int[] {
R.id.InnerText });
Datalist.setAdapter(adapter);
}
}
}
web service running and parsing code is running correctly. i am getting error at post method,so can you help me on this.
Error
Call your Installation activity in onClick() method:
And pass your ArrayList data through intent,
InstallationView.setOnClickListener(new View.OnClickListener(){
public void onClick(View v)
{
Intent intent= new Intent(SearchData.this, Installation.class);
intent.putParcelableArrayListExtra("HASH_MAP",DataList);
startActivity(intent);
}
});
In your Installation activity class,set the view in onCreate() and initialize listview from xml file:
setContentView(R.layout.activity_installation);
ListView listView = (ListView)findViwById(R.id.listview);
And try to get the data from intent:
ArrayList<HashMap<String,String>> hashmap_dataList = getIntent.getParcelableArrayListExtra("HASH_MAP");
then do whatever you want with listview and hashmap.
In the onCreate(...) method of your SearchData Activity, the following can never work and will always return 'null' (hence your NullPointerException)...
Datalist=(ListView)findViewById(R.layout.activity_installation);
Calling findViewById(...) will only work for any UI elements which have been inflated when you called setContentView(...). In this case you used R.layout.activity_search_data for your layout file which doesn't contain a ListView with an id of R.layout.activity_installation which is, by the way, a resource id of a layout file and not a resource id of a UI element.
The only way you can do what you need is to put your data as an extra into the Intent you use when you call...
startActivity(new Intent(SearchData.this, Installation.class));
...when the Installation Activity is created it will then need to get the data and create its own adapter.
EDIT: HashMap is Serializable and can be passed as an Intent extra. Pass your DataList HashMap as follows...
Intent i = new Intent(SearchData.this, Installation.class);
i.putExtra("data_list", DataList);
startActivity(i);
In the Installation Activity you can then use...
getIntent().getSerializableExtra("data_list");
I got a weird problem with an android activity : I re-used one of my previous activity that works well, but this time all I got is "Can't create handler inside thread that has not called Looper.prepare()"
I tried to debug, and everything in the async task is performing well but when I reach then end of onPostExecute() the error is raised.
So I tried to disable my process about the process dialog, the only change is that it's crashing on line upper.
Here is the code :
public class DateActivity extends ActionBarActivity{
ProgressDialog mProgressDialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_date);
ActionBar actionBar = this.getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(getResources().getString(R.string.actionbar_titre_date));
if (VerifConnexion.isOnline(this)) {
this.mProgressDialog = ProgressDialog.show(this, getResources().getString(R.string.loading),
getResources().getString(R.string.loading), true);
new QueryForDateTask().execute(this.mProgressDialog, this, this.getApplicationContext());
} else {
...
}
});
alertDialog.show();
}
}
private class QueryForDateTask extends
AsyncTask<Object, Void, ArrayList<String>> {
private ProgressDialog mProgressDialog;
private Activity act;
private Context context;
protected ArrayList<String> doInBackground(Object... o) {
this.mProgressDialog = (ProgressDialog) o[0];
this.act = (Activity) o[1];
this.context = (Context) o[2];
ArrayList<String> listeDate = this.parseJSON(this.startQuerying());
return listeDate;
}
public JSONObject startQuerying() {
JSONRequest jr = new JSONRequest();
String from = getResources().getString(R.string.api_param_from);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.FRANCE);
from += "=" + sdf.format(new Date());
String url = getResources().getString(
R.string.api_dates_json);
JSONObject jo = jr.getJSONFromUrl(url + "?" + from);
return jo;
}
public ArrayList<String> parseJSON(JSONObject jsonObject) {
ArrayList<String> l = new ArrayList<String>();
try {
JSONArray array = jsonObject.getJSONArray("dates");
if (array != null) {
for (int i = 0; i < array.length(); i++) {
String type = array.getString(i);
l.add(type);
} // fin parcours JSONArray
}
} catch (Exception _e) {
}
return l;
}
protected void onProgressUpdate(Integer... progress) {
// setProgressPercent(progress[0]);
}
protected void onPostExecute(ArrayList<String> lDate) {
// Create items for the ListView
DateAdapter adapter = new DateAdapter(this.context, R.layout.searchitem_date, lDate, this.act);
// specify the list adaptor
((ListView)findViewById(R.id.list)).setAdapter(adapter);
this.mProgressDialog.dismiss();
}
} // fin async
}
I tried this to replace the call to the AsyncTask :
runOnUiThread(new Runnable() {
public void run() {
QueryForDateTask task = new QueryForDateTask();
task.execute(DateActivity.this.mProgressDialog, DateActivity.this, DateActivity.this.getApplicationContext());
}
});
(like explained in Asynctask causes exception 'Can't create handler inside thread that has not called Looper.prepare()' as far as I understood), but the result is exactly the same.
So I can't understand why it is not working in this activity despite all is ok for the other ones of the project.
Any clue ?
Thank a lot for all ideas :)
Just a post to mark the trouble as resolved :
the adapter i used was buggy in parsing parameters and throwed a NullPointerException.
I just fixed it, the AsyncTask is now running without problem.
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.