please help, I've given up on finding a solution
Data json already be in ArrayList, nothing error found but the progressdialog can't stop loading. I'm already put PG.dismis in postExecute but even the Adapter cannot changed.
private static List<DataVoucher> processResponse(String response) {
List<DataVoucher> list = new ArrayList<DataVoucher>();
try {
JSONObject jsonObj = new JSONObject(response);
JSONArray jsonArray = jsonObj.getJSONArray("produk");
Log.d(TAG, "data lengt: " + jsonArray.length());
DataVoucher dataVoucher = null;
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
dataVoucher = new DataVoucher();
dataVoucher.setKode(obj.getString("kode"));
dataVoucher.setHrg(obj.getString("hrg"));
dataVoucher.setNom(obj.getString("nom"));
dataVoucher.setKet(obj.getString("ket"));
list.add(dataVoucher);
listvoucher.add(obj.getString("nom"));
}
} catch (JSONException e) {
Log.d(TAG, e.getMessage());
}
return list;
}
public static String requestDataVoucher(final String operator) {
final String TAG = "SEND JSON";
Thread thread = new Thread() {
public void run() {
Looper.prepare();
JSONObject jsonObjSend = new JSONObject();
try {
jsonObjSend.put("type", "svoc");
jsonObjSend.put("hp", "089631633614");
jsonObjSend.put("opr", operator);
Log.i(TAG, jsonObjSend.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
SendHttpPost(jsonObjSend);
Looper.loop();
}
};
thread.start();
return TAG;
}
private class MainActivityAsync extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("retrieving...");
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
String response = requestDataVoucher(pilihOperator
.getSelectedItem().toString());
list = processResponse(response);
return null;
}
#Override
protected void onPostExecute(String result) {
adapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_item, listvoucher);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
pilihVoucher.setAdapter(adapter);
adapter.notifyDataSetChanged();
if (!adapter.isEmpty()) {
progressDialog.dismiss();
} // this is annoying
}
}
adapter = new ArrayAdapter(MainActivity.this,
android.R.layout.simple_spinner_item, listvoucher);
I think u mean
adapter = new ArrayAdapter(MainActivity.this,
android.R.layout.simple_spinner_item, list);
Btw just dismiss ur progressDialog at onPostExecute() not checking anything and maybe warn the user if the list is empty so you will evade these problems.
Many issues here
doInBackground is running in a thread, different from the ui thread. You are calling requestDataVoucher which is also creating a new thread, useless in this case.
You are calling processResponse with the String response which is the result of requestDataVoucher. According to your code, response equals "SEND JSON". So JSONObject jsonObj = new JSONObject(response); will trigger an Exception, listvoucher will remain empty, and so will your adapter. Conclusion, adapter is empty, the progressDialog won't disappear.
I can't propose a fix, as SendHttpPost is unknown. But as far as goes my understanding, you should remove the Thread creation from requestDataVoucher and return the JSON String generate by SendHttpPost.
Related
Progress dialog should appear before display Alert dialog in Android app . I am using android studio.
Alert dialog content will be from Async task in separate class file. So excuting Progress dialog from async task.
But i am not able to see progress dialog screen before AlertDialog opens.
here is my async task code below.
public class ResidentsPaymentInfoHttpResponse extends AsyncTask<String,
Void, List<paymentInfo>> {
ProgressDialog pDialog;
private Context MSAContext;
public ResidentsPaymentInfoHttpResponse(Context context) {
MSAContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(MSAContext,"Autenticando", "Contactando o
servidor, por favor, aguarde alguns instantes.", true, false);
}
#Override
protected List<UserPaymentInfo> doInBackground(String... params){
String flatNo = params[0];
String urls = "https://script.google.com/macros/s/;"
List<UserPaymentInfo> residentsMonthlyPayments = new ArrayList<>();
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(urls)
.build();
Response responses = null;
try
{
responses = client.newCall(request).execute();
String jsonData = responses.body().string();
JSONObject jobject = new JSONObject(jsonData);
JSONArray jarray = jobject.getJSONArray("ResidentsInfo");
int limit = jarray.length();
for(int i=0;i<limit; i++)
{
JSONObject object = jarray.getJSONObject(i);
if(object.getString("FlatNo").equals(flatNo) &&
object.getString("PaymentStatus").equals("notpaid")) {
UserPaymentInfo residentMaintePayment = new
UserPaymentInfo();
UserInfo residentInfo = new UserInfo();
residentInfo.setUserFlatNo(object.getString("FlatNo"));
residentsMonthlyPayments.add(residentMaintePayment);
}
}
}
catch (IOException e)
{
// e.printStackTrace();
}
pDialog.dismiss();
}
catch (Exception ex)
{
// ex.printStackTrace();
}
return residentsMonthlyPayments;
}
protected void onPostExecute(List<UserPaymentInfo> rusult){
super.onPostExecute(rusult);
pDialog.dismiss();
}
}
Am i missing something???
You should not update UI elements (which belong to main/UI thread) inside doInBackground(). May be removing pDialog.dismiss(); from end lines of doInBackground() change the situation.
Check below link.
How to show progress dialog in Android?
you are not calling show() method on progress dialog. You should do it inside preExecute then dismiss it in postExecute method of async task.
Also as said by VSB you should not update UI elements from doInBackground method.
I have a little problem with make a toast when my table database is null based on parsing json. I mean, when data is no result or no data found then make a toast " Sorry no data found". Any help would be greatly appreciated.
here my code for show the data
private void showEmployee(){
JSONObject jsonObject = null;
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(konfigurasi.TAG_JSON_ARRAY);
for(int i = 0; i<result.length(); i++){
JSONObject jo = result.getJSONObject(i);
String id = jo.getString(konfigurasi.TAG_ID);
String nama = jo.getString(konfigurasi.TAG_NAMA);
String pyg = jo.getString(konfigurasi.TAG_PENYELENGGARA);
String tmpt = jo.getString(konfigurasi.TAG_TEMPAT);
String tgl = jo.getString(konfigurasi.TAG_TGL);
String jam = jo.getString(konfigurasi.TAG_JAM);
String email = jo.getString(konfigurasi.TAG_EMAIL);
HashMap<String,String> employees = new HashMap<>();
employees.put(konfigurasi.TAG_ID,id);
employees.put(konfigurasi.TAG_NAMA,nama);
employees.put(konfigurasi.TAG_PENYELENGGARA,pyg);
employees.put(konfigurasi.TAG_TEMPAT,tmpt);
employees.put(konfigurasi.TAG_TGL,tgl);
employees.put(konfigurasi.TAG_JAM,jam);
employees.put(konfigurasi.TAG_EMAIL,email);
list.add(employees);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new MySimpleArrayAdapter(this, list);
listView.setAdapter(adapter);
}
And this for postexcetude code :
private void getJSON(){
class GetJSON extends AsyncTask<Void,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(TampilSemuaPgw.this,"Mengambil Data","Mohon Tunggu...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(s == null || s.length() == 0){
Toast.makeText(getApplicationContext(), "No Data",Toast.LENGTH_LONG).show();
}
// Dismiss the progress dialog
if (loading.isShowing())
loading.dismiss();
JSON_STRING = s;
showEmployee();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(konfigurasi.URL_GET_ALL);
return s;
}
}
GetJSON gj = new GetJSON();
gj.execute();
}
Update Code by KeLiuyue :
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(konfigurasi.URL_GET_ALL);
return s;
}
#Override
protected void onPostExecute(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("result");
if(jsonArray.length() == 0){
Toast.makeText(getApplicationContext(), "No Data", Toast.LENGTH_LONG).show();
if (loading.isShowing()){
loading.dismiss();
}
return;
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("TAG",s);
// Dismiss the progress dialog
if (loading.isShowing())
loading.dismiss();
JSON_STRING = s;
showEmployee();
}
Try this in your code .
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(konfigurasi.URL_GET_ALL);
return s;
}
#Override
protected void onPostExecute(String s) {
// edited here
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("result");
if(jsonArray.length() == 0){
Toast.makeText(getApplicationContext(), "No Data", Toast.LENGTH_LONG).show();
if (loading.isShowing()){
loading.dismiss();
}
return;
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("TAG",s);
// Dismiss the progress dialog
if (loading.isShowing())
loading.dismiss();
JSON_STRING = s;
showEmployee();
}
1.Determine return value whether is empty in doInBackground method
2.Determine param value whether is empty in onPostExecute method
You need to Debug this issue why your toast is not showing:
You have correctly put show Toast code in onPostExecute
Now to debug , first put a Log to know the value of s , whether it is ever null or empty.
If yes and still toast is not showing, move the dialog dismiss dialog before Toast and check.
If Toast still does not show debug your showEmployee() method as what it does.
Good Day everyone,
I have some problem here. I make a web service call in AsyncTask DoInBackground.
And I wanted to set list adapter, but I got error
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
Now how to set list adapter in post execute or something?
My code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
progressBar = (ProgressBar)findViewById(R.id.prgLoading);
//Initialize the ListView
final ListView lvProf = (ListView)findViewById(R.id.lvProfile);
//call the asynctask cals and add item to the list.
new LoadDataForActivity().execute();
//Set adapter , but i got error here
lvProf.setAdapter(new ListProfileAdapter(this,mItems));
}
private class LoadDataForActivity extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
progressBar.setVisibility(View.VISIBLE);
progressBar.setIndeterminate(false);
progressBar.setClickable(false);
}
#Override
protected Void doInBackground(Void... params) {
getAll();
getTotalLeaveBalance();
getMedicalBalance();
return null;
}
#Override
protected void onPostExecute(Void result) {
//here is I add the item to my list (mitems)
try{
ResponseServiceMedicalBalance = ResponseServiceMedicalBalance.replace("\\\"", "\"");
ResponseServiceMedicalBalance = ResponseServiceMedicalBalance.substring(1, ResponseServiceMedicalBalance.length() - 1);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(ResponseServiceMedicalBalance);
String Status = jsonObject.get("Status").toString();
if (Status == "true") {
// JSONArray structure = (JSONArray) jsonObject.get("DataList");
String dataku = jsonObject.get("DataList").toString();
mItems = new ArrayList<ListProfileItem>();
try {
dataku = ANGGACRYYPT.decrypt(Enc_Pass, dataku);
}catch (GeneralSecurityException e){
//handle error - could be due to incorrect password or tampered encryptedMsg
}
JSONParser parser = new JSONParser();
JSONArray structure = (JSONArray) parser.parse(dataku);
for (int i = 0; i < structure.size(); i++) {
JSONObject data = (JSONObject) structure.get(i);
item = new ListProfileItem();
item.claimpostname = data.get("claim_post_name").toString();
String claimamount = data.get("max_limit_per_year").toString();
if (claimamount!=("0.0"))
{
Double amount = Double.parseDouble(claimamount);
DecimalFormat formatter = new DecimalFormat("#,###.00");
String AmountFormatted = formatter.format(amount);
item.claimpostamount = AmountFormatted;
}
else
{
item.claimpostamount = data.get("max_limit_per_year").toString();
}
mItems.add(item);
}
// initialize and set the list adapter
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
There are several ways of solving this, One of the quick and dirtiest is:
Change your AsyncTaskActivity Like this:
private class LoadDataForActivity extends AsyncTask<Void, Void, Void> {
private ListView listView;
private Context context;
public LoadDataForActivity(ListView listView,Context context){
this. listView = listView;
this.context = context;
}
#Override
protected void onPreExecute() {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
progressBar.setVisibility(View.VISIBLE);
progressBar.setIndeterminate(false);
progressBar.setClickable(false);
}
#Override
protected Void doInBackground(Void... params) {
getAll();
getTotalLeaveBalance();
getMedicalBalance();
return null;
}
#Override
protected void onPostExecute(Void result) {
//here is I add the item to my list (mitems)
try{
ResponseServiceMedicalBalance = ResponseServiceMedicalBalance.replace("\\\"", "\"");
ResponseServiceMedicalBalance = ResponseServiceMedicalBalance.substring(1, ResponseServiceMedicalBalance.length() - 1);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(ResponseServiceMedicalBalance);
String Status = jsonObject.get("Status").toString();
if (Status == "true") {
// JSONArray structure = (JSONArray) jsonObject.get("DataList");
String dataku = jsonObject.get("DataList").toString();
mItems = new ArrayList<ListProfileItem>();
try {
dataku = ANGGACRYYPT.decrypt(Enc_Pass, dataku);
}catch (GeneralSecurityException e){
//handle error - could be due to incorrect password or tampered encryptedMsg
}
JSONParser parser = new JSONParser();
JSONArray structure = (JSONArray) parser.parse(dataku);
for (int i = 0; i < structure.size(); i++) {
JSONObject data = (JSONObject) structure.get(i);
item = new ListProfileItem();
item.claimpostname = data.get("claim_post_name").toString();
String claimamount = data.get("max_limit_per_year").toString();
if (claimamount!=("0.0"))
{
Double amount = Double.parseDouble(claimamount);
DecimalFormat formatter = new DecimalFormat("#,###.00");
String AmountFormatted = formatter.format(amount);
item.claimpostamount = AmountFormatted;
}
else
{
item.claimpostamount = data.get("max_limit_per_year").toString();
}
mItems.add(item);
}
listView.setAdapter(new ListProfileAdapter(context,mItems));
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
And you can call the asyncTask like this:
new LoadDataForActivity(listView,this).execute();
Initialise mItems as
mItems = new ArrayList<>();
Create object for ListProfileAdapter
ListProfileAdapter adapter = new ListProfileAdapter(this,mItems);
lvProf.setAdapter(adapter);
Add items in mItems
mItems.add(item);
After all items added to the list notify the adapter
adapter.notifyDataSetChanged();
move it from onCreate to onPostExecute()
define instance of Adapter as global variable then add Items in doInBackground() & call setAdapter onPostExec.
//Set adapter , but i got error here >> move it to onPostExecute
lvProf.setAdapter(new ListProfileAdapter(this,mItems));
I think the following line should be before setting your adapter,
mItems = new ArrayList<ListProfileItem>();
adapter = new ListProfileAdapter(this,mItems)
lvProf.setAdapter(adapter);
Make the instance variable,
ListProfileAdapter adapter;
instead of putting in the Asynctask. After finishing the asynctask in onPostExecute you also need to run,
adapter.notifyDatasetChanged();
I'm trying to get scoreboards from FB, and to achieve this I issue a HTTP request to the API. It has to be done on a separate thread, here is my async task class:
public class AsyncBuildScoreboard extends AsyncTask<Void, Void,String> {
ProgressBar pb;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... voids) {
String token = Session.getActiveSession().getAccessToken();
try{
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("https://graph.facebook.com/"+GameStatic.app_id+"?fields=scores&access_token=" + token);
HttpResponse resp = client.execute(get);
HttpEntity responseEntity = resp.getEntity();
String response = EntityUtils.toString(responseEntity);
return response;
}
catch (IOException e)
{
}
return "";
}
protected void onPostExecute(String response) {
try{
JSONObject res = new JSONObject(response);
JSONObject scores = res.getJSONObject("scores");
JSONArray data = scores.getJSONArray("data");
int len = data.length();
String[] values = new String[len];
for(int i=0;i<len;i++)
{
JSONObject obj = data.getJSONObject(i);
JSONObject user = obj.getJSONObject("user");
String name = user.getString("name");
String score = obj.getString("score");
values[i] = name + " " + score;
GameStatic.scoreboard.add(values[i]);
}
}
catch (JSONException e)
{
}
}
}
GameStatic is an external variable to store what I get from thread. And yet, when doing this:
AsyncBuildScoreboard board = new AsyncBuildScoreboard ();
board.execute();
final ListView listview = (ListView) findViewById(R.id.scorelist);
final StableArrayAdapter adapter = new StableArrayAdapter(this,
android.R.layout.simple_list_item_1, GameStatic.scoreboard);
listview.setAdapter(adapter);
a null pointer exception occurs, which means, that the GameStatic.scoreboard has NOT been filled with the entries I wanted.
What am I doing wrong, any ideas?
I'd be obliged, since I am REALLY pressed on time...
public class AsyncBuildScoreboard extends AsyncTask<Void, Void, Void>
{
public ListView list;
public Context ctx;
public ArrayList<String> scoreboard = new ArrayList <String> ();
public AsyncBuildScoreboard(ListView list, Context context)
{
this.list = list;
this.ctx = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids)
{
Void nothing = null;
String token = Session.getActiveSession().getAccessToken();
try{
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("https://graph.facebook.com/"+GameStatic.app_id+"?fields=scores&access_token=" + token);
HttpResponse resp = client.execute(get);
HttpEntity responseEntity = resp.getEntity();
String response = EntityUtils.toString(responseEntity);
}
catch (IOException e)
{
}
return nothing;
}
protected void onPostExecute(String response) {
try{
JSONObject res = new JSONObject(response);
JSONObject scores = res.getJSONObject("scores");
JSONArray data = scores.getJSONArray("data");
int len = data.length();
String[] values = new String[len];
for(int i=0;i<len;i++)
{
JSONObject obj = data.getJSONObject(i);
JSONObject user = obj.getJSONObject("user");
String name = user.getString("name");
String score = obj.getString("score");
values[i] = name + " " + score;
scoreboard.add(values[i]);
}
}
catch (JSONException e)
{
}
final ArrayAdapter adapter = new ArrayAdapter(ctx,
android.R.layout.simple_list_item_1, scoreboard);
list.setAdapter(adapter);
}
}
you will need to use onPostExecute for showing the score when doInBackground execution complete instead of passing GameStatic.scoreboard just after AsyncTask.execute() because doInBackground always execute in separate thread so it.
you can use AsyncBuildScoreboard class constructor for passing ListView instance and Context from Activity as:
ListView listview;
Context context;
public AsyncBuildScoreboard(ListView listview,Context context){
this.context=context;
this.listview=listview;
}
....
protected void onPostExecute(String response) {
//...your code here..
StableArrayAdapter adapter = new StableArrayAdapter(context,
android.R.layout.simple_list_item_1, GameStatic.scoreboard);
listview.setAdapter(adapter);
}
and change your Activity code as for passing Context :
ListView listview = (ListView) findViewById(R.id.scorelist);
AsyncBuildScoreboard board = new AsyncBuildScoreboard (listview,
Your_Activity.this);
board.execute();
or you can also create callbacks methods using interface which fire when on UI Thread when doInBackground execution complete.see following post for more details:
android asynctask sending callbacks to ui
I was using AsyncTask to display data on a List, But the loading is visible, but it dosen't show the list..
public void getLocations(){
Connect client = new Connect(SERVICE_URI + "/GetLocations");
client.AddHeader("Accept", "application/json");
client.AddHeader("Content-Type", "application/json");
try {
client.Execute(RequestMethod.GET);
JSONObject rootJson = new JSONObject(client.getResponse());
JSONArray jsonArray = rootJson.getJSONArray("GetLocationsResult");
String[] names = null;
if (jsonArray != null) {
names = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
names[i] = json.getString("Name");
}
}
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, names));
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public void getLocations(){
Connect client = new Connect(SERVICE_URI + "/GetLocations");
client.AddHeader("Accept", "application/json");
client.AddHeader("Content-Type", "application/json");
try {
client.Execute(RequestMethod.GET);
JSONObject rootJson = new JSONObject(client.getResponse());
JSONArray jsonArray = rootJson.getJSONArray("GetLocationsResult");
String[] names = null;
if (jsonArray != null) {
names = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
names[i] = json.getString("Name");
}
}
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, names));
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
If data for ListAdapter is collected in doInBackground() of AsyncTask, Activity onCreate() does not wait for AsyncTask to complete.
So what we have:
1. Activity Start
2. AsyncTask start
3. Activity trying to set ListAdapter - it's empty, because AsyncTask does not completed
4. AsyncTask completed - but ListAdapter filled with empty data
My solution: AsyncTask should notify ListAdapter of Activity after data loading completes:
Public class MyActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myActivity);
ExpandableListView listView = (ExpandableListView) findViewById(R.id.expList);
//MyArrayList - data source for your list. For example, I use static ArrayList from other class. Replace with your data object.
final MyExpandableListAdapter adapter = new MyrExpandableListAdapter(getApplicationContext(), myArrayList);
listView.setAdapter(adapter);
int taskId=1; // type of task should be executed
MyAsyncTask myTask = new MyAsyncTask(taskId);
myTask.execute(adapter);
#Override
protected Dialog onCreateDialog(int id) {
ProgressDialog progress = null;
progress = new ProgressDialog(this);
//Should user work with app while data loading? In my case, no, so setCancelable=false
progress.setCancelable(false);
if (id==1) {
progress.setMessage("Getting locations, please wait...");
}
if (id==2) {
progress.setMessage("Task type #2 performing...");
}
return progress;
} // end onCreateDialog
class MyAsyncTask extends AsyncTask<Void, Void, Void> {
MyExpandableListAdapter adapter; //ExpandableListAdapter you wanna notify about data load completion
int taskId; //Type of tasks in your Activity. You have only one, however - getLocations().
MyAsyncTask(int taskId) {
//save task ID to use in doInBackground, showDialog and dismissDialog
this.taskId=taskId;
}
#Override
protected Void doInBackground(Void... params) {
if (taskId==1) {
// YOUR LONG-TIME TASK #1 THAT UPDATES DATA SOURCE FOR LIST ADAPTER GOES HERE;
}
if (taskId==2) {
// YOUR LONG-TIME TASK #2 THAT UPDATES DATA SOURCE FOR LIST ADAPTER GOES HERE;
// create more task types if needed
}
//this adapter will be used in onPostExecute() to notify Activity about data changes
adapter = (MyExpandableListAdapter) params[0];
return null;
}
#Override
protected void onPreExecute() {
//Show dialog for this task type. if need more than one - us switch here and in onCreateDialog,
// different dialog types for different tasks etc.
showDialog(taskId);
}
#Override
protected void onPostExecute(Void result) {
// IMPORTANT! Update data in Activity
adapter.notifyDataSetChanged();
dismissDialog(taskId);
}
} //end of AsyncTask
} //end of Activity class