How to set the textview if condition is satisfied? - android

Here in my previous question How to Print Message when Json Response has no fileds? Toast is working fine but if my response is showing no fileds with array and what if I want to use textview instead of Toast? can anyone help me?
public class MessageSent extends ListActivity{
private ProgressDialog pDialog;
JSONArray msg=null;
private TextView nomsg;
private ListView listview;
private ArrayList<HashMap<String,String>> aList;
private static String MESSAGE_URL = "";
private static final String MESSAGE_ALL="msg";
private static final String MESSAGEUSER_ID="msg_user_id";
private static final String MESSAGE_NAME="name";
private static final String MESSAGE_PROFILE="profile_id";
private static final String MESSAGE_IMAGE="image";
private static final String MESSAGE_CAST="cast";
private static final String MESSAGE_AGE="age";
private static final String MESSAGE_LOCATION="location";
private CustomAdapterMessage adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view_msgsent);
nomsg=(TextView)findViewById(R.id.no_message);
String strtexts = getIntent().getStringExtra("id");
System.out.println("<<<<<<<< id : " + strtexts);
MESSAGE_URL = "xxxxx"+strtexts;
// listview=(ListView)findViewById(R.id.list);
//ListView listview = this.getListView();
ListView listview = (ListView)findViewById(android.R.id.list);
new LoadAlbums().execute();
}
});
}
class LoadAlbums extends AsyncTask>> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MessageSent.this);
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected ArrayList<HashMap<String,String>> doInBackground(String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
ArrayList<HashMap<String,String>> data = new ArrayList<HashMap<String, String>>();
String jsonStr = sh.makeServiceCall(MESSAGE_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null)
{
try
{
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
msg = jsonObj.getJSONArray(MESSAGE_ALL);
// looping through All Contacts
for (int i = 0; i < msg.length(); i++)
{
JSONObject c = msg.getJSONObject(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(MESSAGEUSER_ID ,c.getString(MESSAGEUSER_ID));
map.put(MESSAGE_NAME,c.getString(MESSAGE_NAME));
map.put(MESSAGE_PROFILE, c.getString(MESSAGE_PROFILE));
map.put(MESSAGE_IMAGE, c.getString(MESSAGE_IMAGE));
map.put(MESSAGE_CAST, c.getString(MESSAGE_CAST));
map.put(MESSAGE_AGE, c.getString(MESSAGE_AGE)+" years");
map.put(MESSAGE_LOCATION, c.getString(MESSAGE_LOCATION));
// adding HashList to ArrayList
data.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return data;
}
protected void onPostExecute(ArrayList<HashMap<String,String>> result) {
super.onPostExecute(result);
// dismiss the dialog after getting all albums
if (pDialog.isShowing())
pDialog.dismiss();
if(msg == null || msg.length() == 0) {
//Toast.makeText(getApplicationContext(), "No response", Toast.LENGTH_LONG).show
nomsg.setText("No Message Found");
//nomsg.setBackgroundDrawable(R.drawable.borders);
}
if(aList == null) {
aList = new ArrayList<HashMap<String, String>>();
aList.addAll(result);
adapter = new CustomAdapterMessage(getBaseContext(), result);
setListAdapter(adapter);
} else {
aList.addAll(result);
adapter.notifyDataSetChanged();
}
}
}
}

As it seems you have confusions in setting up the app. Let me explain few things and also provide you some sample code.
The use of an AsynTask?
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
But there are some operations that you would have to do in the UI while working in the background thread. In that case you make use of the,
1. onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
2. onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
In your specific case as you want to set the values after the operation you have to make use of the latter mathod of the AsynTask.
The same code referring to the example you follow,
//MainActivity.java
public class MainActivity extends ListActivity {
TextView yourTextView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
.
.
//change the ID in this line from what you are using
yourTextView = (TextView) findViewByID(R.id.id_in_activity_main);
.
.
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
.
.
}
#Override
protected Void doInBackground(Void... arg0) {
.
.
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
if(contacts == null || contacts.length() <= 0){
yourTextView.setText("No Data");
}
}
}
}

Try this way :
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
if(contacts == null || contacts.length() <= 0){
yourTextView.setText("No Data");
}
}

Related

How to use listview from different xml layout file

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");

keep a ProgessDialog until the callback is executed

