Start function inside overriden Asynctask method of the same class - java

I have AsyncTask class and I call it in my main class. I need to override the onPostExecute function and call inside ftpDisconnect(). But it does not work properly.
TempClass dj = new TempClass(serialnum) {
#Override
protected void onProgressUpdate(Integer... values) {
pr_bar.setProgress(values[0]);
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
//dj.ftpDisconnect(); //need to make this happen
super.onPostExecute(result);
}
};
dj.execute();
My TempClass:
public class TempClass extends AsyncTask<String, Integer, String> {
public TempClass(String serialnum) {
this.serialnum = serialnum;
}
#Override
protected String doInBackground(String... params) {
//do stuff
return null;
}
public boolean ftpDisconnect() {
try {
mFTPClient.disconnect();
return true;
} catch (Exception e) {
}
return false;
}
}

You can't access that instance of dj without making it final. You should be able to call ftpDisconnect from inside the class:
#Override
protected void onPostExecute(String result) {
ftpDisconnect();
super.onPostExecute(result);
}

Related

How to use RxJava instead of AsyncTask to load data?

I am using AsyncTask for loading data, data comes from server, but due to so much data I want to load data on a background thread.
Here is my code
private void loadData() {
new AsyncTask<Void, ArrayList<DataModel>, ArrayList<DataModel>>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
DialogHelper.showProgress(MyActivity.this);
}
#Override
protected ArrayList<DataModel> doInBackground(Void... voids) {
try {
return MyParser.parseData(jsonDataAsResultFromServer);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(ArrayList<DataModel> list) {
super.onPostExecute(list);
DialogHelper.hideProgress();
if (list.size() > 0) {
myAdapter = new MyAdapter(MyActivity.this);
myAdapter.addAll(list);
recyclerview.setAdapter(myAdapter);
}
}
}.execute();
}

Can't get website using jsoup on Android

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());

AsyncTask onPostExecute listener [duplicate]

