So I am having issues with my AsyncTask. I need postExecute to display an alert dialog if a certain error throwable is caught in doInBackground. The problem is that postExecute is never called. I have tried adding #Override but Android Studio says that it isn't overriding a method in its super class. I have also tried changing the return type. I looked around this site and couldn't find an answer. Thanks in advance.
AsyncTask Class
public class AsyncTaskActivity extends AsyncTask<Void, Void, Void> {
String exception;
#Override
protected void onPreExecute() {
}
protected void onPostExecute() {
if (exception.contains("java.net.UnknownHostException")) {
MainActivity.showDialog();
Log.i("Error Message", "ERROR MESSAGE SHOWN");
}
}
#Override
protected Void doInBackground(Void... params) {
try {
Log.i("AsyncTask", "Loading...");
// Make a URL to the web page. This takes the string representation of the URL
// and changes it into a URL object
URL url = new URL("http://api.wunderground.com/api/0c0fcc3bf62ab910/conditions/q/IN/Fort_Wayne.json");
// Get the input stream through URL Connection
URLConnection con = url.openConnection();
InputStream is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
// read each line and write to text file
while ((line = br.readLine()) != null) {
Log.i("AsyncTask", line);
TextEditor.file = new File(MainActivity.path, "siteInfo.txt");
TextEditor.writeString(line);
}
TextEditor.saveAndClose();
} catch (Exception e) {
e.printStackTrace();
exception = e.toString();
}
Log.i("AsyncTask", "DONE");
return null;
}
}
showDialog method
public static void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.context);
builder.setView(R.layout.dialog_layout);
builder.setPositiveButton(
R.string.dialog_close,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
System.exit(1);
}
});
builder.show();
}
look like you're missing something
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (exception.contains("java.net.UnknownHostException")) {
MainActivity.showDialog();
Log.i("Error Message", "ERROR MESSAGE SHOWN");
}
}
First please refer this documentation. you have missed parameters on onPostExecute().
https://developer.android.com/reference/android/os/AsyncTask.html
What you would have to do is,
#Override
protected void onPostExecute(Params) {
// your logics
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (exception.contains("java.net.UnknownHostException")) {
MainActivity.showDialog();
Log.i("Error Message", "ERROR MESSAGE SHOWN");
}
}
Please note that you need to initialize exception, otherwise it may cause a NullPointerException
Related
I have two methods which are from soap webservice. I am calling them in asyntask that is a superclass of info.java page and tring to get the results in onPost method of asyntask. The calling code of info.java/onCreate is below.
try{
PropertyInfo propertyInfo1 = new PropertyInfo();
properties.clear();
propertyInfo1 = new PropertyInfo();
propertyInfo1.setName("Module_id");
propertyInfo1.setType(String.class);
propertyInfo1.setValue(Utils.selectedModule_id);
properties.add(propertyInfo1);
new Info.AsyncTaskService().execute(new ServiceParams("GetInfo", properties), new ServiceParams("GetInfo_Photo", properties));
} catch (Exception e) {
Toast.makeText(Info.this, "Please check your internet connection.", Toast.LENGTH_LONG);
}
Both of the service methods takes the same properties thats why i gave them same properties. My problem is i can't take the results because i know that it needs to call these two methods in different threads with an order but i don't know how to do it. Could you help me please? The codes of asynctask class is also below thank you.
public class AsyncTaskService extends AsyncTask<ServiceParams, Void, Void> {
String resp = "";
String resp2 = "";
ProgressDialog progressDialog;
#Override
protected Void doInBackground(ServiceParams... params) {
resp = WebService.invoke(params[0].properties, params[0].methodName);
resp2 = WebService.invoke(params[1].properties, params[1].methodName);
return null;
}
#Override
protected void onPostExecute(Void result) {
Log.w("WEBSERVICE RESPONSE===", resp);
Log.w("WEBSERVICE RESPONSE===", resp2);
try {
JSONArray ja = new JSONArray(resp);
Utils.subMenuArrayList.clear();
Info_Item info_item=new Info_Item(ja.getJSONObject(0));
((TextView)findViewById(R.id.txtInfo)).setText(info_item.getInfo());
((TextView)findViewById(R.id.txtModule)).setText(Utils.selectedMenuName);
} catch (JSONException e) {
e.printStackTrace();
}
if (progressDialog != null)
progressDialog.dismiss();
}
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(Info.this);
if (progressDialog != null) {
progressDialog.setCancelable(false);
progressDialog.setMessage("İşlem yapılıyor ...");
progressDialog.show();
}
}
protected void onProgressUpdate(Integer... progress) {
if (progressDialog != null)
progressDialog.setProgress(progress[0]);
}
}
I have found how to do it! Wanted to share with you too.
First of all describe you async tasks as below. I have two methods which i want to use in one activity at the same time(paralel) so i described two async task classes.
public class FirstAsyncTask extends AsyncTask<ServiceParams, Void, Void> {
String resp = "";
ProgressDialog progressDialog;
#Override
protected Void doInBackground(ServiceParams... params) {
resp = WebService.invoke(params[0].properties, params[0].methodName);
return null;
}
#Override
protected void onPostExecute(Void result) {
Log.w("WEBSERVICE RESPONSE===", resp);
try {
JSONArray ja = new JSONArray(resp);
Utils.subMenuArrayList.clear();
Info_Item info_item=new Info_Item(ja.getJSONObject(0));
((TextView)findViewById(R.id.txtInfo)).setText(info_item.getInfo());
((TextView)findViewById(R.id.txtModule)).setText(Utils.selectedMenuName);
} catch (JSONException e) {
e.printStackTrace();
}
if (progressDialog != null)
progressDialog.dismiss();
}
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(Info.this);
if (progressDialog != null) {
progressDialog.setCancelable(false);
progressDialog.setMessage("İşlem yapılıyor ...");
progressDialog.show();
}
}
protected void onProgressUpdate(Integer... progress) {
if (progressDialog != null)
progressDialog.setProgress(progress[0]);
}
}
Then you should call the tasks like this with executeOnExecuter in your activity's onCreate method. I used a property array here to hold the parameters i am going to send to web service method and describe a serviceparameter with properties and method name and send them in executeOnExecuter() method. I used same properties for my both web service methods but you can describe an other property array like this "private ArrayList properties = new ArrayList<>();" and add informations you need for parameters you will send to web service method.
try{
PropertyInfo propertyInfo1 = new PropertyInfo();
properties.clear();
propertyInfo1 = new PropertyInfo();
propertyInfo1.setName("Module_id");
propertyInfo1.setType(String.class);
propertyInfo1.setValue(Utils.selectedModule_id);
properties.add(propertyInfo1);
ServiceParams serviceparams=new ServiceParams("GetInfo", properties);
ServiceParams serviceparams2=new ServiceParams("GetInfo_Photo", properties);
FirstAsyncTask asyncTask = new FirstAsyncTask(); // First
asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, serviceparams);
SecondAsyncTask asyncTask2 = new SecondAsyncTask(); // Second
asyncTask2.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, serviceparams2);
} catch (Exception e) {
Toast.makeText(Info.this, "Please check your internet connection.", Toast.LENGTH_LONG);
}
Currently , I am working in android application , in that I have 10 separate Asynctask Class for 10 separate operation , in that , the user defined function called inside onPreExecute() and onProgressUpdate() will be same for all 10 Asynctask Class. Is there any other way to simplify this . For example , I have an user defined function named "ADD" , and as of now , I have called the "ADD" function in onPreExecute() of all 10 Asynctask Class , is there any other way to simplify this , by using interface or any-other else,
Create One Class that is BaseAsyncTask which extends AsyncTask.
And write implementation of your both onPreExecute() and onProgressUpdate() int this.
public abstract class BaseAsyncTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> {
#android.support.annotation.Nullable
private ProgressDialog progressDialog = null;
public Activity activity;
public BaseAsyncTask(Activity activity) {
this.activity = activity;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(activity, R.style.CustomProgressSpinner);
CommonUtilities.showDialog(progressDialog,activity);
}
#Override
protected void onProgressUpdate(Progress... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Result result) {
super.onPostExecute(result);
CommonUtilities.dismissDialog(progressDialog);
}
}
And in extend that BaseAsyncTask in your all AsyncTask.
public class AttachmentLoadTask extends BaseAsyncTask<DocumentVO, Void, File> {#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected File doInBackground(DocumentVO... documentVOs) {
File file = null;
return file;
}
#Override
protected void onProgressUpdate(Progress... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(File file) {
super.onPostExecute(file);
}}
Create a basic async task with the operations in onPreExecute() and onProgressExecute(). Then create your async task classes (extend from the basic async task).
surely , you may create a single class for all Asynctask calls
just create a class
public class MyConnectionClass extends AsyncTask<Uri, Void, Boolean> {
MyAsyncInterface delegate = null;
HttpURLConnection httpURLConnection;
String output;
public MyConnectionClass(MyAsyncInterface myAsyncInterface) {
delegate = myAsyncInterface;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Boolean aBoolean) {
delegate.processFinish(output);
super.onPostExecute(aBoolean);
}
#Override
protected Boolean doInBackground(Uri... uris) {
try {
URL url = new URL(uris[0].toString());
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String line = null;
StringBuilder builder = new StringBuilder();
while ((line = reader.readLine()) != null) {
builder.append(line);
}
output = builder.toString();
return true;
} catch (MalformedURLException e) {
output = e.getMessage();
return false;
} catch (IOException e) {
output = e.getMessage();
return false;
} finally {
httpURLConnection.disconnect();
}
}
}
and declare an interface like this
public interface MyAsyncInterface {
void processFinish(String output);
}
then create a Uri in your activity and implement MyAsyncInterface then inside the onPostExecute call processFinish and pass the output to the processFinish(String output) method present in your calling activity
I have a problem with getting website with jsoup on Android.
public class Parser
{
Parser()
{
new Parser1().execute();
}
class Parser1 extends AsyncTask<Void, Void, Void>
{
String website1 = "http://google.com";
Document doc;
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
This code is not execute doInBackground method.
#Override
protected Void doInBackground(Void... params)
{
try
{
doc = Jsoup.connect(website1).get();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
And the rest of code.
#Override
protected void onProgressUpdate(Void... values)
{
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void result)
{
Log.d ("OK",doc.toString());
super.onPostExecute(result);
}
#Override
protected void onCancelled()
{
super.onCancelled();
}
}
}
I tried to write code without class AsyncTask, but always on Json.connect the program was exception.
Thanks for all replies.
Try this:
#Override
protected Void doInBackground(Void... params) {
try {
doc = GetDocument(website1);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Click the following link to get the full implementation of GetDocument.
References
How to use Jsoup with Volley?
you can use a httpURLconnections as an alternative and see if that works.
are you getting anything as the debug output for this code?
Log.d ("OK",doc.toString());
I am following the documentation given by IBM (https://developer.ibm.com/mobilefirstplatform/documentation/getting-started-7-0/hello-world/creating-first-native-android-mobilefirst-application/)
After calling request.send(new MyInvokeListener()); there is no sucess or failure call back. Receiving an error message "Android Prototype stopped working."
Adapter is working fine when i right click on the adapter --> Run As --> Call Mobile First Adapter
Below is my android native code.
public class TaskFeed extends AsyncTask<Void, Void, String> {
ProgressDialog Dialog = new ProgressDialog(TaskActivity.this);
#Override
protected void onPreExecute() {
Dialog.setMessage("Establishing connection...");
Dialog.show();
}
#Override
protected String doInBackground(Void... params) {
try {
final WLClient client = WLClient.createInstance(TaskActivity.this);
client.connect(new MyConnectListener());
URI adapterPath = new URI("/adapters/TaskAdapter/getAllTasks");
WLResourceRequest request = new WLResourceRequest(adapterPath,WLResourceRequest.GET);
request.send(new MyInvokeListener());
} catch (Exception e) {
e.printStackTrace();
}
// Dialog.setMessage("Loading Tasks..");
return "test";
}
#Override
protected void onPostExecute(String r) {
Dialog.dismiss();
ArrayList<ListViewModel> result = AssignAndGetCurrentTaskResults();
tvListCount.setText(GetActionBarString());
adapter = new ArrayDataAdapter(taContext, R.layout.task_row_item, result);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
My InvokeListner Class
public class MyInvokeListener implements WLResponseListener {
public void onSuccess(WLResponse response) {
try {
allTaskResults= ParseData(response.getResponseJSON().getJSONArray("array"));
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public void onFailure(WLFailResponse response) {
}
}
Taking out the code which creates and call to mobile first adapter from async task solved my problem.
There is a window leakage in android doing so.
i have a question regarding the AsyncTask class in android, and why it is giving me an error. I have defined an inner class here..
class MyTask extends AsyncTask<String,String,Integer>{
Context context;
ProgressDialog dialog;
MyTask(Context c)
{
this.context = c;
}
//#Override
protected void onPreExecute()
{
dialog = new ProgressDialog(context);
dialog.setMessage("Scanning Ports!");
dialog.show();
}
#Override
protected Integer doInBackground(String... params) {
// TODO Auto-generated method stub
for(intBeg = intBeg; intBeg <= intEnd; intBeg++
{
try
{
Socket s = new Socket(strMachine, intBeg);
isConnected += strMachine + " Is Listening On Port: " + intBeg + "\n";
Log.d("PORTSCAN", isConnected);
s.close();
}catch(Exception e){
notConnected += strMachine + " Is Not Listening On Port: " + intBeg + "\n";
//Toast.makeText(getBaseContext(), e.getMessage(), 3000).show();
Log.d("PORTSCAN", notConnected);
}
}
return 1;
}
protected void onPostExecute(Integer... params)
{
}
protected void onProgressUpdate(String... params)
{
}
}
However, when the doInBackground finishes, it supposed to call onPostExecute(), which never happens. And even when i try to use the "#Override" annotation over the onPostExecute(), it gives me an error saying onPostExecute must override a superclass method. I dont get what is happening! any help? Thanks!
onPostExcecute(Integer result) takes a single argument (no ...).
If the arguments don't match, it will not match the super method and will therefore not override it (and be called). Generally if #Override gives you an error something is wrong with your method name/parameters (or the superclass does not have such a method).
protected void onPostExecute(Integer params)//its single Integer object, not array of Integer objects
its java Varargs.and you can't change parameter of overrided method,You just change the Behaviour of override method.And its method of AsyncTask Class.
Just use this onPostExecuteMethod
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
Log.e("LOG", " on Post");
}
Check this code
private class DownloadingProgressTask extends
AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog = new ProgressDialog(ShowDescription.this);
/** progress dialog to show user that the backup is processing. */
/** application context. */
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
}
protected Boolean doInBackground(final String... args) {
try {
downloadFile(b.getString("URL"));
return true;
} catch (Exception e) {
Log.e("tag", "error", e);
return false;
}
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
if (success) {
Toast.makeText(ShowDescription.this,
"File successfully downloaded", Toast.LENGTH_LONG)
.show();
imgDownload.setVisibility(8);
} else {
Toast.makeText(ShowDescription.this, "Error", Toast.LENGTH_LONG)
.show();
}
}
}