not able to check AsyncTask result - android

I have a problem that I am not able to check the value of AsyncTask result in order to start new activity if the result is desirable.
Here is my onPostExecute method:
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(LoginActivity.this, s, Toast.LENGTH_SHORT).show();
}
It toasts string value from php file and it has two possible values, "You are successfully logged in" or "Incorrect email or password". Everything is working fine until I want to check what the toasted message is, because if login is successfull I need to start a new activity.
This is how I tried to do that:
public void onClick(View v) {
AttemptLogin login = new AttemptLogin();
try {
String res = login.execute("http://10.0.2.2/loginApp.php").get();
if (res.equals("You are successfully logged in"))
startActivity(new Intent(LoginActivity.this,ConnectActivity.class));
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
I am totally confused because when I toast res, I get the desirable message, so the problem is with this line,if (res.equals("You are successfully logged in")). The app behaves like this line doesn't exist at all.
I also tried with if(AsyncTask.getStatus() == FINISHED) and then to check AsyncTask result but it didn't help.
I really don't have idea what is going on, can anyone please help me with this?

AsyncTask has OnPostExecute and OnPreExecute methods.
Both of them can call items, variables and methods as if they were normal methods.
So in your onPostExecute you can easily check the result and start your activity using this:
#Override
protected void onPostExecute(String s) {
super.onPostExecute();
try {
if (s.equals("You are successfully logged in")){
Intent i = new Intent(LoginActivity.this,ConnectActivity.class);
startActivity(i);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Toast.makeText(LoginActivity.this, s, Toast.LENGTH_SHORT).show();
}

Related

using method inside asyntask in android

i have created one simple login application which takes user name and password from sqlserver..it works fine...
i want during login process one progeress bar should be displayed using asyntask...
but i am unaware to use parameters in asyntask...if some one plzz tell me how to put my method in doInbackground of asyntask and what param should i use....
my code is;.....
public void save(){
initilize();
ResultSet rs = null;
String mylog=id.getText().toString();
String mypass=pass.getText().toString();
try{
Statement statement=connect.createStatement();
rs=statement.executeQuery("LOGIN '"+mylog+"', '"+mypass+"'");
}catch(Exception e){
e.printStackTrace();
}
if(mylog.equals("")||mypass.equals("")){
Toast.makeText(getApplicationContext(), "empty fields", Toast.LENGTH_SHORT).show();
} else
try {
if(rs.next()){
Intent i=new Intent(getApplicationContext(),Act2.class);
startActivity(i);
}
else if(rs.next()==false){
Toast.makeText(getApplicationContext(), "incorrect login", Toast.LENGTH_SHORT).show();
id.setText("");
pass.setText("");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if it is possible that same method save() be kept inside doInbackground() of asyntask...
making a fast refactorization (note that this as it stand it's really bad practice and coding, you MUST refactor this code to be more maintanable and to avoid duplication):
public class MyAsyncTask extends AsyncTask<> {
private Activity activity;
boolean result;
private String myLog;
private String myPass;
private Connection connect;
public MyAsyncTask(Activity activity, Connection connect) {
this.activity = activity;
this.connect = connect;
}
#Override
protected void onPreExecute() {
//show your progress dialog
}
#Override
protected Object doInBackground(Object[] objects) {
ResultSet rs = null;
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
initilize();
mylog=id.getText().toString();
mypass=pass.getText().toString();
}
});
try{
Statement statement=connect.createStatement();
rs=statement.executeQuery("LOGIN '"+mylog+"', '"+mypass+"'");
}catch(Exception e){
e.printStackTrace();
}
if(mylog.equals("")||mypass.equals("")){
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(activity.getApplicationContext(), "empty fields", Toast.LENGTH_SHORT).show();
}
});
} else
try {
if(rs.next()){
result = true;
}
else if(rs.next()==false){
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(activity.getApplicationContext(), "incorrect login", Toast.LENGTH_SHORT).show();
id.setText("");
pass.setText("");
}
});
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Object o) {
//hide your progress dialog
if(result == Boolean.TRUE){
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Intent i=new Intent(activity.getApplicationContext(),Act2.class);
activity.startActivity(i);
}
});
}
}
}
then in your Activity you do this:
MyAsyncTask a = new MyAsyncTask(this, connect); //im guessing "connect" is your Connection object
a.execute();
As i said i made this fast refactoring for the code to work but best practice and good implementation is not in consideration here.
Maybe, you could use a timer, to check if your
login is ready. As long as it is not, you Show your progress Bar. If its ready, you can close the Bar and start a new activity or anything. timers run can run on u UI thread.
regards :)

AsyncTask in onDestroy() not being executed

