Call global variable before it is set using AsyncTask - android

Okay, this has me confused once again. I am trying to either A: set a golbal variable, which i can do or B: retieve a variable from my AsyncTask. I have set can set the golbal variable from asynctask which is fine, but the activity calls it before it is set with the asynctask.
So therefore I need the application to finsh the AsyncTask before calling the golbal variable.
new createUser().execute();
Log.i("res", "After: " + Boolean.toString(MyProperties.getInstance().valut));
private class createUser extends AsyncTask<Void, Void, Boolean> {
ProgressDialog dialog = ProgressDialog.show(MainActivity.this, "",
"Creating User...", true);
Toast toast = Toast.makeText(getApplicationContext(), "",
Toast.LENGTH_SHORT);
#Override
protected Boolean doInBackground(Void... params) {
// TODO Auto-generated method stub
if (db.createUser(nameU.getText().toString(), userU.getText()
.toString(), emailU.getText().toString(), passU.getText()
.toString()) == false) {
return false;
} else {
return true;
}
}
protected void onPreExecute() {
dialog.show();
}
protected void onPostExecute(Boolean result) {
dialog.dismiss();
if (!result) {
toast.setText("User already exists!");
toast.show();
res = result;
MyProperties.getInstance().valut = res;
Log.i("res", Boolean.toString(MyProperties.getInstance().valut));
} else {
toast.setText("Success");
toast.show();
res = result;
MyProperties.getInstance().valut = res;
Log.i("res", Boolean.toString(MyProperties.getInstance().valut));
}
}
}

Work with your global variable in onPostExecute method of your AsyncTask. You need to implement it in your AsyncTask's child. This method is called then all work is done.
EDIT
private class createUser extends AsyncTask<Void, Void, Boolean> {
ProgressDialog dialog;
#Override
protected Boolean doInBackground(Void... params) {
// TODO Auto-generated method stub
if (db.createUser(nameU.getText().toString(), userU.getText()
.toString(), emailU.getText().toString(), passU.getText()
.toString()) == false) {
return false;
} else {
return true;
}
}
protected void onPreExecute() {
dialog = ProgressDialog.show(MainActivity.this, "", "Creating User...", true);
dialog.show();
}
protected void onPostExecute(Boolean result) {
dialog.dismiss();
Toast.makeText(
getApplicationContext(),
result?"Success":"User already exists!",
Toast.LENGTH_SHORT).show();
MyProperties.getInstance().valut = result
Log.i("res", Boolean.toString(MyProperties.getInstance().valut));
}
}

Two issues:
Java does not really have any global variables. The closest it has are static class variables. Since you haven't shown your declared variable, I can't say what you've really implemented.
Every AsyncTask has a onPostExecute(..) method you can override that runs in the original thread/Looper after doInBackground(..) has completed. Override this to do things like Update the UI thread.

Related

onPostExecute is not getting called after successful completion of doinbackground

I have used Async Task many times but I am facing this type of problem for the first time. I searched Stack Overflow but couldn't find any useful solution.
My issue is onPostExecute is not getting called in Async task, All operations that are in doinbackground are completed but control is not reaching the onPostExecute... not able to understand the reason.
Code:
public class deletedaily extends AsyncTask<Void , Void, long[]>{
ProgressDialog pd;
long resultdelete;
protected void onPreExecute(){
pd=new ProgressDialog(StockDetail.this);
if(pd!=null){
pd.setMessage("Deleting data.....please wait");
pd.show();
}
}
protected long[] doInBackground(Void... params) {
// TODO Auto-generated method stub
try{
Database.getInstance(getApplicationContext()).getWritableDatabase().beginTransaction();
resultdelete = Database.getInstance(getApplicationContext()).getWritableDatabase().delete(st.tablename, st.column2 + "=? AND " + st.column3 + "=?", new String[] {getdailydate.toString(),stockname} );
Database.getInstance(getApplicationContext()).getWritableDatabase().setTransactionSuccessful();
new popdailydata().execute(); //here calling list view to populate after deletion
}
catch(Exception dailydeleteerror){}
finally{
Database.getInstance(getApplicationContext()).getWritableDatabase().endTransaction();
}
return new long[] {resultdelete};
}
protected void onPostExecute(long result){
System.out.println("postexecute entered");
if(pd!=null){
pd.dismiss();
}
if(result!=-1){
Toast.makeText(getApplicationContext(),"Date deleted from your portfolio", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(),"Failed to delete ....try again", Toast.LENGTH_LONG).show();
}
}
}
Edit
I am calling from onclick of Image buton
deletedailydata.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new deletedaily().execute();
}
});
It should be onPostExecute(long [] result).
You extended your class like AsyncTask<Void , Void, long[]>. This means that the return value of doInBackground will be long[] and the parameter of onPostExecute also. As what you get in onPostExecute is the result returned by doInBackgroud the type should be the same.

