I have generic async task class which fetches response from server . And i receive those response by using get method . Now i knw that UI thread is block when i use get method , bcoz of which my progress Dialog doesnt showup on time .
Now can someone tell me alternative to do this ?? (In every case i need to send back the response to the activity which has made the call of execute so opening new activity wouldn't help me )
Code :
AsyncTask Class
public class GetDataFromNetwork extends AsyncTask<Void,String,Object> {
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}
protected Object doInBackground(Void... params) {
Object result = null;
try {
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER10);
new MarshalBase64().register(envelope);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(ipAddress + webService);
System.setProperty("http.keepAlive", "true");
try {
androidHttpTransport.call(nameSpace + methodName, envelope);
} catch (Exception e) {
e.printStackTrace();
publishProgress(e.getMessage());
}
androidHttpTransport.debug = true;
System.out.println("response: " + androidHttpTransport.requestDump);
result = envelope.getResponse();
if(result!=null){
System.out.println("GetDataFromNetwork.doInBackground() result expection---------"+result);
}
} catch (Exception e) {
System.out.println("GetDataFromNetwork.doInBackground()-------- Errors");
e.printStackTrace();
}
return result;
}
protected void onPostExecute(Object result) {
super.onPostExecute(result);
progressDialog.dismiss();
}
Code : Activity
GetDataFromNetwork request = new GetDataFromNetwork(
this,
ProgressDialog.STYLE_SPINNER,
getResources().getText(R.string.autenticate).toString());
response= (SoapObject)request.execute().get();
I'm doing stuff like this all the time in my apps and the easiest way I found was to create "Callback" interface and pass it as a parameter to my "AsyncTask"s. You do your "doInBackground()" processing and when it's finished you call the "Callback" instance from onPostExecute passing the "result" object as parameter.
Below is a very simplified version of it.
Example of Callback interface:
package example.app;
public interface Callback {
void run(Object result);
}
Example of AsyncTask using the Callback interface above:
public class GetDataFromNetwork extends AsyncTask<Void,String,Object> {
Callback callback;
public GetDataFromNetwork(Callback callback){
this.callback = callback;
}
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}
protected Object doInBackground(Void... params) {
Object result = null;
// do your stuff here
return result;
}
protected void onPostExecute(Object result) {
callback.run(result);
progressDialog.dismiss();
}
}
Example of how to use the classes above in your app:
class Example {
public onCreate(Bundle savedInstanceState){
//initialize
GetDataFromNetwork request = new GetDataFromNetwork(new Callback(){
public void run(Object result){
//do something here with the result
}});
request.execute();
}
}
Like yorkw says, The problem is that you make the UI thread wait for the response with this code:
response= (SoapObject)request.execute().get();
As the documentation for AsyncTask.get() says:
Waits if necessary for the computation to complete, and then retrieves
its result.
Since the UI thread waits for the response, it can't show a progress dialog. The solution is to move the code that handles the response to the onPostExecute() method:
protected void onPostExecute(Object result) {
super.onPostExecute(result);
// Now we have the response, dismiss the dialog and handle the response
progressDialog.dismiss();
response = (SoapObject) result;
}
This method will be invoked after you have the response. Meanwhile, the UI thread can take care of showing a progress dialog.
Why don't create another class in which you will put response and in there you will have get and set method. Then in onPostExecute you write it with set method and call a handler where you will do whatever you want...This is just an idea... :)
If you are using the AsyncTask, your UI thread won't be blocked. Are you downloading your data inside doInBackground() ? Because that is where you should be doing it.
Related
I'm trying to implement a basic login screen for an android app. The flow is as follows:
1) User enters login information and hits submit
2) A LoginRequest which extends AsyncTask is created and executed.
3) The doInBackground will fire some http calls to validate the user credentials
4) The onPostExecute should be getting called to set the loginResults
5) Ui thread sees the login results and continues accordingly.
I'm been simplifying the code to get to the root issue but haven't had any luck so far. Here is the simplified code that still repros the issue.
Inside my activity:
private void tryLogin(String email, String password)
{
this.showProgress(true);
LoginHelper loginHelper = new LoginHelper();
LoginResult result = loginHelper.tryLogin(email, password);
this.showProgress(false);
}
This gets called from my submit buttons on click listener.
Inside LoginHelper:
TestClass test = new TestClass();
public LoginResult tryLogin(String mobileNumber, String password, int deviceId)
{
String loginUrl = "...";
new LoginRequest(test).execute(loginUrl);
while (test.result == null)
{
try {
Thread.sleep(1000);
}
catch (Exception e)
{
//...
}
}
return test.result;
}
This will execute the AsyncTask and wait for the result being continuing.
LoginRequest:
public class LoginRequest extends AsyncTask<String, Void, LoginResult>
TestClass test;
public LoginRequest(TestClass test)
{
this.test = test;
}
#Override
protected LoginResult doInBackground(String... params) {
LoginResult ret = null;
ret = new LoginResult(1,"test");
return ret;
}
#Override
protected void onPostExecute(LoginResult result) {
this.test.result = result;
}
}
I run this through the debugger with breakpoints inside the doInBackground and onPostExecute. The doInBackground executes correctly and returns the LoginResult value, but the onPostExecute breakpoint never gets hit, and my code will wait in the while loop in LoginHelper.
You are basically checking the whole time the variable 'result' of your LoginRequest. But that's not, how AsyncTask works.
From Docs:
AsyncTask allows you to perform asynchronous work on your user
interface. It performs the blocking operations in a worker thread and
then publishes the results on the UI thread, without requiring you to
handle threads and/or handlers yourself.
You can do your work in doInBackground() method and the publish you results in onPostExecute().
onPostExecute runs on UI Thread, to allow you change elements, show the result or whatever you want to do. Your problem is, that you are the whole time blocking the UI Thread with your checking method in tryLogin()
So how to solve it?
Remove the checking method:
public void tryLogin(String mobileNumber, String password, int deviceId)
{
// Starts AsynTasks, handle results there
String loginUrl = "...";
new LoginRequest().execute(loginUrl);
}
in AsyncTask:
public class LoginRequest extends AsyncTask<String, Void, LoginResult>
// Removed Constructor, if you need to pass some other variables, add it again
#Override
protected LoginResult doInBackground(String... params) {
// TODO: Change this to actual Http Request
LoginResult ret = null;
ret = new LoginResult(1, "test");
return ret;
}
#Override
protected void onPostExecute(LoginResult result) {
// Now the result arrived!
// TODO: Use the result
}
}
More Thoughts:
You probably want to store user credentials. If so, make sure the are safe. Link
You might want, depending on results, change some UI. Here's an example:
AsyncTask:
public class LoginRequest extends AsyncTask
private Activity activity;
// Constructor
public LoginRequest(Activity activity) {
this.activity = activity;
}
#Override
protected LoginResult doInBackground(String... params) {
// TODO: Change this to actual Http Request
LoginResult ret = null;
ret = new LoginResult(1, "test");
return ret;
}
#Override
protected void onPostExecute(LoginResult result) {
ActivityLogin acLogin = (ActivityLogin) activity;
if(result.equals("ok")) {
Button loginButton = (Button) acLogin.findViewById(R.id.login-button);
loginButton.setBackgroundColor(Color.GREEN);
//Finish LoginActivity
acLogin.finish();
}
else {
//TODO: Fail Handling
}
}
}
And the start it like this:
new LoginRequest(loginActivity).execute(loginUrl);
I didnt tested the code.
It's AsyncTask so it's calling the LoginRequest and while(test.result) at the same time. You got stuck in the while loop because test.result is not done returning yet. test.result is done in onPostExecute(), so if you move that while loop in that function it will work and onPostExecute() will get called. One way to solve this problem is to implement a callback interface. Put the while loop in the overrided callback method.
refer to my answer here: how to send ArrayList(Bitmap) from asyncTask to Fragment and use it in Arrayadapter
Try This
public class LoginRequest extends AsyncTask<String, Void, LoginResult>
{
TestClass test;
LoginResult ret = null;
public LoginRequest(TestClass test)
{
this.test = test;
}
#Override
protected Boolean doInBackground(String... params) {
ret = new LoginResult(1,"test");
return true;
}
#Override
protected void onPostExecute(Boolean success) {
if(success)
this.test.result = result;
}
}
Temporary solution : You can add this.test.result = result; in the doInbackground() method.
#Override
protected LoginResult doInBackground(String... params) {
LoginResult ret = null;
ret = new LoginResult(1, "test");
this.test.result = result;
return ret;
}
Please post full code to get proper solution.
Hi onCancel of dialog i want to cancel to server call but i m facing problem that even i cancel the task, it hits my server and modifies the data. How can I resolve this issue ? Below is my code..
private class UserBoardingTask extends AsyncTask {
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage(getResources().getString(R.string.please_wait));
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(true);
progressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
if (userOnBoardingTask!= null && userOnBoardingTask.getStatus() != AsyncTask.Status.FINISHED && !userOnBoardingTask.isCancelled()) {
userOnBoardingTask.cancel(true);
}
}
});
progressDialog.show();
}
#Override
protected Void doInBackground(String... urls) {
String boardingURL=null;
boardingURL= getUrl();
UserOnBoardingDTO userOnBoardingDetailsDTO = AppStateManager.getUserBoardingDetails();
try{
RestAPIManager.putToNSWebService(boardingURL, userOnBoardingDetailsDTO, username, password);
}
catch (Exception e) {
errorMessage=getResources().getString(R.string.unknown_exp);
}
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
closeProgressDialog();
errorMessage="";
AppStateManager.setUserBoardingDetails(null);
userOnBoardingTask=null;
}
#Override
protected void onPostExecute(Void res) {
closeProgressDialog();
userOnBoardingTask=null;
if(!FieldsValidator.isBlank(errorMessage)){
CommonUtil.showToast(getActivity(),errorMessage);
errorMessage="";
return;
}
Just check isCancelled() once in a while:
protected Object doInBackground(Object... x) {
while (/* condition */) {
// work...
if (isCancelled()) break;
}
return null;
}
and another solution is
protected void onProgressUpdate(String... progress1) {
if(condition){
break;
}
}
Move the dialog out of the async task and only start the task when the dialog is not canceled.
Actually the problem is not termination of your asynsTask but the server hit if a server hit is already done before termination of asynsTask then you must interrupt your server request also.Just terminate your server request using abort method.
Where is userOnBoardingTask declared and where it is assigned to a reference to running task? I suspect this does not store a proper reference when the task tries to cancel it.
I am not sure if it is the actual reason of your problem. But for sure you may get rid of this variable if it is intended to pint at current task. Just change dialog's on cancel listener:
private class UserBoardingTask extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
// ...
progressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
if (UserBoardingTask.this.getStatus() != AsyncTask.Status.FINISHED
&& UserBoardingTask.this.isCancelled()) {
UserBoardingTask.this.cancel(true);
}
}
});
In fact you may omit UserBoardingTask.this phrase as the inner class can point directly fields of nesting class as far as the names are not obscured by the names of inner class members:
private class UserBoardingTask extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
// ...
progressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
if (getStatus() != AsyncTask.Status.FINISHED && isCancelled()) {
cancel(true);
}
}
});
EDIT
Another point is that before sending request to the server you may check inside doInBackground you may check if the task has not been cancelled
// ...
#Override
protected Void doInBackground(String... urls) {
// ...
try {
if(isCancelled()) {
throw new Exception("Exit: task cancelled!");
}
RestAPIManager.putToNSWebService(boardingURL, userOnBoardingDetailsDTO, username, password);
// ...
RestAPIManager.putToNSWebService(boardingURL, userOnBoardingDetailsDTO, username, password);
This above code hit the server. So you have to validate the execution of code inbetween cancellation.
Try something like this
try{
if(!userOnBoardingTask.isCancelled())
{
RestAPIManager.putToNSWebService(boardingURL, userOnBoardingDetailsDTO, username, password);
}
}
catch (Exception e) {
errorMessage=getResources().getString(R.string.unknown_exp);
}
This is ok. If user cancel the task before ResetAPIManager code executes. Suppose user try to cancel the task after server call initiated you have to tell already modified or remodify server data or unable to cancel or some message to user. All done through getting server reponse and validate server response if it changed or not.
Use something like this
Var rsponse = RestAPIManager.putToNSWebService(boardingURL,userOnBoardingDetailsDTO, username, password);
Validate the reponse message in onPostExecute() or OnCancelled() method.
If you cancel the asynctask after access this method
RestAPIManager.putToNSWebService(boardingURL,userOnBoardingDetailsDTO, username, password); the async task will cancel after running the above code so you should correct this by creating a new method inside RestAPIManager class and call that method inside OnCancelled method from your asyncTask.
Short Anser: Its not possible stop data posts thru a simple cancel. once an async task runs even if you cancel it mid way data posts will occure. Cancellation can be done in a Simple Run
Check this Post
[Android - Cancel AsyncTask Forcefully
I have an app that makes numerous RESTful service calls. I execute the calls in a class extending Asynctask. If I have to cancel the asynctask, I also want to cancel the service call. Unfortunately, cancelling the async operation still allows doInBackground to complete and I can't call isCancelled() once the request is waiting for a response (which can take a little bit). Right now, from within my doInBackground method I'm registering to be notified from the UI thread if a cancel request is made, so I can abort the HttpResponse object. Here is a piece of sample code.
It has worked so far, but can I really count on it, or am I just getting lucky? Can you count on one thread to call a method in another thread?
public class AsyncTestActivity extends Activity {
private ArrayList<IStopRequestMonitor> monitors;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
}
public void stopActivity() {
if (monitors == null || monitors.size() < 1) return;
for (int i = 0; i < monitors.size(); i++) {
monitors.get(i).stopRequest();
}
}
public void addListener(IStopRequestMonitor listener) {
if (monitors == null) monitors = new ArrayList<IStopRequestMonitor>();
monitors.add(listener);
}
public void readWebpage(View view) {
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://www.mywebsite.com/feeds/rsstest.xml" });
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
DefaultHttpClient client = new DefaultHttpClient();
final HttpGet httpGet = new HttpGet(urls[0]);
addListener(new IStopRequestMonitor() {
public void stopRequest() {
if (httpGet == null) return;
httpGet.abort();
cancel(true);
}
});
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
// handle inputstream
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
#Override
protected void onPostExecute(String result) {
Log.d("Result:", result);
}
}
interface IStopRequestMonitor {
public void stopRequest();
}
}
There is still a race here. If stopActivity() runs before the background thread has called addListener(), the listener will get added later and will never be called to abort the HttpGet.
If you are going to call cancel() from the UI thread (or whatever thread you create the AsyncTask on), you can:
Create a 'private HttpGet httpGet' field in your AsyncTask.
Override onPreExecute() and initialize httpGet there.
Override onCancel() and say 'if (httpGet != null) { httpGet.abort() }'
In doInBackground(), return immediately if isCancelled(), otherwise run.
Because this initializes httpGet on the UI thread, a cancel() call will either run before execute() (and therefore doInBackground will see isCancelled() return true), or it will run after httpGet exists and therefore the HttpGet will be aborted.
You don't need the listeners unless you are using that for something else.
you can define global object of asynctask class and using obj.cancle() method call on button click or whenever you need.
i am using AsyncTask class in my first activity its work fine
and call second and i am call another AsyncTask call object in onCreate
and call the webservice in doInBackground
then its give exception
android.os.networkmainthread.
i am not getting any idea as
i am new to android development
so please show me some sample or i show you my code
this is my code
public class panel extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.panel);
User_Balance_Load Balance_load=new User_Balance_Load();
Balance_load.execute();
Toast.makeText(getBaseContext(),Cls_Constant.username, Toast.LENGTH_LONG).show();
}
class User_Balance_Load extends AsyncTask<Void, Void, Void>
{
private final ProgressDialog dialog = new ProgressDialog(panel.this);
protected void onPreExecute() {
this.dialog.setMessage("Loding Diet type...");
this.dialog.show();
}
protected Void doInBackground(final Void... unused) {
// TODO Auto-generated method stub
panel.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Update_balance();
}
});
return null;
}
protected void onPostExecute(Void result)
{
if (this.dialog.isShowing())
{
this.dialog.dismiss();
}
}
}
void Update_balance()
{
Vector result;
result=Cls_webservice.User_Balance(Cls_Constant.Guid);
if(result.size()>0)
{
String UserBalance=result.elementAt(2).toString();
TextView Tv_User_balacne=(TextView)findViewById(R.id.tv_point_balance);
Tv_User_balacne.setText(UserBalance);
}
}
And this is my class of webservice
public class Cls_webservice {
public static Vector User_Balance(String id)
{
Vector _vector = new Vector();
final String userid = id;
final String METHOD_NAME = "WCFDatatableRes";
final String SOAP_ACTION = "http://tempuri.org/WCFDatatableRes";
final String NAMESPACE = "http://tempuri.org/";
final String URL = "http://xxxxxxxx.com/GameRoom/ANDROIDLOTT/WebService.asmx";
String return_val="";
SoapObject newob;
try
{
Object response;
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.encodingStyle = SoapEnvelope.ENC;
SoapObject Request = new SoapObject(NAMESPACE , METHOD_NAME);
Request.addProperty("Params", userid+",3");
Request.addProperty("Do", "Balance");
envelope.dotNet = true;
envelope.setOutputSoapObject(Request);
AndroidHttpTransport httptransport ;
httptransport = new AndroidHttpTransport(URL);
httptransport.debug=true;
try
{
httptransport.call(SOAP_ACTION,envelope);
response = envelope.getResponse();
newob = (SoapObject)envelope.bodyIn;
return_val = newob.toString();
SoapObject diettype_listResult = (SoapObject) newob.getProperty("WCFDatatableRes ") ;
SoapObject diffgram = (SoapObject) diettype_listResult.getProperty("diffgram") ;
}
catch (Exception e) {
System.out.println("error:" + e);
}
}
catch (Exception e) {
}
return _vector;
}
}
The exception come in this line -> "httptransport.call(SOAP_ACTION,envelope);
so please help me
and this same code work in
my first activity
i don't know why in second come error
thanks
NetworkOnMainThread Exception occurs because you are running a network related operation on the UI Thread. This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged. See the document Designing for Responsiveness.
Your are running Update_balance() by using runonUithread.
You are attempting to update ui on in doInBackground() by calling Update_balance() which sets the text in textview as below. You should not update ui in doInBackground().
TextView Tv_User_balacne=(TextView)findViewById(R.id.tv_point_balance);
Tv_User_balacne.setText(UserBalance);TextView Tv_User_balacne=(TextView)findViewById(R.id.tv_point_balance);
Tv_User_balacne.setText(UserBalance);
All your network related operations should be done in doInBackground(). Make your webservice call in doInBackground().
You can return value from doInBackground() retrieve it in onPostExecute() and update ui accordingly.
class TheTask extends AsyncTask<Void,Void,Void>
{
protected void onPreExecute()
{ super.onPreExecute();
//display progressdialog.
}
protected void doInBackground(Void ...params)//return result here
{
//http request. do not update ui here
//call webservice
//return result here
return null;
}
protected void onPostExecute(Void result)//result of doInBackground is passed a parameter
{
super.onPostExecute(result);
//dismiss progressdialog.
//update ui using the result returned form doInbackground()
}
}
The 4 steps
When an asynchronous task is executed, the task goes through 4 steps:
onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
For more details please check the link below
http://developer.android.com/reference/android/os/AsyncTask.html
You're using an asynctask and then in your asynctask you're running code under the UI thread. That is nonsense, since the result is the same as executing the code on the OnCreate() method.
protected Void doInBackground(final Void... unused)
{
Vector result = Update_balance();
panel.this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
if(result.size()>0)
{
String UserBalance=result.elementAt(2).toString();
TextView Tv_User_balacne=(TextView)findViewById(R.id.tv_point_balance);
Tv_User_balacne.setText(UserBalance);
}
}
});
return null;
}
Vector Update_balance()
{
Vector result;
result=Cls_webservice.User_Balance(Cls_Constant.Guid);
return result;
}
Hello
I'm loading Tweets from a user account to show in a listview. Now I want to let the users know what's going on while they're waiting. I've implementend Async Task, but for some reason, onPostExcecute is never called. That's why the dialog is never removed.
Can someone give me a hint.. What am I doing wrong?
I can post my TweetAdapterClass if that's needed
This is my AsyncClass
public class ProgressTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
dialog.setTitle("Even geduld...");
dialog.setMessage("De tweets worden ingeladen...");
dialog.show();
}
protected void onPostExecute() {
try {
if (dialog.isShowing()) {
adaptor = new TweetListAdaptor(MainActivity.this, R.layout.tweetitem, loadTweets());
setListAdapter(adaptor);
dialog.dismiss();
}
} catch (Exception e) {
}
}
#Override
protected Void doInBackground(Void... arg0) {
return null;
}
}
LoadTweets looks like this:
private ArrayList<Tweets> loadTweets() {
ArrayList<Tweets> tweets = new ArrayList<Tweets>();
try {
HttpClient hc = new DefaultHttpClient();
HttpGet get = new HttpGet(
"http://search.twitter.com/search.json?q=JobXXL_be&rpp=10");
// HttpGet get = new
// HttpGet("http://search.twitter.com/search.json?q=Stijn_messiaen&rp=10");
HttpResponse rp = hc.execute(get);
if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String result = EntityUtils.toString(rp.getEntity());
JSONObject root = new JSONObject(result);
JSONArray sessions = root.getJSONArray("results");
for (int i = 0; i < sessions.length(); i++) {
JSONObject session = sessions.getJSONObject(i);
Tweets tweet = new Tweets();
tweet.setTweet(session.getString("text"));
tweet.setUser(session.getString("from_user"));
// datum vertalen
String date = session.getString("created_at").substring(5,
16);
String[] arrDate = date.split(" ");
int id = this.getResources().getIdentifier(
arrDate[1].toString(), "string",
this.getPackageName());
String maand = getResources().getString(id);
date = arrDate[0].toString() + " " + maand + " "
+ arrDate[2].toString();
tweet.setDate(date);
tweets.add(tweet);
}
}
} catch (Exception e) {
Log.e("TwitterFeedActivity", "Error loading JSON", e);
}
return tweets;
}
EDIT: I added my LoadTweets() in my doInBackgroundMethod and that solved my problems!
Try declaring the ProgressDialog dialog in the main class in which your AsyncTask class exists and only call the dialog.show and dialog.dismiss method in the AsyncTask class.
Use onCreateDialog(int id) in activity to create ProgressDialog. In AsyncTask call:
MainActivity.this.showDialog(PROGRESS_DIALOG_ID);
To dismiss:
MainActivity.this.dismissDialog(PROGRESS_DIALOG_ID);
Dialogs are connected with activity's context. When activity is recreated dialog should be recreated too but then instance of the dialog is not the same.
I had the same problems and yeah this happened to me when onPostExecute didn't match the declaration... try something like protected Void onPostExecute(Void... arg0)
Next thing to do is to put Log.d("Your app", "Location of this code"); and check which part doesn't execute on Log file ...
Hope u will find the solution...
onPostExecute() does not match the declaration Void. I am on the road so off the top of my head consider:
protected void onPostExecute(Void result)
More here.
Hmm, two things come to mind here..
1) Why is your onPostExecute not overridden like the onPreExecute and doInBackground?
2) Why is the doInBackground after the onPost Execute? Generally the order is
onPreExecute
doInBackground
onPostExecute