i try this Tutorial
i still confused how to add progress dialog in button logout with asynctask
here is my activity.
package hariff.ltis.mainmenu;
import hariff.ltis.inputhama.CInputHamaApp;
import hariff.ltis.library.DatabaseHandler;
import hariff.ltis.library.UserFunctions;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import hariff.ltis.mainmenu.R;
public class MainMenu extends Activity{
UserFunctions userFunctions;
Button btnLogout;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
userFunctions = new UserFunctions();
if(userFunctions.isUserLoggedIn(getApplicationContext())){
setContentView(R.layout.main);
btnLogout = (Button) findViewById(R.id.btnLogout);
btnLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
userFunctions.logoutUser(getApplicationContext());
Intent login = new Intent(getApplicationContext(), LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
});
loadUser();
View button3Click = findViewById(R.id.button3);
button3Click.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
// Perform action on click
DataHama();
}
});
}else{
// user is not logged in show login screen
Intent login = new Intent(getApplicationContext(), LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
}
/*private void InputData(){
Intent i = new Intent(this, SaveData.class);
startActivity(i);
}
private void CheckData(){
Intent i1 = new Intent(this, CheckData.class);
startActivity(i1);
}*/
private void loadUser() {
TextView txt = (TextView) findViewById(R.id.textUser);
// database handler
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
// Spinner Drop down elements
SQLiteDatabase dbs = db.getReadableDatabase();
Cursor cursor = dbs.rawQuery("SELECT * FROM login", null);
if (cursor.moveToFirst()) {
do {
String emailid=cursor.getString(2); // Here you can get data from table and stored in string if it has only one string.
txt.setText(emailid);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
if(db!=null)
{
db.close();
}
// Creating adapter for spinner
}
private void DataHama(){
Intent i2 = new Intent(this, CInputHamaApp.class);
startActivity(i2);
}
}
so when i click button logout, the progress dialog show and have a time, example 5 second. how to do that?
the button logout EDIT :
btnLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
logoutUserOperation loguttask = new logoutUserOperation(MainMenu.this);
loguttask.execute("");
}
});
here is the logoutUser function
/**
* Function to logout user
* Reset Database
* */
public boolean logoutUser(Context context){
DatabaseHandler db = new DatabaseHandler(context);
db.resetTables();
return true;
}
EDIT: here is the asynctask
private class logoutUserOperation extends AsyncTask<String, Void, Boolean> {
ProgressDialog progressDialog;
Context context;
public logoutUserOperation(Context context){
this.context=context;
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(context, "", "Logout...");
}
#Override
protected Boolean doInBackground(String... params) {
boolean boollogout=userFunctions.logoutUser(context);
return boollogout;
}
#Override
protected void onPostExecute(Boolean result) {
progressDialog.dismiss();
if(result){
Intent login = new Intent(context,LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(login);
// Closing dashboard screen
context.finish();
}else{
// your code here...
}
}
}
when i try but show error
The method finish() is undefined for the type Context
BR
Alex
EDIT : this is the code to sleep 5 second
protected Boolean doInBackground(String... params) {
boolean boollogout=userFunctions.logoutUser(context);
try{
Thread.sleep( 5000 );
} catch( Exception e ){
Log.i("Logout", e.getMessage() );
}
return boollogout;
}
you can show ProgressDialog on button click using AsyncTask as:
private class logoutUserOperation extends AsyncTask<String, Void, Boolean> {
ProgressDialog progressDialog;
Context context;
public logoutUserOperation(Context context){
this.context=context;
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(context, "", "Logout...");
}
#Override
protected boolean doInBackground(String... params) {
boolean boollogout=userFunctions.logoutUser(context);
return boollogout;
}
#Override
protected void onPostExecute(boolean result) {
progressDialog.dismiss();
if(result){
Intent login = new Intent(context,
LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(login);
// Closing dashboard screen
context.finish();
}else{
// your code here...
}
}
}
and start AsyncTask as on button click :
btnLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
logoutUserOperation loguttask = new logoutUserOperation(MainMenu.this);
loguttask.execute("");
}
});
Related
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class Second extends AppCompatActivity {
TextView t1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
t1 = (TextView)findViewById(R.id.textView);
Bundle b = getIntent().getExtras();
String S = b.getString("key1");
t1.setText(S);
try {
wait(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Intent i2 = new Intent();
i2.putExtra("reply","Everything is cool");
setResult(RESULT_OK,i2);
finish();
}
}
This is my second Activity code. Actually, I was seeing how intent works by implementing a very basic program. Program is working without wait, but the app is crashing if I put wait function. provide me some way so that i can stay on to the second activity for a longer time before sending back the r
Use Handler and try to start Intent from run() You can check below example,
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent i2 = new Intent();
i2.putExtra("reply","Everything is cool");
setResult(RESULT_OK,i2);
finish();
}
}, 3000);
you can use service or acyncTask instead of
try {
wait(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
You could try this code
public void onclick(View v) {
mt = new MyTask();
mt.execute();
}
class MyTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
Hope it will be helpful.
When i tried to run the code, only main toast is running. Progress Dialog and other toast message is not running.This program is simple async example for sleeping process.The main issue is that it is not showing the Progressdialog.
Did i need to add xml file(it contain only a textView and a Button).
Please help me to solve this.Thank You
package com.example.asyncexample;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
public class MainActivity extends Activity {
ProgressDialog progressBar;
int prorgessInc = 1; // incrementing the progress dialog
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.start_button);
button.setOnClickListener(startTaskListener);
}
private OnClickListener startTaskListener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Context context = getApplicationContext();
progressBar = new ProgressDialog(v.getContext());
BackgroundTask test = new BackgroundTask();
test.execute(context);
CharSequence text = "Main Thread is Running";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
};
private class BackgroundTask extends AsyncTask<Context, Integer, String>{
protected void OnPreExecute() {
CharSequence msg = "BackgroundTask is Operating";
progressBar.setCancelable(true);
progressBar.setMessage(msg);
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setProgress(0);
progressBar.setMax(100);
progressBar.show();
}
#Override
protected String doInBackground(Context... params) {
//BackgroundTask Is Running
for(int i =0; i<=100; i+=prorgessInc){
try {Thread.sleep(100);}
catch (InterruptedException e) { e.printStackTrace();}
publishProgress(prorgessInc);
if(isCancelled()) break;
}
return getString(R.string.backgndcompld);
}
protected void OnProgressUpdate(Integer...values ) {
//Update Progress bar
progressBar.incrementProgressBy(prorgessInc);
}
protected void PostExecute(String result){
//Dissmiss progressbar
progressBar.dismiss();
Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
Toast toast2 = Toast.makeText(context, result, duration);
toast2.show();
}
}
}
Right, your problem is in your method naming for the AsyncTask.
You have defined:
protected void OnPreExecute()
protected void OnProgressUpdate()
protected void PostExecute()
However the real methods are:
protected void onPreExecute()
protected void onProgressUpdate()
protected void onPostExecute()
Note the difference in case. If you had used the #Override as below your IDE would likely have shown you that.
I have done some cleaning of that and other parts of your code. Take a look:
public class MainActivity
extends Activity
implements View.OnClickListener
{
private Button button;
private ProgressDialog progressBar;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main_example);
button = (Button) findViewById(R.id.start_button);
button.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
Log.d("click", "start button clicked, starting task");
BackgroundTask test = new BackgroundTask();
test.execute();
}
private class BackgroundTask
extends AsyncTask<Void, Integer, String>
{
int PROGRESS_INCREMENT = 1;
int PROGRESS_MAX = 100;
String DIALOG_MSG = "AsyncTask is Operating";
#Override
protected void onPreExecute()
{
progressBar = new ProgressDialog(getApplicationContext());
progressBar.setCancelable(true);
progressBar.setMessage(DIALOG_MSG);
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setProgress(0);
progressBar.setMax(PROGRESS_MAX);
progressBar.show();
}
#Override
protected String doInBackground(Void... params)
{
for (int i = 0; i <= 100; i += PROGRESS_INCREMENT)
{
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
publishProgress(PROGRESS_INCREMENT);
if (this.isCancelled())
{
break;
}
}
return "[some result text]";
}
#Override
protected void onProgressUpdate(Integer... values)
{
progressBar.incrementProgressBy(PROGRESS_INCREMENT);
}
#Override
protected void onPostExecute(String result)
{
progressBar.dismiss();
Toast.makeText(getApplicationContext(),
result,
Toast.LENGTH_LONG)
.show();
}
}
}
Notable changes:
Activity implements View.OnClickListener so you can move your onClick() method to your Activity eliminating the anonymous inner class.
Button moved to a class level scope. Defining it in your listener could be error prone.
prepare and display your PrgressDialog from the onPreExecute() method. That's what it's for.
Cleaned up your Toast. No need to use all those variables and waste space with useless objects.
Instead of Toast messages use the built in Log for debug messages. Toast messages can very quickly begin to spam your screen and because of the display lengths are very inaccurate for knowing when things happen.
am able to sucessfully get data from the server.if data is success then am navigating NextScreen.1. if backbutton pressed when getting data then AsyncTask Dialog disappear, but after sometime it navigates to Nextscreen activity. so if i press backbuttob asyn task has to cancel and it should not navigate to next activity.
public class Screenone extends Activity {
EditText user,pass;
Button login;
InputStream is;
String productResponse;
EditText edit;
int responseCode;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.mainlog);
user = (EditText) findViewById(R.id.user);
pass = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.login);
}
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if ((user.getText().length() > 0)
&& (pass.getText().length() > 0) ) {
new Load().execute(Status);
}
}
});
}
private class Load extends AsyncTask<String, String, String> {
private ProgressDialog Dialog = new ProgressDialog(LoginScreen.this);
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
Dialog.setMessage("Please wait...");
Dialog.show();
}
protected String doInBackground(String... status) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost("---url---");
responseCode =httpResponse.getStatusLine().getStatusCode();
}
catch (Exception e) {
}
return null;
}
protected void onPostExecute(String Result) {
// TODO Auto-generated method stub
super.onPostExecute(Result);
if (responseCode==200) {
Dialog.dismiss();
Intent intent =new Intent(Screenone.this, NextScreen.class);
startActivity(intent);
}
}
}
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
moveTaskToBack(true);
}
}
OK the problem is that you have no reference to your asynctask. Try creating a property in your Activity for the asynctask:
private Load myAsyncTask;
now in your onClick method:
myAsyncTask=new Load();
myAsyncTask.execute(Status);
and finally in your onBackPressed:
public void onBackPressed() {
super...
if(myAsyncTask!=null)
myAsyncTask.cancel(true);
}
you will need to Cancel AsyncTask, dismiss ProgressDialog and also abort HttpPost before moving back from current Activity . try it as :
#Override
public void onBackPressed() {
if(Load!=null){
if(!Load.getStatus() == AsyncTask.Status.FINISHED){
// first abort Httppost request
// post.abort();
httpclient.getConnectionManager().shutdown();
// now dismiss ProgressDialog
if (Dialog!=null&&Dialog.isShowing()) {
Dialog.dismiss();
}
// now cancel AsyncTask if running
if(Load.getStatus() == AsyncTask.Status.RUNNING){
Load.cancel(true);
}
}
}
}
am able to sucessfully get data from the server.if data is success then it navigates to NextScreen.
1. if i press back button before data is appeared then Asyntask has to disappear and it should not navigates to NextScreen.it has to stay in Screenone only.
but if i press backbutton dailog disappearing after some few seconds it navigating to the NextScreen.so how to stop this.
public class Screenone extends Activity {
EditText user,pass;
Button login;
InputStream is;
String productResponse;
EditText edit;
int responseCode;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.mainlog);
user = (EditText) findViewById(R.id.user);
pass = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.login);
}
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if ((user.getText().length() > 0)
&& (pass.getText().length() > 0) ) {
new Load().execute(Status);
}
}
});
}
private class Load extends AsyncTask<String, String, String> {
private ProgressDialog Dialog = new ProgressDialog(LoginScreen.this);
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
Dialog.setMessage("Please wait...");
Dialog.show();
}
protected String doInBackground(String... status) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost("---url---");
responseCode =httpResponse.getStatusLine().getStatusCode();
}
catch (Exception e) {
}
return null;
}
protected void onPostExecute(String Result) {
// TODO Auto-generated method stub
super.onPostExecute(Result);
if (responseCode==200) {
Dialog.dismiss();
Intent intent =new Intent(Screenone.this, NextScreen.class);
startActivity(intent);
}
}
}
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
LoginScreen.Load xx = new LoginScreen().new Load();
if(new Load()!=null){
if(!(new Load().getStatus() == AsyncTask.Status.FINISHED)){
httpclient.getConnectionManager().shutdown();
if (xx.Dialog!=null&&xx.Dialog.isShowing()) {
xx.Dialog.dismiss();
}
if(new Load().getStatus() == AsyncTask.Status.RUNNING){
new Load().cancel(true);
}
}
}
}
}
you will need to start next Activity on Back Button Click after AsyncTask canceled as :
if(new Load().getStatus() == AsyncTask.Status.RUNNING){
new Load().cancel(true);
// start Next Activity here...
Intent intent =new Intent(Screenone.this, NextScreen.class);
startActivity(intent);
}
My app have a splash activity
It must display at least 5 seconds
But in this activity I have another thread to sync data from internet
Sync process may take more than 5 seconds or less than 5 second.
If less than 5 seconds, the Handler should wait until fifth second
If more then 5 seconds, the Handler should wait until process complete
How to make the Handler wait another thread?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
syncFromInternet(); // another thread may over 5 seconds
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent;
intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent);
}
}, 5000);
}
You have to make just simple logic Like
When handler completes then check for completion of syncFromInternet method, if it completed open main Activity
When syncFromInternet completes then check for completion of handler, if it completed open main Activity.
Above explanation in code:
boolean isHandlerCompleted = false, isAsyncCompleted = false;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
isHandlerCompleted = true;
if (isHandlerCompleted && isAsyncCompleted) {
openMainActivity();// both thread completed
}
}
}, 5000);
// in your async task add this condition when it completes its task
isAsyncCompleted = true;
if (isHandlerCompleted && isAsyncCompleted) {
openMainActivity();// both thread completed
} // till this line
// make this function to open main activity
openMainActivity() {
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent);
}
You can use an AsyncTask instance and measure the time for syncing with the remote server. If the time is greater than 5 minutes, start the new activity, otherwise - wait till the 5th second:
#Override
protected void onCreate(Bundle savedInstanceState) {
...
AsyncTask<Void, Void, Void> asyncTask = new AsyncTask<Void, Void, Void>() {
private static final long FIVE_SECONDS = 5 * 1000;
private volatile Date mStartTime;
#Override
protected void onPreExecute() {
mStartTime = new Date();
}
#Override
protected Void doInBackground(Void... params) {
// Do the syncing here
syncFromInternet();
Date now = new Date();
long execTime = now.getTime() - mStartTime.getTime();
if(execTime < FIVE_SECONDS) {
Thread.sleep(FIVE_SECONDS - execTime);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
Intent intent = new Intent(...);
startActivity(intent);
finish();
}
};
asyncTask.execute(null, null);
}
You can use this code :
package com.example.untitled;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import java.io.File;
import java.io.IOException;
public class MyActivity extends Activity {
private volatile boolean isAvailable = false;
private volatile boolean isOver = false;
private Handler messageHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 0:
if (isOver) {
Log.e("messageHandler","isOver");
transitToNewActivity();
}else {
Log.e("messageHandler","isOver false");
}
break;
}
}
};
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
syncFromInternet(); // another thread may over 5 seconds
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
isOver = true;
Log.e("mainHandler", "Main handler expired");
if (isAvailable) {
transitToNewActivity();
Log.e("mainHandler", "isAvailable");
}else {
Log.e("mainHandler","isAvailable false");
}
}
}, 50000);
public void transitToNewActivity() {
Log.e("transitToNewActivity","Activity transited");
Intent intent;
intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent);
}
public void syncFromInternet() {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(80000);
isAvailable = true;
messageHandler.sendEmptyMessage(0);
Log.e("syncFromInternet", "internet data synced");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
}
}
and please modify it according to your requirement.
you should implement AsyncTask so that this will wait untill your syncFromInternet() is completed.
private class BackgroundSplashTask extends AsyncTask {
#Override
protected void onPreExecute() {
super.onPreExecute();
// show progressbar
}
#Override
protected Object doInBackground(Object[] params) {
try {
syncFromInternet(); // sync in background
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
// dismiss progressbar
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent); // go to SecondActivity after syncFromInternet is completed
finish();
}
}
Call your handler inside syncFromInternet() after execution of thread.