I want to send logout information to server, when the app gets destroyed.
Here's the code:
#Override
protected void onDestroy() {
try {
Log.i("myApp", "Activity destroyed");
SharedPreferences prefs1 = getSharedPreferences("com.my.app", Context.MODE_PRIVATE);
Log.i("myApp", "step1");
String response;
Log.i("myApp", "step2");
response = HttpPOSTer.logout(EventCodes.LOGOUT, LOGOUT_EVENTCODE, prefs.getString("sessionID", "null"));
Log.i("myApp", "step3");
if (response.equals("logout")) {
Log.i("myApp", "logged out succesfully");
} else {
Log.i("myApp", "couldn't perform logout");
}
prefs1.edit().clear().commit();
}
catch (InterruptedException e) {
e.printStackTrace();
}
catch (ExecutionException e) {
e.printStackTrace();
}
super.onDestroy();
}
But here's the log, when I close the app from home button's long click menu:
I can't even debug here. I place breakpoint, but it never gets fired while debugging.
Is there any reason, why AsyncTask doesn't get called from onDestroy()?
its not a good idea to use asyntask in onDestroy() instead you can have an activity that extends IntentService and give a call to that activity from onDestroy

Android Thread Join

in my code I have a code inside a thread that first tries to update something from Database and if the update is not successful then an insert is tried. My problem is that this code is called twice (it's not ok I know but let's ignore this for now) and because of this the insert is called twice because the update is not finished (at least this is what I think). I searched on google I thought to use thread.join(). My question is if it's ok to use thread.join() in my case.
Thanks
public void persistChangesToDatabase() {
final Thread backThread = new Thread(new Runnable() {
#Override
public void run() {
try {
openDataBase();
<-- SOME CODE -->
//First, an UPDATE is tried
int rowsAffected = updateTable();
// If update fails an INSERT is tried
if (rowsAffected == 0) {
//Insert
insert();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
});
backThread.start();
try {
backThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

using AsyncTask for implementing Logout functionality for Facebook using Facebook SDK

I want to create an application which uses Facebook SDK to log on to the facebook.
I was successful to implement login functionality using the same. (I would also like to mention i am using deprecated functions, i will switch over to further things later, i would like to first fix the problems that i am encountering here).
But I got problems in implementing Logout functionality. I made my research and found out that I need to implement network functionality in AsyncTasks for better performance. So, should I implement this functionality using AsyncTask? following is my code.
Please suggest any corrections required and also further readings and articles to clear my basic concepts. I am new to Android and facing problems in understanding AsyncTasks.
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.fb_button:
try{
if(fb.isSessionValid())
{
new myAsyncClass().doInBackground(fb);
//button close session
}
else
{
fb.authorize(LoginPage.this, new DialogListener(){
#Override
public void onFacebookError(FacebookError e)
{
Toast.makeText(LoginPage.this, "on Facebook error", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(DialogError e)
{
Toast.makeText(LoginPage.this, "on error", Toast.LENGTH_SHORT).show();
}
#Override
public void onComplete(Bundle values)
{
update_fb_buttonimage();
Toast.makeText(getBaseContext(), "onComplete works",Toast.LENGTH_LONG).show();
}
#Override
public void onCancel()
{
}
});
//login in to facebook
}
}catch(Exception e){
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
}
my asynctask class is as follows....
private class myAsyncClass extends AsyncTask<Facebook, Void, Void>{
protected void onPreExecute() {
// update the UI immediately after the task is executed
super.onPreExecute();
}
#Override
protected Void doInBackground(Facebook... arg0) {
// TODO Auto-generated method stub
Facebook fb=arg0[0];
try {
fb.logout(getApplicationContext());
update_fb_buttonimage();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
So in my switch case if session is invalid and i click on my button i get logged on to facebook without any problem
and also my view (button) also gets updated.
but when session is valid, i get the famous exception
android.os.networkonmainthreadexception
where should I place my
new myAsyncClass().doInBackground(fb);
please suggest me!! I am totally stuck up.
You do not call the doInBackground()directly while calling an AsyncTask.
You simply execute() the AsyncTask and it follows a certain sequence of execution as onPreExecute(), doInBackground(), onProgressUpdate() and onPostExecute().
So, instead of calling doInBackground(), you should be calling execute().
if(fb.isSessionValid())
{
new myAsyncClass().execute(fb);
}
OnClick on button which logout but this
new myAsyncClass().doInBackground(fb);

Using of Toast with thread in android

progressDialog = ProgressDialog.show(GetResponse.this, "", "Loading...");
new Thread()
{
public void run()
{
try
{
// inside i have written code for making connection to the server using SSL connection.
}catch (Exception e)
{
progressDialog.dismiss();
exception(e.getMessage())
}.start();
}
private void exception(String msg)
{
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
this.finish();
Intent i = new Intent(getBaseContext(), LoginPage.class);
startActivity(i);
}
my LoginPage.java is previous activity.
If the connection is successfull it goes to the next activity ot doesnt give any error,
But if der is any prob with connection then i want progress bar should be stopped and go back to the LoginPage activity and also i want the error msg to be displayed.
From the above im getting some error.. Please help me out on this
Pass in and use the context from LoginPage. Also, use the 101010 button to format your code as code in your posts.
you can go up by using try catch mechanism where in your catch place your toast message and u can do it also by asynchronous task,
here simple code
private class Task_News_ArticleView extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(
Bru_Sports_View.this);
// can use UI thread here
protected void onPreExecute() {
this.dialog.setMessage("Loading...");
this.dialog.setCancelable(false);
this.dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
//here the condition to check login details
}
} catch (Exception e) {
}
return null;
}
protected void onPostExecute(Void result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
}
and u can also use try,catch in catch block you can place your toast message
with finsih() method

Categories

Resources