This question already has answers here:
how to return result from asyn call
(2 answers)
Closed 7 years ago.
Activity.java
//Activity stuff
MyClass mc = new MyClass();
mc.getText();
public void dosomething() {
textview.setText(mc.getText());
}
MyClass.java
class MyClass {
String text;
public void setText() {
class GetTextFromWEB extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String url = urls[0];
String output;
//Getting text from web
return output;
}
#Override
protected void onPostExecute(String _text) {
text = _text;
}
}
String url = "google.com";
//Doing with url something
new GetText().execute(url);
}
public String getText() {return text;}
}
Promblem is - in activity setText do faster, then AsyncTask do it's job.
So when setText run, it's run like setText(null)
I need to check in activity, is asynk ended, so i have my text to set.
I hope i explained it
And i don't even need exactly AsyncTask, i need jsoup working, so if there is solution with another thread-class, with which jsoup will work, i can use it
Edit
class GetLyrics extends AsyncTask<String, Void, String> { //Class for getting lyrics
private Context con;
public GetLyrics(Context con) {
this.con = con;
}
#Override
protected String doInBackground(String... urls) {
//do something
}
#Override
protected void onPostExecute(String _lyrics) {
lyrics = _lyrics;
con.runOnUiThread(new Runnable() {
#Override
public void run() {
((TextView) findViewById(R.id.lyricsOutput)).setText(lyrics);
}
});
}
}
Call the method setting your text in the postExecute inside your AsyncTask or set the text directly on your postExecute method.
And wrap the line with setText() inside runOnUIThread (otherwise you will get an exception saying that the view can be accessed only by the thread that created it, since you are setting the text from async task).
Setting the text would be something like this
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
((TextView) findViewById(R.id.txtFieldName)).setText("your text");
}
});
That way you can quit worrying about checking if the async task is finished. But avoid doing complex ui operations like this. Since this is just setting the text on TextView, it should be allright.
1: Make my first project from my previous post and add some new lines in it to get data from http: api's.
public class Example extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_example);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("parameter1", "xyz"));
params.add(new BasicNameValuePair("parameter2", "abc"));
params.add(new BasicNameValuePair("parameter3", "opqr"));
ServerConnection task = new ServerConnection(this, new ResultListener() {
#Override
public void result(String response) {
Toast.make(this, response, Toast.LENGTH_LONG).show();
}
#Override
public void loader(boolean visble) {
}
#Override
public void connectionLost(String error) {
Toast.make(this, error, Toast.LENGTH_LONG).show();
}
});
}
public class ServerConnection extends AsyncTask<String, String, String> implements Constant {
ResultListener listener;
private String Method = "GET";
private List<NameValuePair> params = new ArrayList<NameValuePair>();
private Context context;
private ConnectionDetector cd;
// public static Drawable drawable;
public ServerConnection(Context context, ResultListener r) {
this.context = context;
this.listener = r;
cd = new ConnectionDetector(context);
this.execute();
}
public boolean isConnection() {
return cd.isConnectingToInternet();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
if (!isConnection()) {
cancel(true);
return "Sorry!connection lost,try again or later";
}
ApiResponse air = new ApiResponse();
System.out.println("working hre" + "hi");
String json;
try {
json = air.makeHttpRequest(URL, getMethod(), getParams());
} catch (Exception e) {
json = e.getMessage();
cancel(true);
return json;
}
return json;
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCancelled(String result) {
listener.connectionLost(result);
rl.connectionLost("Sorry!connection lost,try again or later");
super.onCancelled(result);
}
#Override
protected void onPostExecute(String result) {
System.out.println("onpost" + result);
listener.result(result);
listener.loader(true);
super.onPostExecute(result);
}
public String getMethod() {
return Method;
}
public void setMethod(String method) {
Method = method;
}
public List<NameValuePair> getParams() {
return params;
}
public void setParams(List<NameValuePair> params) {
this.params = params;
}
}
Example

publishing progress in shared class in doBackgorund in AsyncTask

I have several different AsyncTasks that need to perform the same shared basic operation and show progress while doing so. Rather than copying a lot of code several times (with progress showing in each) is there a way to share the code by passing in the other class? The AsyncTasks are very different and you can't just pass in the Abstract, which has a protected publishProgress() method anyway. Looked at a bunch of examples and tried to a lot of different variations without success.
So here are the details...lets say we have two different tasks doing different stuff, but sharing the need to hit a server, download a number of files and then put them in a DB (and then do other stuff):
public class ExampleTaskFragment extends ListFragment {
private ProgressDialog mProgress;
private void hideProgress() {
mProgress.dismiss();
}
private void showProgress(String message) {
mProgress = ProgressDialog.show(getActivity(), null, message, true, false);
}
protected void updateProgressMessage(String message) {
mProgress.setMessage(message);
}
public class TaskA extends AsyncTask<Object, String, ArrayList<A>> {
public void progressUpdate(String... values) {
publishProgress(values);
}
#Override
protected void onCancelled() {
hideProgress();
}
#Override
protected void onPreExecute() {
showProgress("Stuff before shared...");
}
#Override
protected ArrayList<A> doInBackground(Object... params) {
// DoStuffPublish is the common stuff both tasks share
DoStuffPublish dostuff = new DoStuffPublish(this);
return doMoreStuffA();
}
#Override
protected void onPostExecute(ArrayList<A> result) {
updateProgressMessage("After shared stuff...");
hideProgress();
}
ArrayList<A> doMoreStuffA() {
return new ArrayList<A>();
}
}
public class TaskB extends AsyncTask<Object, String, ArrayList<B>> {
public void progressUpdate(String... values) {
publishProgress(values);
}
#Override
protected void onCancelled() {
hideProgress();
}
#Override
protected void onPreExecute() {
showProgress("Stuff before shared...");
}
#Override
protected ArrayList<B> doInBackground(Object... params) {
// DoStuffPublish is the common stuff both tasks share
DoStuffPublish dostuff = new DoStuffPublish(this);
return doMoreStuffB();
}
#Override
protected void onPostExecute(ArrayList<B> result) {
updateProgressMessage("After shared stuff...");
hideProgress();
}
ArrayList<B> doMoreStuffB() {
return new ArrayList<B>();
}
}
}
public class DoStuffPublish {
private AsyncTask task;
public DoStuffPublish(AsyncTask task) {
super();
this.task = task;
doSharedStuff();
}
protected void publishProgress(String message) {
if (task instanceof TaskA) {
((TaskA)task).progressUpdate(message);
}
else if (task instanceof TaskB) {
((TaskB)task).progressUpdate(message);
}
}
public void doSharedStuff() {
publishProgress("Doing Shared stuff...");
// Do lots of shared things here...
publishProgress("Done doing shared stuff...");
}
}
This code has been cobbled together - so don't get too hung up on the syntax. The concept it there...I want to have a shared class I can call in 2 or more tasks that can share that code and still publish updates. I have tried putting the ProgressDialog in the tasks and outside without success. When I have done so I get "Only the original thread that created a view hierarchy can touch it's views". And in the debugger you can see the two different threads - the original main UI thread and the thread created in the Form doInBackground(Object... params).
I fear this may not be possible...
robinj - had it correct, just needed to read his/her answer a little better. The trick was to code it like this:`public class ExampleTaskFragment extends ListFragment {
private ProgressDialog mProgress;
private void hideProgress() {
mProgress.dismiss();
}
private void showProgress(String message) {
mProgress = ProgressDialog.show(getActivity(), null, message, true, false);
}
protected void updateProgressMessage(String message) {
mProgress.setMessage(message);
}
public class TaskA extends AsyncTask<Object, String, ArrayList<A>> {
public void progressUpdate(String... values) {
publishProgress(values);
}
#Override
protected void onProgressUpdate(String... values) {
updateProgressMessage(values[0]);
}
#Override
protected void onCancelled() {
hideProgress();
}
#Override
protected void onPreExecute() {
showProgress("Stuff before shared...");
}
#Override
protected ArrayList<A> doInBackground(Object... params) {
// DoStuffPublish is the common stuff both tasks share
DoStuffPublish dostuff = new DoStuffPublish(this);
return doMoreStuffA();
}
#Override
protected void onPostExecute(ArrayList<A> result) {
updateProgressMessage("After shared stuff...");
hideProgress();
}
ArrayList<A> doMoreStuffA() {
return new ArrayList<A>();
}
}
public class TaskB extends AsyncTask<Object, String, ArrayList<B>> {
public void progressUpdate(String... values) {
publishProgress(values);
}
#Override
protected void onProgressUpdate(String... values) {
updateProgressMessage(values[0]);
}
#Override
protected void onCancelled() {
hideProgress();
}
#Override
protected void onPreExecute() {
showProgress("Stuff before shared...");
}
#Override
protected ArrayList<B> doInBackground(Object... params) {
// DoStuffPublish is the common stuff both tasks share
DoStuffPublish dostuff = new DoStuffPublish(this);
return doMoreStuffB();
}
#Override
protected void onPostExecute(ArrayList<B> result) {
updateProgressMessage("After shared stuff...");
hideProgress();
}
ArrayList<B> doMoreStuffB() {
return new ArrayList<B>();
}
}
}
public class DoStuffPublish {
private AsyncTask task;
public DoStuffPublish(AsyncTask task) {
super();
this.task = task;
doSharedStuff();
}
protected void publishProgress(String message) {
if (task instanceof TaskA) {
((TaskA)task).progressUpdate(message);
}
else if (task instanceof TaskB) {
((TaskB)task).progressUpdate(message);
}
}
public void doSharedStuff() {
publishProgress("Doing Shared stuff...");
// Do lots of shared things here...
publishProgress("Done doing shared stuff...");
}
}
`
Note the
#Override
protected void onProgressUpdate(String... values) {
updateProgressMessage(values[0]);
}
Previously I had been trying to directly set the mProgress value, but it was in the wrong thread? Anyway thanks to robinj for the help! If you put an answer in I will thumbs it up...

progressbar in asynctask not getting in onProgressUpdate

My asynctask not going in onProgressUpdate. why? I'm going to create progress bar in asynctask. Below is my code to show uploading image by using progress bar.
public static class RegisterDataEngineForPost extends AsyncTask<MultipartEntity, integer, String>{
ProgressBar ProgressBarUpload;
public void setmCurrentPhotoPath(ProgressBarUploadb) {
ProgressBarUpload = ProgressBarUploadb;
}
#Override
protected void onProgressUpdate(integer... values) {
}
#Override
protected void onPreExecute() {
ProgressBarUpload.setProgress(0);
}
#Override
protected String doInBackground(MultipartEntity... params) {
}
#Override
protected void onPostExecute(String result) {
}
}
}
Use http://developer.android.com/reference/android/os/AsyncTask.html#publishProgress(Progress...)
manually, Android will not know your progress out of nothing, you need to determine it yourself.
You have to call publishProgress(progress_value) to update the progress like that
public static class RegisterDataEngineForPost extends AsyncTask<MultipartEntity, integer, String>{
ProgressBar ProgressBarUpload;
public void setmCurrentPhotoPath(ProgressBarUploadb) {
ProgressBarUpload = ProgressBarUploadb;
}
#Override
protected void onProgressUpdate(integer... values) {
}
#Override
protected void onPreExecute() {
ProgressBarUpload.setProgress(0);
}
#Override
protected String doInBackground(MultipartEntity... params) {
//do some task and update the progress
publishProgress(progress_value);
}
#Override
protected void onPostExecute(String result) {
}
}
}

Categories

Resources