AsyncTask HttpParams

Could anyone help me on following questions.
1) onPostExecute - Toast.make while in background i am sending HttpRequest.
0nCraeteBunle - execute() ; startNewActivity
showing error. AsycTask# Runtime Exception .
While commenting Http request in background, no error is showed.
here, how can i know that http Request and reply finished , so that i can start my new Activity.
2) how to get HttpParams. Sending from TIBCO BE (As event with properties)
3) What if i am recieving JSONObject, JAVAObject, Integer other than String in onPostExecute. unable to override .
Try this,
protected class GetTask extends AsyncTask<Void, Void, Integer> {
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(MainActivity.this,
"Loading", "Please wait");
}
#Override
protected Integer doInBackground(Void... params) {
// TODO Auto-generated method stub
//call ur HttpRequest
httpRequest();
return 0;
}
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
mHandler.sendEmptyMessage(0);
}
}
Handler mHandler = new Handler() {
public void handleMessage(Message Msg) {
if (Flag) {
//Add ur stuff
}else{
}
And then in ur method set Flag value
public void httpRequest() {
// TODO Auto-generated method stub
String URL ="ADD UR URL";
try {
JSONObject ResponseObject = mAPIService.CallAPI(
YourActivity.this, URL);
String status = ResponseObject.getString("status");
Flag = true;
} catch (Exception err) {
Flag = false;
}
}

How to Handle networkonmainthreadexception in Android?

I have following 2 class
class CallNetworkMethod extends AsyncTask<Void, Void, Void>
{
#Override
protected Void doInBackground(Void... params) {
if (TwitterUtils.isAuthenticated(prefs)) {
sendTweet();
} else {
Intent i = new Intent(getApplicationContext(), TwPrepareRequestTokenActivity.class);
i.putExtra("tweet_msg",getTweetMsg());
startActivity(i);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//updateLoginStatus();
loginStatus.setText("Logged into Twitter : " + TwitterUtils.isAuthenticated(prefs));
}
}
====================================================
public class TwitterUtils {
static ArrayList<String> friens=null;
public static boolean isAuthenticated(SharedPreferences prefs) {
String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
AccessToken a = new AccessToken(token,secret);
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(TwConstants.CONSUMER_KEY, TwConstants.CONSUMER_SECRET);
twitter.setOAuthAccessToken(a);
try {
**twitter.getAccountSettings();**
return true;
} catch (TwitterException e) {
return false;
}
}
}
I got the exception when running this code(networkonmainthreadexception).I debug this code and found the location where exception come out. It is twitter.getAccountSettings(); .I think this method should run inside a AsynTask but i dont know how to do that.
Currently you are calling TwitterUtils.isAuthenticated(prefs) in onPostExecute because onPostExecute always execute on UI thread then you are getting networkonmainthreadexception exception .
to avoid this issue use a Boolean Flag to get return from doInBackground and show it in TextView in onPostExecute as:
class CallNetworkMethod extends AsyncTask<Void, Void, Void>
{
public static boolean status=false;
#Override
protected Void doInBackground(Void... params) {
status=TwitterUtils.isAuthenticated(prefs);
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//updateLoginStatus();
loginStatus.setText("Logged into Twitter : " + status);
}
}
the problem is that you're using the AsyncTask wrong.
The idea for the onBackground returning a value and the onPostExecute receiving a result is to pass to the UI thread something that was done on the background thread.
Something like that:
change the class CallNetworkMethod extends AsyncTask<Void, Void, Void> to
class CallNetworkMethod extends AsyncTask<Void, Void, Boolean>
change the protected Void doInBackground(Void... params) { to
protected Boolean doInBackground(Void... params) {
Boolean result = TwitterUtils.isAuthenticated(prefs);
if (result) {
sendTweet();
} else {
Intent i = new Intent(getApplicationContext(), TwPrepareRequestTokenActivity.class);
i.putExtra("tweet_msg",getTweetMsg());
startActivity(i);
}
return result;
}
and change the protected void onPostExecute(Void result) { to
protected void onPostExecute(Boolean result) {
loginStatus.setText("Logged into Twitter : " + result.toString());
}
Note that this method blocks waiting for a network response, so do not call it in a UI thread.
This is what is suggested when using:
facebook.request("me");
Same might be the case with:
twitter.getAccountSettings();
So, just like other Network connections, which you call using AsyncTasks, call this in some AsyncTask.
Okay, the Error might be here:
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//updateLoginStatus();
loginStatus.setText("Logged into Twitter : " + TwitterUtils.isAuthenticated(prefs));
}
You are calling TwitterUtils.isAuthenticated(prefs) in onPostExecute();
Your first call to isAuthenticated() is correctly placed in the AsyncTask. However, when you use:
loginStatus.setText("Logged into Twitter : " + TwitterUtils.isAuthenticated(prefs));
in your onPostExecute(), you're calling a networking method on the UI thread again, as onPostExecute() is run on the UI thread.
Remove this line, or store the result locally from doInBackground() and use it here.

ProgressBar does not show immediately in android

I have a base class of an activity and a sub class which extends the base class. The superclass has a async task to perform some action. I call this by running it on the ui thread since otherwise it throws an IllegalInitializerError:
superclass.this.runOnUiThread(new Runnable() {
public void run() {
String p="";
try {
p=new asynctasker().execute().get();
}
}
}
In my async task:
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
//showDialog();
Log.d("Now","Inside right now");
dialog = ProgressDialog.show(class_create_event.this, "Loading1", "Please Wait");
}
However the dialog is displayed almost at the end of the request. The I am in part is printed correctly. I know that something is blocking my ui thread. But if I dont call the async task from the UI thread it throws an illegal initializer error. Is there any way out?
You don't need to have UIthread for calling AsyncTask
Call it like this way
FetchRSSFeeds async = new FetchRSSFeeds();
async.execute();
private class FetchRSSFeeds extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog = new ProgressDialog(HomeActivity.this);
/** progress dialog to show user that the backup is processing. */
/** application context. */
protected void onPreExecute() {
this.dialog.setMessage(getResources().getString(
R.string.Loading_String));
this.dialog.show();
}
protected Boolean doInBackground(final String... args) {
try {
// Fetch the RSS Feeds from URL
// do background process
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) {
// Setting data to list adaptar
setListData();
}
}
}

app crashes when implementing async Android

I'm trying to implement async on Android but it keeps crashing my app, the code in doInBackground works if I put it in the oncreate so that i know that It works
any help is greatly appreciated
thanks
here's my code :
public class accueilEco extends Activity
{
String[] param = new String[5];
TextView nom;
TextView prenom;
ProgressDialog mDialog;
Context ctxt;
TelephonyManager tm;
connectEco ce;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
nom = (TextView) findViewById(R.id.user);
ctxt = getBaseContext();
tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
new chargerParam().execute();
}
public class chargerParam extends AsyncTask<Void, Void, Void> {
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(Void... params) {
try
{
ce =new connectEco();
param = ce.recupereParam(tm.getDeviceId());
if(String.valueOf(param[4]) == String.valueOf(1))
{
Toast.makeText(ctxt, "Paramétres chargées" , Toast.LENGTH_LONG).show();
//setContentView(R.layout.home);
nom.setText(param[1]+" "+ param[2]+" - "+param[3]);
}
else
{
Toast.makeText(ctxt, "=> login" , Toast.LENGTH_LONG).show();
}
}
catch(Exception ex)
{
Toast.makeText(ctxt, "erreur" , Toast.LENGTH_LONG).show();
}
return null;
}
}
}
You cannot access UI objects from another thread than the UI thread. The code:
nom.setText(param[1]+" "+ param[2]+" - "+param[3]);
will throw the exception.
You can access the UI elements when you are in onPreExecute() or onPostExecute(Result). Accessing UI elements while youre in doInBackground, it'll result in exception.
To "fix" this you need to read through and understand the AsyncTask implementation. Instead of declaring your background task by AsyncTask<Void, Void, Void> you can provide an "result type" that the can be posted from the doInBackground method to the onPostExecute method (on the UI thread). AsyncTask<Void, Void, String> (the String type).
You would have to do something like this:
#Override
protected void onPostExecute(String result) {
if (result != null)
nom.setText(result);
// else show toast
}
#Override
protected String doInBackground(Void... params) {
try {
String[] param = new connectEco().recupereParam(tm.getDeviceId());
if (String.valueOf(param[4]) == String.valueOf(1))
return param[1]+" "+ param[2]+" - "+param[3];
} catch(Exception ex) {
// ignore and return null
}
return null;
}

Categories

Resources