ProgressDialog using AsyncTask producing constructor undefined error - android

public class async extends AsyncTask<String, Integer, String>{
ProgressDialog prog;
#Override
protected void onPreExecute() {
super.onPreExecute();
prog=new ProgressDialog(async.this);//This is chowing error
prog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
prog.setMax(100);
prog.show();
}
#Override
protected String doInBackground(String... params) {
for (int i = 0; i < 10; i++) {
publishProgress(5);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
prog.dismiss();
}
#Override
protected void onProgressUpdate(Integer... values) {
prog.setProgress(values[0]);
super.onProgressUpdate(values);
}
}
The above code is producing the error:
the constructor ProgressDialog(AndroidasynctaskActivity.async) is
undefined
Why is this so? Can anyone please help me troubleshoot this?

As already mentioned, the reason this is happening is because the ProgressDialog constructor you're using needs a Context object. Here's one example of how you can do this.
Modify your async class and add a single-argument constructor that accepts a Context object. Then modify the onPreExecute method to use said Context. For example:
public class async extends AsyncTask<String, Integer, String>{
private Context context;
ProgressDialog prog;
public async(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
prog=new ProgressDialog(context);
prog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
prog.setMax(100);
prog.show();
}
// ...
}
Then to instantiate and run this AsyncTask:
async mTask = new async(context);
mTask.execute(params);

Async tasks do not provide an application or activity context. You may have to pass the context in if this class is contained within the activity that called it.

Related

ProgressDialog not displaying

I have a progress dialog, I want it to show and dismiss when my method has finished executing. now, I have this:
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Downloading...");
progressDialog.show();
new Thread(new Runnable() {
#Override
public void run() {
try{
DownloadMethod(s);
progressDialog.dismiss();
}catch (Exception e){
Toast.makeText(prefs.this, "We can't reach the data...Try again", Toast.LENGTH_SHORT).show();
}
}
}).start();
My method DownloadMethod is executed but never shows the dialog.
Actually, It must be throwing an exception with progressDialog.dismiss(); call because you cannot update UI from a worker thread, instead use AsyncTask
e.g pass parameter to constructor
private class DownloadFilesTask extends AsyncTask<Void, Void, Void> {
TypeOf_S s;
public DownloadFilesTask(TypeOf_S s){
this.s = s;
}
#Override
protected Void doInBackground(Void... obj) {
DownloadMethod(s);
return null;
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
}
}
and call it like new DownloadFilesTask(s).execute();
or with generic parameter
private class DownloadFilesTask extends AsyncTask<TypeOf_S, Void, Void> {
#Override
protected Void doInBackground(TypeOf_S... obj) {
DownloadMethod(obj[0]);
return null;
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
}
}
and call it like new DownloadFilesTask().execute(s);
progressDialog.dismiss();is throwing an exception so move your code inside runOnUiThread() method like this:
runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog.dismiss();
}
});
as suggested by Pavneet you can use async task as follows where AsyncTask<String, void, String> corresponds to the input type progress value and last is result value you are interested so give data types accordingly.
private class DownloadFilesTask extends AsyncTask<String, void, String> {
protected String doInBackground(String... urls) {
//here do the actual downloading instead of calling the DownloadMethod(s)
}
protected void onPreExecute() {
//here show the dialog
progressDialog.show();
}
protected void onPostExecute(String result) {
//here hide the dialog
progressDialog.dismiss();
}
}
and where you are calling the download function you just call this
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Downloading...");
new DownloadFilesTask().execute(s);
//here s is assumed to be string type you can give anything

How te set the time for progress dialog