im using the azure mobile service. I have some users in the db i want to authenticate, and in order to do that, I execute a query to get a User after you enter a username and a password and press OK. When OK is pressed, if all it's well an intent should be started. How can I display a ProgressDialog until the callback method of the executed query is completed?
EDIT: the problem is that i have a button(logIn button) and when you click it, it will build a query and execute it in an async task, hence my problem. If i just add a progress dialog the call flow will move on since from the onClickListener point of view, the action has finished.
Just show() it before you call the query and dismiss() it in the callback method.
As your using the AsyncTask to query the data , use the onPreExecute and onPostExecute methods to show/dismiss the ProgressDialog.
Create a class which extends the AsyncTask , like this . In the onPreExecute show the ProgressDialog and when your done with fetching the data in doInBackground , in onPostExecute dismiss the dialog
public class QueryTask extends AsyncTask<Void,Void,Object> {
private ProgressDialog progressDialog = null;
private final Context mContext;
public QueryTask(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(mContext);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// do your stuff to query the data
return null;
}
#Override
protected void onPostExecute(Object result) {
progressDialog.dismiss();
// do your other stuff with the queried result
}
#Override
protected void onCancelled(Object result) {
progressDialog.dismiss();
}
}
Finally, when button onClick execute the task
new QueryTask(YourActivity.this).execute();
This example code was used by me to load all the events from an SQL database. Until the app gets the data from the server, a progress dialog is displayed to the user.
class LoadAllEvents extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Just a moment...");
pDialog.setIndeterminate(true);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_events,
"GET", params);
try {
// Checking for SUCCESS TAG
int success = json.getInt(CONNECTION_STATUS);
if (success == 1) {
// products found
// Getting Array of Products
Events = json.getJSONArray(TABLE_EVENT);
// looping through All Contacts
for (int i = 0; i < Events.length(); i++) {
JSONObject evt = Events.getJSONObject(i);
// Storing each json item in variable
id = evt.getString(pid);
group = evt.getString(COL_GROUP);
name = evt.getString(COL_NAME);
desc = evt.getString(COL_DESC);
date = evt.getString(COL_DATE);
time = evt.getString(COL_TIME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(pid, id);
map.put(COL_GROUP, group);
map.put(COL_NAME, name);
map.put(COL_DESC, desc);
map.put(COL_DATE, date);
map.put(COL_TIME, time);
// adding HashList to ArrayList
eventsList.add(map);
}
} else {
// Options are not available or server is down.
// Dismiss the loading dialog and display an alert
// onPostExecute
pDialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(getActivity(),
eventsList, R.layout.list_item, new String[] {
pid, COL_GROUP, COL_NAME, COL_DATE, COL_TIME },
new int[] { R.id.pid, R.id.group, R.id.name, R.id.header,
R.id.title2 });
setListAdapter(adapter);
}
});
}
hope this helps.

Call to AsyncTask error: LoadBookBuyInfo cannot be resolved to a type

