I have a chat application. I have to send a message only once whereas I am using while(true). Because of this loop message is sending again and again. How can I break the while loop when the message is sent only once? That message should not be sent again and again.
Here is my code:
while (true) {
String[] jobsNumbers = numbers.toArray(new String[numbers.size()]);
new SendMessage().execute(jobsNumbers);
}
and here is my sendMessage Asynctask:
private class sendMessage extends AsyncTask<String, Integer, Integer> {
#Override
protected Integer doInBackground(String[] toNumbers) {
totalNumbers = toNumbers.length;
for (i = 0; i < toNumbers.length; i++) {
toNumber = toNumbers[i];
if (countMessagePerDay() >= Integer.parseInt(MaxNoOfMessagePerDay)) {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
sendSMS(toNumber);
this.publishProgress(1);
}
if (randomNo != 0 && isSent) {
databaseHelperClass.updateJobMessageStatus(JobId);
}
}
return toNumbers.length;
}
#Override
protected void onProgressUpdate(Integer... values) {
Toast.makeText(getApplicationContext(), i + "/" + totalNumbers + " :: to " + toNumber, Toast.LENGTH_SHORT).show();
super.onProgressUpdate(values);
}
#Override
protected void onCancelled(Integer integer) {
super.onCancelled(integer);
}
#Override
protected void onPostExecute(Integer integer) {
Toast.makeText(getApplicationContext(), "Message sent!", Toast.LENGTH_LONG).show();
super.onPostExecute(integer);
}
}
You can use break; for this,like:
while (true) {
String[] jobsNumbers = numbers.toArray(new String[numbers.size()]);
new SendMessage().execute(jobsNumbers);
Boolean destroy= true;
if(destroy == true){
break;
}
}
int i = 0;
while (i<1)
{
String[] jobsNumbers = numbers.toArray(new String[numbers.size()]);
new SendMessage().execute(jobsNumbers);
i++;
}
Related
I have gone through many tutorials with API.AI But didn't get the exact solution. My requirement is simply:- user will send some command using voice or text and get that commands in my application and execute some method.
API.AI
Actions on Google
Tutorial of Google Assistant
First of all you need to train your model on API.AI to respond upon some text given to the model.
Some code with API.AI FYI:
//Initialize Service
private void initService(final LanguageConfig selectedLanguage) {
try {
final AIConfiguration.SupportedLanguages lang = AIConfiguration.SupportedLanguages.fromLanguageTag(selectedLanguage.getLanguageCode());
final AIConfiguration config = new AIConfiguration(selectedLanguage.getAccessToken(),
lang,
AIConfiguration.RecognitionEngine.System);
aiDataService = new AIDataService(this, config);
} catch (Exception e) {
e.printStackTrace();
}
}
//Send request method where you can put user typed text to get the result from API.AI
private void sendRequest(final String textToSend, final int flag) {
Log.w(TAG, "Sending" + textToSend);
final AsyncTask<String, Void, AIResponse> task = new AsyncTask<String, Void, AIResponse>() {
private AIError aiError;
#Override
protected void onPreExecute() {
super.onPreExecute();
showHideProgressBar(true);
if (mVoiceRecorder != null) {
mVoiceRecorder.pauseRecording();
}
}
#Override
protected AIResponse doInBackground(final String... params) {
final AIRequest request = new AIRequest();
String query = params[0];
String event = params[1];
if (!TextUtils.isEmpty(query))
request.setQuery(query);
if (!TextUtils.isEmpty(event)) {
request.setEvent(new AIEvent(event));
}
final String contextString = params[2];
RequestExtras requestExtras = null;
if (!TextUtils.isEmpty(contextString)) {
final List<AIContext> contexts = Collections.singletonList(new AIContext(contextString));
requestExtras = new RequestExtras(contexts, null);
}
try {
Log.i("API AI Request", "" + request.toString());
return aiDataService.request(request, requestExtras);
} catch (final AIServiceException e) {
aiError = new AIError(e);
return null;
}
}
#Override
protected void onPostExecute(final AIResponse response) {
showHideProgressBar(false);
speechSentStatus = false;
okSentStatus = false;
if (response != null) {
onResult(response, flag, textToSend);
} else {
onError(aiError);
}
}
};
if (flag == OPEN_COMPLAIN_CODE) {
task.execute("", Config.Events[0], Config.Events[0]);
} else if (flag == OPEN_DIAGNOSIS_CODE) {
task.execute("", Config.Events[1], Config.Events[1]);
} else if (flag == Constants.OPEN_MEDICATION_CODE) {
task.execute("", Config.Events[2], Config.Events[2]);
} else if (flag == Constants.OPEN_LABTEST_CODE) {
task.execute("", Config.Events[3], Config.Events[3]);
} else if (flag == Constants.COMPLAINTS_ADDED) {
task.execute("", Config.Events[0], Config.Events[0]);
} else if (flag == Constants.DIAGNOSIS_ADDED) {
task.execute("", Config.Events[1], Config.Events[1]);
} else {
task.execute(textToSend, null, "");
}
}
//Based on result you can handle the business logic
private void onResult(final AIResponse response, final int flag, final String textToSend) {
runOnUiThread(new Runnable() {
#Override
public void run() {
apiAiResponseCounter = apiAiResponseCounter + 1;
isLast = false;
final Result result = response.getResult();
Log.w(TAG, "" + result.getFulfillment().getSpeech());
if (flag == Constants.COMPLAINTS_ADDED) {
//method you want to execute on receiving certain text from model
send(textToSend.toLowerCase(), DONTTEXT);
} else if (flag == Constants.DIAGNOSIS_ADDED) {
send(textToSend.toLowerCase(), DONTTEXT);
} else {
String error = "";
final String speech = result.getFulfillment().getSpeech();
if (speech.contains("?")) {
if (!result.getAction().equalsIgnoreCase("input.unknown")) {
if (result.getAction().equalsIgnoreCase(Config.Actions[5]) && result.isActionIncomplete() == false) {
//DONOTHING
} else {
digiMessage(speech, YESNO);
}
} else {
digiMessage(speech, ChatMessageAdapter.OTHER_MESSAGE);
}
} else {
if (speech.equalsIgnoreCase("Please help me the intake duration of the medication")) {
digiMessage(speech, ChatMessageAdapter.DURATION);
} else if (speech.equalsIgnoreCase("Please provide the daily routine for the medication intake")) {
digiMessage(speech, ChatMessageAdapter.FREQUENCY);
} else {
digiMessage(speech, ChatMessageAdapter.OTHER_MESSAGE);
}
}
if (result.getAction().equalsIgnoreCase(Config.Actions[4]) || result.getAction().equalsIgnoreCase(Config.Actions[5])) {
if (result.isActionIncomplete() == true) {
playSpeech(speech);
} else {
speechBuffer = "";
speechBuffer = speech;
}
} else {
if (result.getAction().equalsIgnoreCase(Config.Actions[11])) {
isLast = true;
if (mVoiceRecorder != null) {
stopVoiceRecording();
}
} else {
playSpeech(speech);
}
}
}
}
});
if (flag == Constants.COMPLAINTS_ADDED || flag == Constants.DIAGNOSIS_ADDED) {
Log.w(TAG, "Skipped");
} else {
inflateUI(response.getResult());
}
}
Below code is part of search box in my android app.
LoadCatalog is a async task for the api call, problem is whenever it is being called the editText stops taking new character for a fraction of second(skips a character in middle).
for ex- if the user want to enter "The book of leaves"...
it only sometimes take "The boo of " or "The bookof "
It skips the character, pls suggest what's wrong in my code.
private TextWatcher productEntered = new TextWatcher() {
long lastChange = 0;
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence enteredSequence, int start, int before, int count) {
searchbarActionClear.setVisibility(View.VISIBLE);
enteredText = enteredSequence;
if (CommonUtils.isConnectingToInternet(DashboardActivity.this)) {
if (enteredText.length() > 3) {
new Handler().postDelayed(new Runnable() {
public void run() {
if (System.currentTimeMillis() - lastChange >= 600) {
resetList();
toolbarSuggestionEditText.setTag(toolbarSuggestionEditText.getKeyListener());
toolbarSuggestionEditText.setKeyListener(null);
new LoadCatalog().execute(String.valueOf(enteredText));
}
}
}, 600);
lastChange = System.currentTimeMillis();
}
}
}
public void afterTextChanged(Editable s) {
}
};
private class LoadCatalog extends AsyncTask<String, Void, CustomResponse> {
#Override
protected CustomResponse doInBackground(String... params) {
String url;
if (categoryItem != null) {
url = String.format(AppConstants.URLs.SEARCH_WITH_CATEGORY, params[0], categoryItem);
} else {
url = String.format(AppConstants.URLs.SEARCH, params[0]);
}
CustomResponse response = HttpRequest.GET_REQUEST(url, DashboardActivity.this);
return response;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(CustomResponse result) {
try {
if (result.getResponseCode() == 200) {
JSONArray jsonArray = null;
jsonArray = new JSONArray(result.getResponseBody());
Suggestion suggestion = null;
if (jsonArray.length() > 0) {
suggestionList.clear();
suggestionList.add(new Suggestion(null, Suggestion.TYPE_SUGGESTION_HEADER));
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
suggestion = new Suggestion(jsonObject.getString("name"),
jsonObject.getString("category"),
Suggestion.TYPE_SUGGESTION);
suggestionList.add(suggestion);
suggestionAdapter.notifyDataSetChanged();
}
toolbarSuggestionEditText.setKeyListener((KeyListener) toolbarSuggestionEditText.getTag());
} else {
toolbarSuggestionEditText.setKeyListener((KeyListener) toolbarSuggestionEditText.getTag());
Toast.makeText(DashboardActivity.this, "No item match with your search", Toast.LENGTH_SHORT).show();
suggestionList.clear();
}
} else {
toolbarSuggestionEditText.setKeyListener((KeyListener) toolbarSuggestionEditText.getTag());
}
} catch (JSONException e) {
toolbarSuggestionEditText.setKeyListener((KeyListener) toolbarSuggestionEditText.getTag());
e.printStackTrace();
}
}
}
I have three fragments in a FragmentPagerAdapter, and each of them would fetch a list of frames/data from a server using Volley. This data would later be used to update the Fragment's RecyclerView Adapter as a Cursor.
VolleyRestClientUtils.get(getString(R.string.PATH_SHOP), LOG_TAG, params, true, false, new JsonHttpResponseHandler() {
public void onSuccess(JSONObject response) {
Log.d(LOG_TAG, "request Response : " + response.toString());
try {
String status = response.getString("status");
if (RestClientUtils.STATUS_OK.equals(status)) {
final JSONArray frames = response.getJSONArray("items");
Log.d(LOG_TAG, "request Response : " + frames.length());
if (frames != null && frames.length() > 0) {
new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... voids) {
List<ContentValues> listShopFrame = ShopFrame.fromJSONArray(frames, sort);
if (listShopFrame.size() > 0 && isActivityActive()) {
ContentResolver cr = getActivity().getContentResolver();
if (!isRequestMore) {
cr.delete(ShopFrame.CONTENT_URI, ShopFrame.COLUMN_CATEGORY + "=?",
new String[]{sort});
paramSkip = frames.length();
} else {
paramSkip += frames.length();
}
ArrayList<ContentProviderOperation> operations = new ArrayList<>();
String log = listShopFrame.size()+" ";
for (int i = 0; i < listShopFrame.size(); i++) {
operations.add(ContentProviderOperation
.newInsert(ShopFrame.CONTENT_URI)
.withValues(listShopFrame.get(i))
.build());
log += listShopFrame.get(i).toString()+"\n";
}
Log.i("loader_callback_"+sort, log);
//cr.applyBatch(ShopFrame.CONTENT_AUTHORITY, operations);
ContentValues[] opsAsArray = new ContentValues[listShopFrame.size()];
listShopFrame.toArray(opsAsArray);
cr.bulkInsert(ShopFrame.CONTENT_URI, opsAsArray);
//return true;
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
dataRefreshed = true;
Log.i("loader_callback_"+sort, "response post execute");
if (result) {
loadSucceed();
PicMixApp.getInstance().setRefreshed(ShopFrameFragment.this.getClass().getName());
} else {
loadFailed(null);
}
}
}.execute();
} else {
//TODO
//Handle error
loadFailed(getString(R.string.err_load_s, getString(R.string.frame)));
}
} else if (VolleyRestClientUtils.STATUS_RESOURCE_NOT_FOUND.equals(status)) {
hasMore = false;
loadSucceed();
} else {
loadFailed(getString(R.string.err_load_s, getString(R.string.frame)));
}
} catch (Exception e) {
Log.e(LOG_TAG, "Exception:" + e.getMessage());
loadFailed(getString(R.string.err_load_s, getString(R.string.frame)));
}
}
#Override
public void onJSONError(String responseString) {
loadFailed(getString(R.string.err_load_s, getString(R.string.frame)));
}
#Override
public void onFailure(String errMessage, int statusCode, Map<String, String> headers, byte[] responseBytes) {
loadFailed(getString(R.string.err_load_s, getString(R.string.frame)));
}
});
Whereas loadSucceed() has this following code:
if (this.recyclerView != null) {
final RecyclerView.Adapter adapter = recyclerView.getAdapter();
if (adapter != null) {
adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onChanged() {
super.onChanged();
Log.i(DefaultRecyclerFragment.this.getClass().getName(), "onChanged");
adapter.unregisterAdapterDataObserver(this);
isLoading = false;
}
public void onItemRangeRemoved(int positionStart, int itemCount) {
Log.i(DefaultRecyclerFragment.this.getClass().getName(), "onItemRangeRemoved:" + positionStart + ", itemcount:" + itemCount);
adapter.unregisterAdapterDataObserver(this);
isLoading = false;
}
});
if (adapter instanceof CursorRecyclerAdapter && loadMoreView != null) {
((CursorRecyclerAdapter) adapter).removeFooter(loadMoreView);
}
}
}
I've put the code to initialize the loader in the onResume() method of each fragment:
int id = 100+Integer.valueOf(sort);
Loader l = getLoaderManager().getLoader(id);
Log.i("loader_callback_"+sort, "success loading volley "+l);
if(l == null) {
getLoaderManager().restartLoader(id, null, this);
}
My problem is that there seems to be some sort of race condition happening, that the currently viewed fragment's adapter seem to be updated twice, and sometimes thrice. The initial cursor fetched by the Fragment's Loader has 10 rows, sure, but after the update, most of the time it only has 7 of the 21 rows expected to be put in.
I thought all the ContentResolvers' operations are synchronous (can only be done one after another, not simultaneously). What's going on here?
EDIT: Should I just put the loader init code in the loadSuccess() callback?
EDIT2: I should note that these Fragments extend android.support.v4.app.Fragment, and I'm using the version 27.1.1 of the Support Library.
I am currently writing an Android app in Android Studio for the Microsoft band that will record data from the GSR, HR, and Skin Temp.
I have the data for GSR and Skin Temp. currently reading on the application but the rate that it is updated is very slow, especially for the Skin Temp. I was wondering if there was a way to make these sensors send data more frequently because the data I have now has too long of intervals for the purpose I am using it for. Here is my MainPage.java file.
public class MainPage extends Activity {
private BandClient client = null;
TextView tvGSR;
TextView tvHeartRate;
TextView tvTemperature;
Button updateTest;
private BandGsrEventListener mGsrEventListener = new BandGsrEventListener() {
#Override
public void onBandGsrChanged(final BandGsrEvent event) {
if (event != null) {
appendGSRToUI(String.format("%d kΩ\n", event.getResistance()));
}
}
};
private BandSkinTemperatureEventListener tempEventListener = new BandSkinTemperatureEventListener() {
#Override
public void onBandSkinTemperatureChanged(final BandSkinTemperatureEvent event) {
if (event != null) {
appendTempToUI(String.format("%.2f ºF\n", event.getTemperature()*1.800 + 32.00));
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
tvGSR = (TextView) findViewById(R.id.tvGSR);
tvTemperature = (TextView) findViewById(R.id.tvTemperature);
updateTest = (Button) findViewById(R.id.updateTest);
updateTest.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
tvGSR.setText("");
tvTemperature.setText("");
new GsrSubscriptionTask().execute(); // Put first (runs connection)
new TempSubscriptionTask().execute();
}
});
}
#Override
protected void onResume() {
super.onResume();
tvGSR.setText("");
tvTemperature.setText("");
}
#Override
protected void onPause() {
super.onPause();
if (client != null) {
try {
client.getSensorManager().unregisterGsrEventListener(mGsrEventListener);
client.getSensorManager().unregisterSkinTemperatureEventListener(tempEventListener);
} catch (BandIOException e) {
appendGSRToUI(e.getMessage());
appendTempToUI(e.getMessage());
}
}
}
#Override
protected void onDestroy() {
if (client != null) {
try {
client.disconnect().await();
} catch (InterruptedException e) {
// Do nothing as this is happening during destroy
} catch (BandException e) {
// Do nothing as this is happening during destroy
}
}
super.onDestroy();
}
private class GsrSubscriptionTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
if (getConnectedBandClient()) {
int hardwareVersion = Integer.parseInt(client.getHardwareVersion().await());
if (hardwareVersion >= 20) {
appendGSRToUI("Band is connected.\n");
client.getSensorManager().registerGsrEventListener(mGsrEventListener);
} else {
appendGSRToUI("The Gsr sensor is not supported with your Band version. Microsoft Band 2 is required.\n");
}
} else {
appendGSRToUI("Band isn't connected. Check Bluetooth.\n");
}
} catch (BandException e) {
String exceptionMessage="";
switch (e.getErrorType()) {
case UNSUPPORTED_SDK_VERSION_ERROR:
exceptionMessage = "SDK Version Outdated.\n";
break;
case SERVICE_ERROR:
exceptionMessage = "GSR Not Supported\n";
break;
default:
exceptionMessage = "Unknown error occured: " + e.getMessage() + "\n";
break;
}
appendGSRToUI(exceptionMessage);
} catch (Exception e) {
appendGSRToUI(e.getMessage());
}
return null;
}
}
private class TempSubscriptionTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
if (true) {
int hardwareVersion = Integer.parseInt(client.getHardwareVersion().await());
if (hardwareVersion >= 20) {
appendTempToUI("Band is connected.\n");
client.getSensorManager().registerSkinTemperatureEventListener(tempEventListener);
} else {
appendTempToUI("Temperature Not Supported.\n");
}
} else {
appendTempToUI("Band isn't connected. Check Bluetooth\n");
}
} catch (BandException e) {
String exceptionMessage="";
switch (e.getErrorType()) {
case UNSUPPORTED_SDK_VERSION_ERROR:
exceptionMessage = "SDK Version Outdated\n";
break;
case SERVICE_ERROR:
exceptionMessage = "Microsoft Health App Error\n";
break;
default:
exceptionMessage = "Unknown error occured: " + e.getMessage() + "\n";
break;
}
appendTempToUI(exceptionMessage);
} catch (Exception e) {
appendTempToUI(e.getMessage());
}
return null;
}
}
private void appendGSRToUI(final String string) {
this.runOnUiThread(new Runnable() {
#Override
public void run() {
tvGSR.setText(string);
}
});
}
private void appendTempToUI(final String string) {
this.runOnUiThread(new Runnable() {
#Override
public void run() {
tvTemperature.setText(string);
}
});
}
private boolean getConnectedBandClient() throws InterruptedException, BandException {
if (client == null) {
BandInfo[] devices = BandClientManager.getInstance().getPairedBands();
if (devices.length == 0) {
appendGSRToUI("Band isn't paired with your phone.\n");
return false;
}
client = BandClientManager.getInstance().create(getBaseContext(), devices[0]);
} else if (ConnectionState.CONNECTED == client.getConnectionState()) {
return true;
}
appendGSRToUI("Band is connecting...\n");
return ConnectionState.CONNECTED == client.connect().await();
}
}
There is currently no way to get data at a faster rate than provided by the Microsoft Band SDK.
Also, depending on what you want the data for, the skin temperature data might not be useful for you. Looking at the sensors you want to subscribe to, it looks like your application might be health related. But the skin temperature data contains the raw values from one of several thermometers inside of the band. And the band itself will generate some heat internally, so the data is unlikely to represent the skin temperature of the wearer exactly.
I am working on a task that calls my AsyncTask , once the async task is executed , I wait for 20 seconds to get the data from server , if it is still loading I am cancelling it (handling timeout)
public void handleServerTimeOut() {
getStore = new GetStore();
getStore.execute();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (getStore != null && getStore.getStatus() != AsyncTask.Status.FINISHED) {
boolean result = getStore.cancel(true);
Log.e(TAG, " handleServerTimeOut() reached 20 seconds");
Log.e(TAG, "" + result);
}
}
}, 20000);
}
AsyncTask
class GetStore extends AsyncTask<Void, Void, String> {
String status, message;
JSONArray jsonArray;
String buildingIdGuest, buildingIdUser, finalBuildingID;
#Override
protected void onPreExecute() {
super.onPreExecute();
if (isCancelled()) {
return;
} else {
buildingIdUser = utilClass.getSharePerefernce(getActivity(), KEY_BUILDING_ID_USER, "");
buildingIdGuest = utilClass.getSharePerefernce(getActivity(), KEY_BUILDING_ID_GUEST, "");
if (buildingIdUser.equals("0") || buildingIdUser.equals("")) {
finalBuildingID = buildingIdGuest;
} else {
finalBuildingID = buildingIdUser;
}
error_flag = 0;
gridView.setVisibility(View.VISIBLE);
error_layout.setVisibility(View.INVISIBLE);
img_no_internet.setVisibility(View.INVISIBLE);
img_no_results.setVisibility(View.INVISIBLE);
img_server_error.setVisibility(View.INVISIBLE);
progressDialog.setMessage("Getting nearby stores ...");
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(true);
progressDialog.show();
}
}
#Override
protected String doInBackground(Void... params) {
if (NetworkCheck.isNetworkAvailable(getActivity())) {
try {
jsonObj = userFunction.getStores(OS, MAKE, MODEL, finalBuildingID);
Log.e(TAG, jsonObj.toString());
status = jsonObj.getString("status");
message = jsonObj.getString("message");
if (status.equalsIgnoreCase("success")) {
jsonArray = jsonObj.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++) {
gridModel = new GridModel();
gridModel.setId(jsonArray.getJSONObject(i).getString("id"));
gridModel.setStore_name(jsonArray.getJSONObject(i).getString("name"));
gridModel.setImage_name(jsonArray.getJSONObject(i).getString("image_name"));
gridListData.add(gridModel);
}
Log.e(TAG, "****** = " + gridListData.toString());
} else if (status.equalsIgnoreCase("invalid parameters")) {
error_flag = 2;
Log.e(TAG, "invalid parameters");
} else if (status.equalsIgnoreCase("no stores")) {
error_flag = 3;
Log.e(TAG, "No Data");
}
Log.e(TAG, "****** status " + status);
return String.valueOf(jsonObj);
} catch (Exception e) {
error_flag = 1; // Handling server timeout.
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog.dismiss();
return;
}
});
Log.e(TAG, e.toString());
}
} else {
Log.e(TAG, "Network Error");
error_flag = 1;
}
return null;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
Log.e(TAG, " **** error **** " + error_flag);
if (error_flag == 1) {
gridView.setVisibility(View.GONE);
error_layout.setVisibility(View.VISIBLE);
img_no_internet.setVisibility(View.VISIBLE);
} else if (error_flag == 2) {
gridView.setVisibility(View.GONE);
error_layout.setVisibility(View.VISIBLE);
img_server_error.setVisibility(View.VISIBLE);
txtError.setVisibility(View.VISIBLE);
txtError.setText(message);
} else if (error_flag == 3) {
gridView.setVisibility(View.GONE);
error_layout.setVisibility(View.VISIBLE);
img_no_results.setVisibility(View.VISIBLE);
}
gridAdapter = new GridAdapter(getActivity(), gridListData);
gridView.setAdapter(gridAdapter);
if ((progressDialog != null) && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
I also wanted to cancel my AsyncTask when the user cancels the ProgressDialog
You are checking isCancelled() only once in your AsyncTask - in the onPreExecute() method. At the time you call cancel() on your task instance, this check has already been evaluated and this is why the async task is still completing and updating the UI.
To deal with the issue, I suggest you include more checks for cancellation, using the isCancelled() method. One obvious place to include such a check is in the onPostExecute() method, right before you update the UI. You could also include a check before making the actual request to the server, after receiving the response, etc.