I have a big process called that will be called when I execute http-request and move to other activity or fragment,
The problem is, the process isn't finished yes then the display going to be blank and after that it move to another activity.
Question is, how we can set the timer and the timeout and where I can put the line code.
This is my current code
public class BigProccess extends AsyncTask<Void, Integer, Void> {
private Context mContext;
ProgressDialog mProgress;
private int mProgressDialog=0;
public BigProccess(Context context, int progressDialog){
this.mContext = context;
this.mProgressDialog = progressDialog;
}
#Override
public void onPreExecute() {
mProgress = new ProgressDialog(mContext);
mProgress.setMessage("Loading...");
// if (mProgressDialog== ProgressDialog.STYLE_HORIZONTAL){
mProgress.setIndeterminate(false);
mProgress.setMax(100);
mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgress.setCancelable(false);
// }
mProgress.show();
}
#Override
protected void onProgressUpdate(Integer... values) {
// if (mProgressDialog== ProgressDialog.STYLE_HORIZONTAL){
mProgress.setProgress(values[0]);
// }
}
#Override
protected Void doInBackground(Void... values) {
try {
//This is to simulate there is a heavy process is running
//and we make it slow down by 500 ms for each number
for (int i =1; i<=10;i++){
publishProgress(i*10);
Thread.sleep(500);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
mProgress.dismiss();
// Toast.makeText(mContext,"Done!!!",Toast.LENGTH_LONG).show();
}
}
I've tried modified the thread.Sleep to 15000ms but it won't work.
Any help would be appreciated.

Progress dialog not appearing in database operation inside AsynTask

I'm inserting some data in my app's local database inside AysncTask, but when executing the class the progress dialog is not showing on the screen while i can see the running log. I see many related answer but the issue is not resolved. I read the .get() method blocks the ui but I'm already not using this method. I don't why it is not showing on the screen
calling async class from main Activity
AsyncGetDataFromServer task = new AsyncGetDataFromServer(this);
task.execute();
code of AsyncTask class
public class AsyncGetDataFromServer extends AsyncTask<Void, Void, Boolean> {
ProgressDialog pd;
Context cxt;
DatabaseHandler dbHelper;
private static ArrayList<DataModel> categoryArrayList;
public AsyncGetDataFromServer(Context context) {
// TODO Auto-generated constructor stub
cxt= context;
pd = new ProgressDialog(cxt);
pd.setTitle("Please wait");
pd.setMessage("Loading...");
pd.setCancelable(false);
dbHelper = new DatabaseHandler(cxt);
}
#Override
protected Boolean doInBackground(Void... params)
{
try {
Log.d("do in background","true");
for (int i = 0; i < response.body().getVideoEntity().size(); i++) {
//inserting in categories
VideoEntity videoEntity;
videoEntity = response.body().getVideoEntity().get(i);
dbHelper.insertChannels(videoEntity);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e("exception error", e.getMessage());
}
return true;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.d("on pre execute","true");
pd.show();
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
Log.d("on post execute","true");
pd.dismiss();
}
}
pass Activity instead of context to the constructor.For example-
AsyncGetDataFromServer task = new AsyncGetDataFromServer(MyActivity.this);
task.execute();
You should implement the method onProgressUpdate and use the method publishProgress :
see https://developer.android.com/reference/android/os/AsyncTask.html
Show dialog in onPreExecute() method & dismiss in onPostExecute() method:
private class AsyncGetDataFromServer extends AsyncTask<Void, Void, Boolean> {
private final ProgressDialog dialog = new ProgressDialog(YourClass.this);
protected void onPreExecute() {
this.dialog.setMessage("Loading...");
this.dialog.show();
}
protected void doInBackground(final Void unused) {
//don't interact with the ui!
}
protected void onPostExecute(final Boolean result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
}

Progress dialog not dismissing in async task

The progress dialog in AsyncTask does not dismiss, even though progressDialog.dismiss is run in onPostExecute().
I have tried implementing many answers to related questions on SO, with no success so far.
I am sure that I must be overlooking something very basic, but I am stuck.
Any pointers to an explanation and code snippet would be great, Thanks.
Main
public class Main extends Activity {
String result;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
asyncTask task = new asyncTask("Loading ...", this);
try {
result = task.execute("Question").get();
}
catch (Exception e) {
Log.e("Error: ", e.toString());
}
}
}
asyncTask
public class asyncTask extends AsyncTask<String, Void, String> {
private ProgressDialog progressDialog;
private String message;
private Context context;
public asyncTask(String msg, Context ctx) {
this.context = ctx;
message = msg;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.show(context, "", message, true, false);
}
#Override
protected String doInBackground(String... params) {
int count = 100000;
for (int i = 0; i < count; i++) {
// waste time
}
return "Answer";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
}
}
Actually your are doing :
progressDialog.show(context, "", message, true, false);
instead it should be like :
progressDialog = ProgressDialog.show(context, "", message, true, false);
You have to statically call show method and assign it to your progressDialog
Make this changes in your onPostExecute
#Override
protected void onPostExecute(String result) {
try{
if(progrssDialog.isShowing()){
progressDialog.dismiss();
}
}
catch(Exception e){
e.printStackTrace();
}
finally
{
progressDialog.dismiss();
}
}
A common issue i have found is the Variable Scope.
Most times , the ProgressDialog will be defined inside a Method , which wont be accessable outside that method.
You need to Declare it like so ,
Public Class MainActivity extends Activity {
ProgressDialog progressDialog;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private class asyncTask extends AsyncTask<String, Void, String> {
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
}
}
replace
task.execute("Question").get();
with
task.execute("Question");
by calling .get() you forcing main thread to wait. It will/can hang your UI.
progressDialog.dismiss();
put this in doInBackground() method before Return Statement.

Android AsyncTask helper class

I currently have a class UserFunctions that does all my user actions e.g. register, login etc. In the UserFunctions class there's a JSONParser object that does all the actual HTTP calls and returns the JSONObject.
public class UserFunctions {
private JSONParser jsonParser;
private static String registerURL = Constants.registerUrl;
// constructor
public UserFunctions(){
jsonParser = new JSONParser();
}
public JSONObject register(){
// getting JSON Object
JSONObject json = jsonParser.getJSONFromUrl(registerURL);
// return json
return json;
}
...
}
and then in my event handler of my activity classes I just do UserFunctions.register().
My question is, I now want to do all these calls in a background thread and at the same time show a ProgressDialog. I know running in the background thread is achieved with the AsyncTask.
But how should I achieve this design such that I can still do UserFunctions.register() in my Activity class, everything to be done in a background thread and a progressDialog shown.
Ok for this there are two parts the progress dialog and the async task, you need to move your JSONparser into the actual async task. If you want to use multiple progress dialogs just call them before calling the asynctask and close them when it returns
private class JsonRetriever extends AsyncTask<Url, Void, JSONObject>{
private JSONParser jsonParser;
private ProgressDialog dialog;
public JsonRetriever(Context c){
dialog= new ProgressDialog(c);
jsonParser= new JSONParser();
}
protected void onPreExecute() {
dialog.setMessage("Starting retrieval");
dialog.show();
}
protected JSONObject doInBackground(Url... params) {
try{
return jsonParser.getJSONFromUrl(params[0]);
}catch(Exception e){
return false;
}
return true;
}
protected void onPostExecute(final JSONObject success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
Then to call this just do
public JSONObject register(){
return new JSONRetriever(this).execute(registerURL).get();
}
Do as the following:
1)Declare you dialog in activity class like this:
ProgressDialog dialog;
2)then declare you AsyncTask as below:
private class RegisterUser extends AsyncTask<String,Integer,String>{
String nessage="";
#Override
protected void onPreExecute(){
dialog = ProgressDialog.show(context, "Registering user",
"Please wait.....");
}
#Override
protected String doInBackground(String... params) {
// provide yourcode to register the user then return message
return message="you are registered";
}
protected void onPostExecute(String result) {
dialog.dismiss();
if (result.equlas("you are resgisted"))
// optinal if you want to do as below
// do something here showing toast or any thing of your prefreance
}
}
Would this help you?
#Override
public void onCreate(Bundle savedInstanceState) {
new MyAsyncTask(this).execute();
}
privateclass MyAsyncTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
private Context context;
public ProgressTask(Context context) {
this.context= context;
dialog = new ProgressDialog(context);
}
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
protected Boolean doInBackground(final String... args) {
// do you registering or whether here
// in this model you can return a boolean to the PostExecute.
}
}
Have a look at publishProgress() from the AsyncTask-Class i think its what you are looking for.
This method is used for updating the UI, when the Background-Thread done some Work. You can call it when ever you want it in the doInBackground()-Method.

Categories

Resources