In my call to my AsyncTask, new LoadBookBuyInfo().execute();, I receive the error: "LoadBookBuyInfo cannot be resolved to a type". I'm using fragments and I've scoured the internet for an answer but to no avail. Any help would be greatly appreciated, thanks.
Here's my code:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.buy_tbfrag, container, false);
//bookLV = (ListView)view.findViewById(R.id.list);
//bookLV = getListView();
bookLV = (ListView)view.findViewById(android.R.id.list);
//enables filtering for the contents of the given ListView bookLV
bookLV.setTextFilterEnabled(true);
//Search inputed book title
titleSearch = (EditText)view.findViewById(R.id.titleSearch);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
System.out.println("onActivityCreated executed");
bookArray = new ArrayList<Bookinfo>();
//**************************************************************************************//
//*******************New Async Task & JSON Parser code starts here**********************//
//**************************************************************************************//
//Load bookArray in Background Thread
new LoadBookBuyInfo().execute();
//Background AsyncTask to load all BookBuyInfo by making Http Request
class LoadBookBuyInfo extends AsyncTask<String, String, String> {
//Show Progress Dialog before starting background thread
#Override
protected void onPreExecute() {
super.onPreExecute();
//pDialog = new ProgressDialog(BuyFragTab); //might can only be activity
pDialog = new ProgressDialog(getActivity());//might can only be activity
pDialog.setMessage("Loading Books...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
//Get BookBuyInfo Data
protected String doInBackground(String... arg0) {
//Building parameters
ArrayList<NameValuePair> bookValues = new ArrayList<NameValuePair>();
//getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(BOOKBUY_URL, "GET", bookValues);
//Check logcat for JSON response
Log.d("Book Buy JSON: ", json.toString());
//Get JSON Data
try {
bookBuyInfo = json.getJSONArray("books");
//bookArray = new ArrayList<Bookinfo>();
//loop through all books and load data
for (int i = 0; i < bookBuyInfo.length(); i++) {
JSONObject b = bookBuyInfo.getJSONObject(i);
...
(book code setup)}
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
//}
//After completing background task, dismiss the progress dialog
protected void onPostExecute(String file_url) { // might need to be (String result) here
//dismiss the dialog after getting all the records
pDialog.dismiss();
//update UI from background thread
//runOnUiThread(new Runnable() {
getActivity().runOnUiThread(new Runnable() {
public void run() {
//updating parsed JSON data into ListView
adapter = new MyCustomAdapter(getActivity(), R.layout.buy_tbfrag, bookArray);
bookLV.setAdapter(adapter);
}
});
}
}
It looks like you placed your AsyncTask class inside onActivityCreated method. Move the whole AsyncTask class outside of this method and then call it from there.

External AsyncTask populating ListView from Fragment

I am developing an app based off fragments. A lot of the content of these fragments is collected from a database utilizing an AsyncTask. As such I'm trying to externalize the 'getting data' class so it can be reused. My fragment is as follows:
public class LocalFragment extends SherlockListFragment {
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
LoadDataFromURL url_data = new LoadDataFromURL();
url_data.setContext(getSherlockActivity());
url_data.setURL("http://url.com/get_data/");
url_data.execute();
}
}
My LoadDataFromURL class is as follows:
class LoadDataFromURL extends AsyncTask<String, String, String>{
String our_url;
ListActivity our_context;
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
JSONArray results = null;
List<PubListDetails> pubs = new ArrayList<PubListDetails>();
Handler mHandler;
public void setContext(ListActivity context){
our_context = context;
}
public void setURL(String url){
our_url = url;
}
ArrayList<HashMap<String, String>> productsList = new ArrayList<HashMap<String, String>>();
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mHandler = new Handler();
pDialog = new ProgressDialog(our_context);
pDialog.setMessage("Loading pubs please wait..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONArray json = jParser.makeHttpRequest(our_url, "GET", params);
Log.d("All Products: ", json.toString());
try {
int success = json.length();
if (success != 0){
results = json;
pubs.clear();
for (int i = 0; i <results.length(); i++){
JSONObject c = results.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String town = c.getString("town");
String county = c.getString("county");
//HashMap<String, String> map = new HashMap<String, String>();
pubs.add(new PubListDetails(id,name,town,county));
//map.put(TAG_PID, id);
//map.put(TAG_NAME, name);
//productsList.add(map);
}
}else{
Intent i = new Intent(our_context,MainMenu.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
our_context.startActivity(i);
}
} catch (JSONException e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(our_context, "ff", Toast.LENGTH_SHORT).show();
// TODO Auto-generated method stub
pDialog.dismiss();
our_context.runOnUiThread(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
ListAdapter adapter = new PubListAdapter(our_context, pubs);
our_context.setListAdapter(adapter);
}});
}
}
It is giving me errors on the basis that getSherlockActivity does not pass a ListActivity, which setListAdapter requires.
Independent of this, I am feeling more and more that I have conceptually missed the point and this isn't the ideal way to achieve what I want.
Could someone advise how from a fragment I can call an external AsyncTask which will collect data and then populate a ListView with it?
First, you want to set the data on the SherlockListFragment so your business it's not with the Activity .
Independent of this, I am feeling more and more that I have
conceptually missed the point and this isn't the ideal way to achieve
what I want.
Could someone advise how from a fragment I can call an external
AsyncTask which will collect data and then populate a list view with
it..?
Simply implement a callback interface.
public interface OnLoadDataListener {
public onLoadComplete(List<PubListDetails> data);
}
Let your fragment class implement this interface:
public class LocalFragment extends SherlockListFragment implements OnLoadDataListener {
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
LoadDataFromURL url_data = new LoadDataFromURL();
url_data.setContext(getSherlockActivity());
url_data.setURL("http://url.com/get_data/");
url_data.setListener(this); // you could unite the setContext() method in the listener registration
url_data.execute();
}
#Override
public void onLoadComplete(List<PubListDetails> data) {
ListAdapter adapter = new PubListAdapter(getSherlockActivity(), pubs);
our_context.setListAdapter(adapter);
}
}
And in your AsyncTask:
private OnLoadDataListener mListener
public void setListener(OnLoadDataListener listener){
mListener = listener;
}
and in the onPostExecute you send the data to the listener:
#Override
protected void onPostExecute(String result) {
Toast.makeText(our_context, "ff", Toast.LENGTH_SHORT).show();
// TODO Auto-generated method stub
pDialog.dismiss();
if (mListener != null) {
mListener.onLoadComplete(pubs);
}
}

Passing arguments to AsyncTask, and returning results

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.

Categories

Resources