I use asynctask to get json data from remote url but sometimes this url return errors in json data like this :
{
"error": {
"message": "(#803) Some of the aliases you requested do not exist: RNN.NES",
"type": "OAuthException",
"code": 803
}
}
in doInBackground, i check if there an error by json ..
if(true) {
//cancel asynctask and show toast with message i use
cancel(true)
}
but i do that the condititon is true but it is not cancelled
this is my code :
private class MyAsyncTask extends AsyncTask<String, Void, Void> {
ProgressDialog mProgressDialog;
#Override
protected void onPostExecute(Void result) {
db = new DAOPages(context);
db.open();
db.addPage(name, fid, picName);
getPagePrefs(fid);
db.close();
mProgressDialog.dismiss();
Intent intent = new Intent(context, PagePrefsActivity.class);
intent.putExtra("fPageid", fid);
context.startActivity(intent);
}
#Override
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(context, "Loading...",
"Data is Loading...");
}
#Override
protected Void doInBackground(String... params) {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(params[0]);
// addPageData(params[0]);
try {
if(json.getJSONObject("error") != null) {
Log.e("error", "true");
cancel(true);
}
name = json.getString("name");
fid = json.getString("id");
String picture = json.getJSONObject("picture")
.getJSONObject("data").getString("url");
picName = downloadImage(picture, fid);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
Now how can i stop that and show toast ???
thanks in advance
The method cancel(true) doesn't stop the AsyncTask. It just invokes onCancelled() instead of onPostExecute() after doInBackGround returns. You can use AsyncTask.isCancelled(), which will return true if you cancel the AsyncTask, to prevent further processing in doInBackground().
So override onCancelled() and put your Toast in there.
private class MyAsyncTask extends AsyncTask<String, Void, Void> {
ProgressDialog mProgressDialog;
#Override
protected void onPostExecute(Void result) {
db = new DAOPages(context);
db.open();
db.addPage(name, fid, picName);
getPagePrefs(fid);
db.close();
mProgressDialog.dismiss();
Intent intent = new Intent(context, PagePrefsActivity.class);
intent.putExtra("fPageid", fid);
context.startActivity(intent);
}
#Override
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(context, "Loading...",
"Data is Loading...");
}
#Override
protected Void doInBackground(String... params) {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(params[0]);
// addPageData(params[0]);
try {
if(json.getJSONObject("error") != null) {
Log.e("error", "true");
cancel(true); // after this AsyncTask.isCancelled() returns true
}
if(!this.isCancelled()){ // if it's true, prevent further processing
name = json.getString("name");
fid = json.getString("id");
String picture = json.getJSONObject("picture")
.getJSONObject("data").getString("url");
picName = downloadImage(picture, fid);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
// will be called instead onPostExecute after a cancel
#Override
protected void onCancelled() {
// Show your Toast
}
}
You can check using isCancelled() in onPostExecute() method and can show Toast in that method.Here is how you can do that -:
#Override
protected void onPostExecute(Void result) {
if(isCancelled()) {
Toast.makeText(context, "your text", Toast.LENGTH_SHORT).show();
return;
}
db = new DAOPages(context);
db.open();
db.addPage(name, fid, picName);
getPagePrefs(fid);
db.close();
mProgressDialog.dismiss();
Intent intent = new Intent(context, PagePrefsActivity.class);
intent.putExtra("fPageid", fid);
context.startActivity(intent);
}
Related
I think i write wrong my code where i try to retrieve geolocation data:
All relevant api keys are added and relevant api enabled...
private class GetCoordinates extends AsyncTask<String, Void, String>
{
ProgressDialog dialog = new ProgressDialog(AroundMeMapsActivity.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("Please wait...");
dialog.setCanceledOnTouchOutside(true);
dialog.show();
}
#Override
protected String doInBackground(String... strings) {
String response;
try {
Toast.makeText(AroundMeMapsActivity.this, "!!!!", Toast.LENGTH_SHORT).show();
String address = strings[0];
HttpDataHandler http = new HttpDataHandler();
//String url = String.format("https://maps.googleapis.com/maps/api/geocode/json?adress=%s", address);
String url = String.format("https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=AIzaSyAzSgqQEZS1K1fowxhUnwxl4hMsKMsLlN4", address);
response = http.getHTTPData(url);
return response;
} catch (Exception ex) {
}
return null;
}
#Override
protected void onPostExecute(String s) {
try {
Toast.makeText(AroundMeMapsActivity.this, "????", Toast.LENGTH_SHORT).show();
JSONObject jsonObject=new JSONObject(s);
String lat=((JSONArray)jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry")
.getJSONObject("location").get("lat").toString();
String lng=((JSONArray)jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry")
.getJSONObject("location").get("lng").toString();
answer_location.setText(String.format("Coordinates: %s / %s",lat,lng));
if(dialog.isShowing())
dialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I should get lat and lng coordinate, but it is not displayed...
Could you help to check why?
I want to load data from API for the app on the splash screen for some activity.
So I removed async task from that activity and wrote in splash screen.
I want to have splash screen should load for the same time which is provided in handler.i.e SPLASH_TIME_OUT and while navigating the data should be loaded on landing activity.
If any mistake in asking question then please correct me.
Basically want to load data on splash screen without getting more time.
Here is the code snippet.
new Handler().postDelayed(new Runnable() {
public void run() {
// After 5 seconds redirect to another intent
if(CommonUtils.getSavedPreferences(getApplicationContext(), Constants.ACCESS_TOKEN).length()>0)
{
Intent i=new Intent(SplashActivity.this,DashBoardActivity.class);
SplashAsync async=new SplashAsync();
async.execute("");
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}else{
Intent i=new Intent(SplashActivity.this,LoginActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
//Remove activity
// finish();
}
}, SPLASH_TIME_OUT); //it is set to 3000
Async task
public class SplashAsync extends AsyncTask<String, Void, String>{
private Dialog mDialog;
private String response = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
mDialog = new Dialog(SplashActivity.this, android.R.style.Theme_Translucent);
mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
mDialog.setContentView(R.layout.loading);
mDialog.setCancelable(true);
mDialog.show();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(String... params) {
response = callForDirectoryRequest();
System.out.println(response);
return response;
}
#Override
protected void onPostExecute(String result) {
try{
super.onPostExecute(result);
if (mDialog != null) {
mDialog.dismiss();
}
Gson gson = new Gson();
mMemberResponseParser = gson.fromJson(response,
new TypeToken<List<MemberResponseParser>>(){}.getType());
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
private String callForDirectoryRequest() {
String url = Constants.DIRECTORY_URL+"member_email="+CommonUtils.getSavedPreferences(getApplicationContext(), Constants.MEMBER_EMAIL)+"&member_token="+CommonUtils.getSavedPreferences(getApplicationContext(), Constants.ACCESS_TOKEN);
Log.e("", "URL IS NOW " + url);
try {
#SuppressWarnings("deprecation")
StringEntity stringEntity = new StringEntity("");
ServiceCall mServiceCall=new ServiceCall(getApplicationContext(), url, stringEntity);
response = mServiceCall.getHttpGetServiceResponse();
System.out.println("################### Response:"+ response);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
}
Can anyone help on this?
I have implemented AsyncTask like this in my code. Can you tell me if I used AsyncTask correctly? Thanks.
protected class AsyncTranslator extends AsyncTask<String, JSONObject, String>
{
#Override
protected String doInBackground(String... params) {
String mymeaning = null;
RestAPI api = new RestAPI();
try
{
JSONObject jsonObj = api.GetMeaning(params[0]);
mymeaning = jsonObj.toString();
}
catch (Exception e)
{
Log.d("Error", e.getMessage());
}
return mymeaning ;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(context, "Please wait.", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute(String mymeaning) {
Log.d("onPostExecute", null);
Intent i = new Intent(SendMeaningActivity.this, ShowMeaningActivity.class);
i.putExtra("meaning", mymeaning);
startActivity(i);
}
}
Yes you used it correctly.
Fot API call, think to use library like Retrofit. It will make your life easier.
I'm trying to fetch data from server in saving in SQLite database through Async task on Splash. i have multiple tables on server and need to fetch one after another. I'm trying this way
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork()
.penaltyLog().build());
url = getResources().getString(R.string.url);
db = new SQLCont(context);
new asyn_Task1(Splash.this).execute();
}
public class asyn_Task1 extends AsyncTask<String, Void, Boolean> {
public asyn_Task1(Splash activiy) {
context = activiy;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
new asyn_Task2(Splash.this).execute();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressdialog = new ProgressDialog(Splash.this);
progressdialog.setTitle("Processing....");
progressdialog.setMessage("Please Wait.....1 /10");
progressdialog.setCancelable(false);
progressdialog.show();
}
#Override
protected Boolean doInBackground(String... params) {
postParameters.add(new BasicNameValuePair("001", data));
try {
CustomHttpClient.executeHttpGet("001");
} catch (Exception e1) {
e1.printStackTrace();
}
String response = null;
// call executeHttpPost method passing necessary parameters
try {
response = CustomHttpClient.executeHttpPost(
url,
postParameters);
// store the result returned by PHP script that runs
// MySQL query
String result = response.toString();
// parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
id = json_data.getString("id");
st_name = " " + json_data.getString("name");
st_contact = json_data.getString("contact");
st_category = json_data.getString("Category");
st_address = json_data.getString("address");
Log.d("favourite_data", "" + id + st_name + st_contact
+ st_category + st_address);
db.adddata_hospital(context, st_name,st_contact,
st_category, st_address);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
} catch (Exception e) {
Log.e("log_tag", "Error in http connection!!" + e.toString());
}
return null;
}
}
public class asyn_Task2 extends AsyncTask<String, Void, Boolean> {
public asyn_Task2(Splash activiy) {
context = activiy;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
new asyn_Task3(Splash.this).execute();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(String... params) {
// some stuff here
}
return null;
}
}
public class asyn_Task3 extends AsyncTask<String, Void, Boolean> {
public asyn_blood_Group(Splash activiy) {
context = activiy;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
progressdialog.dismiss();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(String... params) {
// some stuff here
}
return null;
}
}
problem is that data is added for asyn_Task1 it repeated every time
expected out put
abc def ghi
jkl mno pqr
mno pqr stu
But getting output
abc def ghi
abc def ghi
abc def ghi
You will get your data based on your query. If you always execute same query then you will always get same data.
And from my point of view if possible single AsyncTask for that purpose. when all the query is completed then onpostExecute() callback will fired.
I am using an AsyncTask to download some big amount of data from a server my AsyncTask work fine so i added a progress bar to make everything beautiful but problem is when its running progress bar get freeze half way down, and i use progress dialog that also the same its freeze half way down,
private class downloadChannelsfromserver extends
AsyncTask<String, Void, String> {
ProgressDialog progressDialog;
#Override
protected String doInBackground(String... url) {
String data = "";
try {
// Fetching the data from web service
data = getLinksfromServer(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog= ProgressDialog.show(Settings.this, "Synchronicing","Synchronicing", true);
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
JSONObject json;
try {
json = new JSONObject(result);
db.deleteAll();
final JSONArray jsonArray = json.getJSONArray("XXXX");
for (int i = 0; i < jsonArray.length(); i++) {
///use for insert datainto database
}
finish();
progressDialog.dismiss();
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.e("settings", "", e);
progressDialog.dismiss();
}
}
can and someone tell me why this happen, Pls
Follow this code
private ProgressDialog pdialog = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
if(pdialog ==null){
//display progress dialog like this
pdialog = new ProgressDialog(context);
pdialog.setCancelable(false);
pdialog.setMessage("Please Wait...");
pdialog.show();
}
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
//dismiss progress dialog like this
if(pdialog!=null){
pdialog.dismiss();
pdialog = null;
}
}
Reason for progress bar get stuck was my JSON decoding since onPostExecute belongs to UI thread it take several time to decode the json results. so it will freeze the UI until JSON decode so move the decoding part to doInBackground will solve the UI freeze issue since doInBackground belongs to background thread
Please edit your code like this:
private class downloadChannelsfromserver extends
AsyncTask<String, Void, String> {
ProgressDialog progressDialog;
public downloadChannelsfromserver()
{
progressDialog = new ProgressDialog(Settings.this);
progressDialog.setTitle("Synchronicing ...");
progressDialog.setCancelable(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
}
#Override
protected String doInBackground(String... url) {
String data = "";
try {
// Fetching the data from web service
data = getLinksfromServer(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
//super.onPreExecute();
progressDialog.show();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
JSONObject json;
try {
json = new JSONObject(result);
db.deleteAll();
final JSONArray jsonArray = json.getJSONArray("XXXX");
for (int i = 0; i < jsonArray.length(); i++) {
///use for insert datainto database
}
finish();
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.e("settings", "", e);
}
finally
{
progressDialog.dismiss();
}
}
I hope this helps.
Just Use This Code:
runOnUiThread(object : Runnable {
override fun run() {
pausingDialog =
SweetAlertDialog(this#History_Activity, SweetAlertDialog.PROGRESS_TYPE)
pausingDialog!!.titleText = "Please wait...."
pausingDialog!!.setCancelable(false)
pausingDialog!!.show()
}
})
runOnUiThread(object : Runnable {
override fun run() {
}
})