I want to implement a sign up activity where user insert his/her information then click a button to send this information to web service which stored this information in a database.
I put the code for connecting to web service in a separated Thread (Not in UI Thread), and I want to display a progressdialog until the connection to web service finish, then I want to display an AlertDialog to display different messages like(this email is used try different one , or Sign up successes!)
here is the which excuse when user click sign up button :
public void SignupNewUser (View V)
{
Working = ProgressDialog.show(this, "Working..", "Connecting To Server");
Runnable work = new Runnable() {
#Override
public void run() {
Edit_Text_FName = (EditText) findViewById(R.id.Edit_Text_Fname_Signup);
Edit_Text_LName = (EditText) findViewById(R.id.Edit_Text_Lname_Signup);
Edit_Text_Password = (EditText) findViewById(R.id.Edit_Text_Password_Signup);
Edit_Text_Email = (EditText) findViewById(R.id.Edit_Text_Email_Signup);
S1 = (Spinner) findViewById(R.id.Spinner_Signup);
SignupPerson SUPerson = new SignupPerson();
SUPerson.F_Name = Edit_Text_FName.getText().toString().trim();
SUPerson.L_Name = Edit_Text_LName.getText().toString().trim();
SUPerson.E_Mail = Edit_Text_Email.getText().toString().trim();
SUPerson.PassW = Edit_Text_Password.getText().toString().trim();
SUPerson.Gen = Choosen_Gender;
SUPerson.Cou_Id = S1.getSelectedItemPosition();
METHOD = "signup";
SoapObject Request = new SoapObject(NAMESPACE, METHOD);
PropertyInfo P = new PropertyInfo();
P.setName("SUPerson");
P.setValue(SUPerson);
P.setType(SUPerson.getClass());
Request.addProperty(P);
SoapSerializationEnvelope envolope = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER11);
envolope.dotNet = true;
envolope.setOutputSoapObject(Request);
envolope.addMapping(NAMESPACE, "SignupPerson", new SignupPerson().getClass());
HttpTransportSE ahttp = new HttpTransportSE(URL);
SoapPrimitive Res = null;
try
{
ahttp.call(NAMESPACE+METHOD, envolope);
Res = (SoapPrimitive) envolope.getResponse();
}
catch (Exception ex)
{
//ex.printStackTrace();
result = -1;
}
if (result != -1)
{
result = Integer.parseInt(Res.toString());
}
Working.dismiss();
}
};
Thread SS = new Thread(work);
SS.start();
switch (result)
{
case -1:
showDialog(-1);
break;
case 0:
showDialog(0);
break;
case 1:
showDialog(1);
break;
case 2:
showDialog(2);
break;
default:break;
}
}
#Override
protected Dialog onCreateDialog(int id)
{
switch (id)
{
case -1:
return new AlertDialog.Builder(this)
.setTitle("error!")
.setMessage("error connecting to the server. please try again")
.setIcon(R.drawable.ic_error)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
})
.create();
case 0:
return new AlertDialog.Builder(this)
.setTitle("error!")
.setMessage("You have entered an Exists Email, Please try another one")
.setIcon(R.drawable.ic_error)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
}).create();
case 1:
return new AlertDialog.Builder(this)
.setTitle("error!")
.setMessage("Server Error, Please Try Again Later")
.setIcon(R.drawable.ic_error)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
})
.create();
case 2:
return new AlertDialog.Builder(this)
.setTitle("Registration successfully!")
.setMessage("Click OK to Sign in and Start Usign Hello!!")
.setIcon(R.drawable.ic_success)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
Intent i = new Intent(SignupActivity.this ,MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
})
.create();
}
return null;
}
here , SUPerson is an object which hold user information, and result is an integer which indicate which AlertDialog will display after connection to web service end.
my question is that when I run the above code ,, No Alert Dialog message appear !
why ?
If you use an AsyncTask you will have a much easier time doing this. I think you might not be getting your dialog because you're trying to show it immediately after starting the thread.
With the AsyncTask, you can have your server connection running in doInBackground() on a separate thread and then you can have your dialog called in onPostExecute().
Let me know if that makes sense! The link is pretty clear on how to use it. :)
Edit: I also wanted to mention, if you use the AsyncTask, it allows you to easily set up a ProgressDialog in the onProgressUpdate() method.
Related
hiiii following is my login code
public class Login extends ActionBarActivity {
// flag for Internet connection status
Boolean isInternetPresent = false;
String shareduid;
// Connection detector class
ConnectionDetector cd;
ImageView imgview;
EditText uname;
EditText pass;
Button create,login;
TextView trouble;
public static final String MyPREFERENCES = "MyPrefs";
public static String userid = null;
SharedPreferences sharedpreferences;
private static final String TAG = "myAppSurun";
//private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
//End Drawer
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
String otpkey,vrfy;
// url to get all products list
private static String url_all_login = "http://xxx/xxx/xxxx/xxx";
//Globalstring
String username =null;
String password = null;
//Global Variable for login state checking
public boolean loginflag = false;
// RelativeLayout relativeLayout=new RelativeLayout(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
cd = new ConnectionDetector(getApplicationContext());
imgview=(ImageView)findViewById(R.id.imageView2);
uname=(EditText)findViewById(R.id.edituser);
pass=(EditText)findViewById(R.id.editpassword);
create=(Button)findViewById(R.id.create);
login=(Button)findViewById(R.id.Login);
trouble=(TextView)findViewById(R.id.trouble_login);
getSupportActionBar().setTitle("Surun Support");
ColorDrawable(Color.parseColor("#F58634")));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
ActionBar bar = getSupportActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#F58634")));
//Click Text Animation
final Animation myanim, imganim;
myanim = AnimationUtils.loadAnimation(this, R.anim.link_text_anim);
imganim = AnimationUtils.loadAnimation(this, R.anim.rotate);
uname.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
validation.isValid(uname, "^[_a-zA-Z]+(\\.[_a-zA-Z 0-9-]+)*#[a-zA-Z]+(\\.[a-zA-Z]+)*(\\.[a-zA-Z]{2,})$", "Invalid UserName", true);
}
});
pass.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
validation.isValid(pass, "[0-9]{10}", "Invalid Mobile No", true);
}
});
//end of initializing component
create.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Create Click", Toast.LENGTH_LONG).show();
Intent i = new Intent(getApplicationContext(), Registration_user.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
});//End of On click for button
//starting font settings this has prone to error try catch is mandatory while setting font(Overriding native font interface).
try {
Typeface myTypeface = Typeface.createFromAsset(this.getAssets(), "fonts/robotoregular.ttf");
create.setTypeface(myTypeface);
} catch (Exception e) {
Log.v(TAG, "Exception " + e);
}
//End of font settings
//Initializing shared preferences
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
//load preferences if exist
Log.v(TAG,""+sharedpreferences);
Log.v(TAG,"Preference is present loading it");
String shareduser = sharedpreferences.getString("User", "");
String sharedpass = sharedpreferences.getString("Password", "");
shareduid = sharedpreferences.getString("userid", "");
String sharedotp = sharedpreferences.getString("otp", "");
String sharedvrfy = sharedpreferences.getString("verified", "");
Log.v(TAG,"uid"+shareduser);
Log.v(TAG,"otp"+sharedpass);
Log.v(TAG,"vrfy"+sharedvrfy);
if ((shareduser.length() > 0) && (sharedpass.length() > 0)) {
//Navigating to main page
Log.v(TAG,"navigate to main");
Intent i = new Intent(getApplicationContext(), UserLogedIn.class);
i.putExtra("user", shareduser);
i.putExtra("pass", sharedpass);
i.putExtra("userid", shareduid);
i.putExtra("otpkey",sharedotp);
i.putExtra("vrfy", sharedvrfy);
//Starting An Activity
startActivity(i);
finish();
} else {
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// get Internet status
isInternetPresent = cd.isConnectingToInternet();
// check for Internet status
if (isInternetPresent) {
if (uname.getText().length() <= 0 || pass.getText().length() <= 0) {
AlertDialog alertDialog = new AlertDialog.Builder(Login.this).create();
// Setting Dialog Title
alertDialog.setTitle("Alert Dialog");
// Setting Dialog Message
alertDialog.setMessage("All Fields Are Mandatory");
// Setting Icon to Dialog
// alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "Please Enter Correct User Name And Password", Toast.LENGTH_SHORT).show();
}
});
// Showing Alert Message
alertDialog.show();
if (pass.getText().length() > 10) {
Toast toast1 = Toast.makeText(getApplicationContext(), "Four Characters Only...", Toast.LENGTH_SHORT);
toast1.show();
trouble.setVisibility(View.VISIBLE);
//Log.v(TAG,"Not Valid");
}
} else if (pass.getText().length() > 10) {
AlertDialog alertDialog = new AlertDialog.Builder(Login.this).create();
// Setting Dialog Title
alertDialog.setTitle("Alert Dialog");
// Setting Dialog Message
alertDialog.setMessage("Mobile no Must be 10 digit only ");
// Setting Icon to Dialog
// alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "Please Enter Correct User Name And Password", Toast.LENGTH_SHORT).show();
}
});
// Showing Alert Message
alertDialog.show();
} else if (!(validation.isValid(uname, "^[_a-zA-Z]+(\\.[_a-zA-Z0-9-]+)*#[a-zA-Z]+(\\.[a-zA-Z]+)*(\\.[a-zA-Z]{2,})$", "Invalid UserName", true))) {
AlertDialog alertDialog = new AlertDialog.Builder(Login.this).create();
// Setting Dialog Title
alertDialog.setTitle("Alert Dialog");
// Setting Dialog Message
alertDialog.setMessage("Email Is Incorrect");
// Setting Icon to Dialog
// alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "Email Id Is InCorrect", Toast.LENGTH_SHORT).show();
uname.requestFocus();
}
});
// Showing Alert Message
alertDialog.show();
} else {
//Animate Button load animation from anim/rotate.xml
imgview.startAnimation(imganim);
username = uname.getText().toString().toLowerCase();
password = pass.getText().toString();
//Sending Login Request To Server for validation Using Asynchronus Tasks where username and password as a parameter to method
Log.v(TAG, "Excuting check detail");
new CheckDetail().execute();
//Creating Shared Preferences
}//end of else_if fields are valid
}
else
{
AlertDialog alertDialog = new AlertDialog.Builder(Login.this).create();
// Setting Dialog Title
alertDialog.setTitle("Alert Dialog");
// Setting Dialog Message
alertDialog.setMessage("Internet is not active.Please Check Your NEtwork Setting");
// Setting Icon to Dialog
// alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "Internet Is Inactive", Toast.LENGTH_SHORT).show();
}
});
// Showing Alert Message
alertDialog.show();
}
}
});//End of On click for button
}//If no shared preferences found
}//End of onCreate function
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_admin_home, menu);
return true;
}//End of onCreateOptionMenu
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
//Remove Following Comment To Enable Drawer Toggling On Login Page
/*// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}*/
return super.onOptionsItemSelected(item);
}//End of onOptionItemSelected
//Alert Dialog when User Click Back Button
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//Handle the back button
if(keyCode == KeyEvent.KEYCODE_BACK) {
//Ask the user if they want to quit
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.quit)
.setMessage(R.string.really_quit)
.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Stop the activity
Login.this.finish();
}
})
.setNegativeButton("no", null)
.show();
return true;
}
else {
return super.onKeyDown(keyCode, event);
}
}//End of Alert Dialog Box
class CheckDetail extends AsyncTask<String,String, String> {
JSONArray datail=null;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Logging in. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
*/
protected String doInBackground(String... args) {
try {
Log.v(TAG, "In Do in Background");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", username));
params.add(new BasicNameValuePair("pwd", password));
// getting JSON string from URL
JSONObject json =jParser.makeHttpRequest(url_all_login, "POST", params);
//Object Parsing Failed here hence by using trail guide using JSONParser.alternateJSONArray to parse user data.
//Hence not using json instance of object using a BACKUP static variable of Parser class for proccessing.
//To use this backup utility theme the process should be standard and return unique or two out put only or ether way use three logical step
if(json != null) {
// As if login fails it returns object handling fail logic here.
//We can make it general by sending array from server side so we can only use alternateJSONArray variable
}
if(JSONParser.alternateJSONArray != null)
{
Log.v(TAG, "USING BACKUP ARRAY");
//Check your log cat for JSON futher details
for (int jsonArrayElementIndex=0; jsonArrayElementIndex < JSONParser.alternateJSONArray.length(); jsonArrayElementIndex++) {
JSONObject jsonObjectAtJsonArrayElementIndex = JSONParser.alternateJSONArray.getJSONObject(jsonArrayElementIndex);
userid=jsonObjectAtJsonArrayElementIndex.getString("u_id");
otpkey=jsonObjectAtJsonArrayElementIndex.getString("OTP");
vrfy=jsonObjectAtJsonArrayElementIndex.getString("is_verified");
Log.v(TAG,"" +userid);
Log.v(TAG,"" +otpkey);
Log.v(TAG,"" +vrfy);
if(jsonObjectAtJsonArrayElementIndex.getString("email").equals(username) && jsonObjectAtJsonArrayElementIndex.getString("mobile").equals(password))
{
Log.v(TAG,"Login Successful Now setting loginflag true");
loginflag = true;
}
}
}
else
{
loginflag=false;
}
} catch (Exception e) {
e.printStackTrace();
Log.v(TAG, "Exception at end :" + e.toString());
//Log.e("TAG", "Error......!RecoverIt");
}
return null ;
}
protected void onPostExecute(String result)
{
// dismiss the dialog after getting all products
//super.onPostExecute();
// pDialog.dismiss();
Log.v(TAG,"verification"+vrfy);
Log.v(TAG,"userid"+userid);
/* if(vrfy==false)
{
Intent i = new Intent(getApplicationContext(), Verifyotp.class);
i.putExtra("userid", userid);
i.putExtra("isverified", vrfy);
startActivity(i);
}else*/
if(loginflag==true) {
Log.v(TAG, "Executing Shared Preferences...");
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("User", uname.getText().toString());
editor.putString("Password", pass.getText().toString());
Log.v(TAG, "Userid==================" + userid);
Log.v(TAG, "otpkey==============" + otpkey);
Log.v(TAG, "is verified " + vrfy);
editor.putString("userid", userid);
editor.putString("otp", otpkey);
editor.putString("vrfy", vrfy);
editor.commit();
Toast.makeText(getApplicationContext(), "Login Succeed", Toast.LENGTH_SHORT).show();
android.util.Log.v(TAG, "Login Succeed");
Intent i = new Intent(getApplicationContext(), UserLogedIn.class);
i.putExtra("user", shareduid);
Log.v(TAG, "" + userid);
startActivity(i);
finish();
}
else
{
Toast.makeText(getApplicationContext(),"Login failed,Invalid Details...!",Toast.LENGTH_LONG).show();
trouble.setVisibility(View.VISIBLE);
}
pDialog.dismiss();
}
}
i send userid from login.java to next activity but in other activity it doesnt receive that userid first time.at first time it display null but at other places it show/print userid correctely
if i restart app userid will be perfect and app will work fine
i dont know why it is happen at first time
code in other activity
Intent iin = getIntent();
Bundle b = iin.getExtras();
if (b != null) {
u_id = (String) b.get("userid");//first time it shows null but after restart it get correct value
Log.v(TAG, "userlogged in" + u_id);
}
because you sending null first time change below in your onpost method
Intent i = new Intent(getApplicationContext(), UserLogedIn.class);
i.putExtra("user", shareduid);
Log.v(TAG, "" + userid);
startActivity(i);
in above shareduid is null first time you setting by shared preference so just put below
Intent i = new Intent(getApplicationContext(), UserLogedIn.class);
i.putExtra("user", userid);
Log.v(TAG, "" + userid);
startActivity(i);
check with this and let me know also i think check with key if you putextra with 'user' key you have to access with the same 'user' key
I have one problem I am writing code for login and logout using SharedPreferneces.
When i click logout it run perfectly and go back to login screen.
Now the problem is that when i logout and come on login screen at that time if i entered invalid detail then server give failed message and but login will success and go to next screen.
here is code
public class Login extends ActionBarActivity {
// flag for Internet connection status
Boolean isInternetPresent = false;
// Connection detector class
ConnectionDetector cd;
ImageView imgview;
EditText uname;
EditText pass;
Button create,login;
TextView trouble;
public static final String MyPREFERENCES = "MyPrefs";
SharedPreferences sharedpreferences;
private static final String TAG = "myAppSurun";
//Drawer
//private ListView mDrawerList;
//private DrawerLayout mDrawerLayout;
//private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
//End Drawer
//Asynchronous task variable
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
String userid,otpkey,vrfy;
// url to get all products list
private static String url_all_login = "http://xxx/xxx/xxx/xxx";
//Globalstring
String username =null;
String password = null;
//Global Variable for login state checking
public static boolean loginflag = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
cd = new ConnectionDetector(getApplicationContext());
imgview=(ImageView)findViewById(R.id.imageView2);
uname=(EditText)findViewById(R.id.edituser);
pass=(EditText)findViewById(R.id.editpassword);
create=(Button)findViewById(R.id.create);
login=(Button)findViewById(R.id.Login);
trouble=(TextView)findViewById(R.id.trouble_login);
getSupportActionBar().setTitle("Surun Support");
//getSupportActionBar().setDisplayShowHomeEnabled(true);
//getSupportActionBar().setLogo(R.drawable.dotlogo1);
//getSupportActionBar().setDisplayUseLogoEnabled(true);
//ActionBar bar = getSupportActionBar();
//bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#F58634")));
// Start Drawer Settings
//mDrawerList = (ListView) findViewById(R.id.navListlog);
//mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout_login);
//mActivityTitle = getTitle().toString();
//addDrawerItems();
//setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
ActionBar bar = getSupportActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#F58634")));
// End of Drawer Settings
//Click Text Animation
final Animation myanim, imganim;
myanim = AnimationUtils.loadAnimation(this, R.anim.link_text_anim);
imganim = AnimationUtils.loadAnimation(this, R.anim.rotate);
//End of animation
//Initialize the component
uname.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
validation.isValid(uname, "^[_a-z]+(\\.[_a-z0-9-]+)*#[a-z]+(\\.[a-z]+)*(\\.[a-z]{2,})$", "Invalid UserName", true);
}
});
pass.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
validation.isValid(pass, "[0-9]{10}", "Invalid Mobile No", true);
}
});
//end of initializing component
// Creating underlined text
// String udata = "Create Account";
//SpannableString content = new SpannableString(udata);
//content.setSpan(new UnderlineSpan(), 0, udata.length(), 0);
//create.setText(content);
//end of creating underlined text
//Toast.makeText(getApplicationContext(), "Create", Toast.LENGTH_LONG).show();
//Log.v("TEST", "TEST");
create.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Create Click", Toast.LENGTH_LONG).show();
Intent i = new Intent(getApplicationContext(), Registration_user.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
});//End of On click for button
//starting font settings this has prone to error try catch is mandatory while setting font(Overriding native font interface).
try {
Typeface myTypeface = Typeface.createFromAsset(this.getAssets(), "fonts/robotoregular.ttf");
create.setTypeface(myTypeface);
} catch (Exception e) {
Log.v(TAG, "Exception " + e);
}
//End of font settings
//Initializing shared preferences
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
//load preferences if exist
Log.v(TAG,""+sharedpreferences);
Log.v(TAG,"Preference is present loading it");
String shareduser = sharedpreferences.getString("User", "");
String sharedpass = sharedpreferences.getString("Password", "");
String shareduid = sharedpreferences.getString("userid", "");
String sharedotp = sharedpreferences.getString("otp", "");
String sharedvrfy = sharedpreferences.getString("verified", "");
Log.v(TAG,"uid"+shareduser);
Log.v(TAG,"otp"+sharedpass);
if ((shareduser.length() > 0) && (sharedpass.length() > 0)) {
//Navigating to main page
Log.v(TAG,"navigate to main");
Intent i = new Intent(getApplicationContext(), UserLogedIn.class);
i.putExtra("user", shareduser);
i.putExtra("pass", sharedpass);
i.putExtra("userid", shareduid);
i.putExtra("otpkey",sharedotp);
i.putExtra("vrfy", sharedvrfy);
//Starting An Activity
startActivity(i);
finish();
} else {
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// get Internet status
isInternetPresent = cd.isConnectingToInternet();
// check for Internet status
if (isInternetPresent) {
if (uname.getText().length() <= 0 || pass.getText().length() <= 0) {
AlertDialog alertDialog = new AlertDialog.Builder(Login.this).create();
// Setting Dialog Title
alertDialog.setTitle("Alert Dialog");
// Setting Dialog Message
alertDialog.setMessage("All Fields Are Mandatory");
// Setting Icon to Dialog
// alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "Please Enter Correct User Name And Password", Toast.LENGTH_SHORT).show();
}
});
// Showing Alert Message
alertDialog.show();
if (pass.getText().length() > 10) {
Toast toast1 = Toast.makeText(getApplicationContext(), "Four Characters Only...", Toast.LENGTH_SHORT);
toast1.show();
trouble.setVisibility(View.VISIBLE);
//Log.v(TAG,"Not Valid");
}
} else if (pass.getText().length() > 10) {
AlertDialog alertDialog = new AlertDialog.Builder(Login.this).create();
// Setting Dialog Title
alertDialog.setTitle("Alert Dialog");
// Setting Dialog Message
alertDialog.setMessage("Mobile no Must be 10 digit only ");
// Setting Icon to Dialog
// alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "Please Enter Correct User Name And Password", Toast.LENGTH_SHORT).show();
}
});
// Showing Alert Message
alertDialog.show();
} else if (!(validation.isValid(uname, "^[_a-z]+(\\.[_a-z0-9-]+)*#[a-z]+(\\.[a-z]+)*(\\.[a-z]{2,})$", "Invalid UserName", true))) {
AlertDialog alertDialog = new AlertDialog.Builder(Login.this).create();
// Setting Dialog Title
alertDialog.setTitle("Alert Dialog");
// Setting Dialog Message
alertDialog.setMessage("Email Is Incorrect");
// Setting Icon to Dialog
// alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "Email Id Is InCorrect", Toast.LENGTH_SHORT).show();
uname.requestFocus();
}
});
// Showing Alert Message
alertDialog.show();
} else {
//Animate Button load animation from anim/rotate.xml
imgview.startAnimation(imganim);
username = uname.getText().toString();
password = pass.getText().toString();
//Sending Login Request To Server for validation Using Asynchronus Tasks where username and password as a parameter to method
Log.v(TAG, "Excuting check detail");
new CheckDetail().execute();
//Creating Shared Preferences
}//end of else_if fields are valid
}
else
{
AlertDialog alertDialog = new AlertDialog.Builder(Login.this).create();
// Setting Dialog Title
alertDialog.setTitle("Alert Dialog");
// Setting Dialog Message
alertDialog.setMessage("Internet is not active.Please Check Your NEtwork Setting");
// Setting Icon to Dialog
// alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "Internet Is Inactive", Toast.LENGTH_SHORT).show();
}
});
// Showing Alert Message
alertDialog.show();
}
}
});//End of On click for button
}//If no shared preferences found
}//End of onCreate function
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_admin_home, menu);
return true;
}//End of onCreateOptionMenu
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
//Remove Following Comment To Enable Drawer Toggling On Login Page
/*// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}*/
return super.onOptionsItemSelected(item);
}//End of onOptionItemSelected
//Alert Dialog when User Click Back Button
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//Handle the back button
if(keyCode == KeyEvent.KEYCODE_BACK) {
//Ask the user if they want to quit
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.quit)
.setMessage(R.string.really_quit)
.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Stop the activity
Login.this.finish();
}
})
.setNegativeButton("no", null)
.show();
return true;
}
else {
return super.onKeyDown(keyCode, event);
}
}//End of Alert Dialog Box
/**
* Background Async Task to Login by making HTTP Request
*/
class CheckDetail extends AsyncTask<String,String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
JSONArray datail=null;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Logging in. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
*/
protected String doInBackground(String... args) {
try {
Log.v(TAG, "In Do in Background");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", username));
params.add(new BasicNameValuePair("pwd", password));
// getting JSON string from URL
JSONObject json =jParser.makeHttpRequest(url_all_login, "POST", params);
//Object Parsing Failed here hence by using trail guide using JSONParser.alternateJSONArray to parse user data.
//Hence not using json instance of object using a BACKUP static variable of Parser class for proccessing.
//To use this backup utility theme the process should be standard and return unique or two out put only or ether way use three logical step
if(json != null) {
// As if login fails it returns object handling fail logic here.
//We can make it general by sending array from server side so we can only use alternateJSONArray variable
}
if(JSONParser.alternateJSONArray != null)
{
Log.v(TAG, "USING BACKUP ARRAY");
//Check your log cat for JSON futher details
for (int jsonArrayElementIndex=0; jsonArrayElementIndex < JSONParser.alternateJSONArray.length(); jsonArrayElementIndex++) {
JSONObject jsonObjectAtJsonArrayElementIndex = JSONParser.alternateJSONArray.getJSONObject(jsonArrayElementIndex);
userid=jsonObjectAtJsonArrayElementIndex.getString("u_id");
otpkey=jsonObjectAtJsonArrayElementIndex.getString("OTP");
vrfy=jsonObjectAtJsonArrayElementIndex.getString("is_verified");
Log.v(TAG,"" +userid);
Log.v(TAG,"" +otpkey);
Log.v(TAG,"" +vrfy);
if(jsonObjectAtJsonArrayElementIndex.getString("email").equals(username) && jsonObjectAtJsonArrayElementIndex.getString("mobile").equals(password))
{
Log.v(TAG,"Login Successful Now setting loginflag true");
loginflag = true;
}
}
}
else
{
//JSON is null ether no data or 204 returned by server
}
} catch (Exception e) {
e.printStackTrace();
Log.v(TAG, "Exception at end :" + e.toString());
//Log.e("TAG", "Error......!RecoverIt");
}
return null ;
}
protected void onPostExecute(String result)
{
// dismiss the dialog after getting all products
//super.onPostExecute();
// pDialog.dismiss();
if(loginflag==true) {
Log.v(TAG, "Executing Shared Preferences...");
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("User", uname.getText().toString());
editor.putString("Password", pass.getText().toString());
Log.v(TAG, "" + userid);
Log.v(TAG, "" + otpkey);
Log.v(TAG, "" + vrfy);
editor.commit();
Toast.makeText(getApplicationContext(), "Login Succeed", Toast.LENGTH_SHORT).show();
android.util.Log.v(TAG, "Login Succeed");
Intent i = new Intent(getApplicationContext(), UserLogedIn.class);
startActivity(i);
finish();
}
else
{
Toast.makeText(getApplicationContext(),"Login failed,Invalid Details...!",Toast.LENGTH_LONG).show();
trouble.setVisibility(View.VISIBLE);
}
pDialog.dismiss();
}
}
String getMD5(String pass) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageDigest = md.digest(pass.getBytes());
BigInteger number = new BigInteger(1, messageDigest);
String hashtext = number.toString(16);
// Now we need to zero pad it if you actually want the full 32 chars.
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}
return hashtext;
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
/* private int returnParsedJsonObject(String result) {
JSONObject resultObject = null;
int returnedResult = 0;
try {
resultObject = new JSONObject(result);
returnedResult = resultObject.getInt("success");
} catch (JSONException e) {
e.printStackTrace();
}
return returnedResult;
}*/
}
When i logout and at login activity if i enter wrong detail it will give following logcat
I think backuparray is not nnull when i logout
loginflag is static. once it is set to true it is never set back to false until you restart the app.
Okey .
First make your AsyncTask extends AsyncTask<Void, Void, Boolean> then return true in Boolean doInBackground(Void... params) if your server gives Success response and set it as false if server gives you failed message.
Now in your onPostExecute(Boolean result) , if result is true then set your login flag here as True else false.
I have problem in my application.
I want to show user's profile, and I have two links in my app.
One link is via TextView, which run showUser(View v) method:
public void showUser(View v){
Intent i;
i=new Intent(getApplicationContext(), ShowProfile.class);
i.putExtra("id",user); // user is String with users ID
startActivity(i);
}
And the second link is in dialog, which user can open:
( I will post here whole method, but I'll highlight important part )
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder .setTitle(R.string.show_photo_show_rated_users_title)
.setNegativeButton("Close", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
ListView modeList = new ListView(this);
String[] stringArray = new String[ratedUsers.size()];
for ( int i=0 ; i<ratedUsers.size() ; i++ ){
stringArray[i] = ratedUsers.get(i).get("name");
}
ArrayAdapter<String> modeAdapter = new ArrayAdapter<String>(this, R.layout.dropdown_item_white, android.R.id.text1, stringArray);
modeList.setAdapter(modeAdapter);
modeList.setOnItemClickListener(new ListView.OnItemClickListener(){
/*********************** IMPORTANT PART *********************************/
#Override
public void onItemClick(AdapterView<?> parent, View arg1, int index,long arg3) {
Intent i;
i=new Intent(ShowPhotoDetails.this , ShowProfile.class);
i.putExtra("id",ratedUsers.get(index).get("id"));
/**** ratedUsers is ArrayList<HashMap<String,String>> ****/
startActivity(i);
}});
builder.setView(modeList);
final Dialog dialog = builder.create();
dialog.show();
}
And finally here's ShowProfile.class:
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
Intent i = getIntent();
try {
id = i.getStringExtra("id");
}catch(Exception e){
e.printStackTrace();
Toast.makeText(getBaseContext(), "Error loading intent", Toast.LENGTH_SHORT).show();
finish();
}
try{
Log.w("ID",id); //always give right number
new GetUserInformations().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, id);
/*
If I comments this asyncTask, there's no error at all, but if I run it, It
open debug View in Eclipse, says that "Source not found" and crashes...
No LogCat Output
*/
}catch(Exception e){
e.printStackTrace();
}
...
I wonder why in one case it run perfectly and in the other it crashes. As I wrote in code, there's no LogCat output for this crash. It don't even say Uncaught exception or something like this.
EDIT: I found out what gives me the error.
public class GetUserInformations extends AsyncTask<String,Void,Void>{
Map<String,Object> tmpUser;
#Override
protected void onPreExecute(){
tmpUser = new HashMap<String,Object>();
}
#Override
protected Void doInBackground(String... arg) {
try{
int u_id = Integer.parseInt(arg[0]);
tmpUser = myDb.getUser(u_id); // downloading info
}catch(Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void arg){
if ( tmpUser != null ){
Log.w("LOG",""+tmpUser.get("name"));
name = (String) tmpUser.get("name");
fbId = (String) tmpUser.get("id");
email = (String) tmpUser.get("email");
country = (Integer) tmpUser.get("country");
userName.setText(name);
profilepic.setProfileId(fbId);
userSubscribe.setVisibility(View.VISIBLE);
}
else {
Toast.makeText(getBaseContext(), "Error", Toast.LENGTH_SHORT).show();
finish();
}
}
}
When I open activity for first time, everything downloads fine, but when I backPress and click on link to this Activity again, then it gives me NullPointerException.
Do you know why ?
In your onItemClick function, try to put :
i = new Intent(getApplicationContext(), ShowProfile.class);
instead of :
i = new Intent(ShowPhotoDetails.this, ShowProfile.class);
remove this:
new GetUserInformations().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, id);
and use :
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB) {
new GetUserInformations().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, id);
}
else {
new GetUserInformations().execute(id);
}
What is the API level on which you are facing this problem. Try to run it on different levels, taking Honeycomb as a reference.
Need to check the same and apply execute or executeONExecutor like this:
if (currentApiVersion >=
android.os.Build.VERSION_CODES.HONEYCOMB) {
new YourAsynctask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
new YourAsynctask().execute();
}
Check this asynctask-threading-regression-confirmed blog post
I'm trying to show an AlertDialog in my AsyncTask on onCancelled. My task is stopping properly, but the dialog isn't appearing. Here's my code below... Need help. Thanks...
public class getWebPage extends AsyncTask<String, Integer, String> {
protected void onPreExecute(String f) {
// TODO Setting up variables
f = "f";
}
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
Looper.prepare();
DefaultHttpClient urlClient = new DefaultHttpClient();
HttpGet getHtml = new HttpGet(PAGE_URL);
ResponseHandler<String> resHandler = new BasicResponseHandler();
try {
String htmlPage = urlClient.execute(getHtml, resHandler);
Log.d("Html Page", htmlPage);
confessionsPage = new File(getApplicationContext().getFilesDir(), "ConfessionsPage.html");
if (!confessionsPage.exists()) {
confessionsPage.createNewFile();
}
writer = new PrintWriter(confessionsPage, "UTF-8");
writer.print(htmlPage.replace("<!--", "").replace("-->", ""));
writer.flush();
writer.close();
Document doc = Jsoup.parse(confessionsPage, "UTF-8", "http://www.facebook.com/");
if (doc.title().contains("Welcome to Facebook")) {
aDialog = new AlertDialog.Builder(OpeningActivity.this).create();
aDialog.setTitle("Restricted Access");
aDialog.setMessage("Looks like your Confessions Page only allows login access. You may be logged in right now, but the app" +
" can't. Tell your page admin to allow non-logged in access for your confessions page.");
aDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
aDialog.dismiss();
}
});
getWebPage.this.cancel(true);
}
and here is my on cancelled method:
#Override
protected void onCancelled() {
// TODO Auto-generated method stub
super.onCancelled();
aDialog.show();
}
Try move everything from the doInBackground to the onCancelled.
So this will be your onCancelled:
AlertDialog aDialog = new AlertDialog.Builder(OpeningActivity.this).create();
aDialog.setTitle("Restricted Access");
aDialog.setMessage("Looks like your Confessions Page only allows login access. You may be logged in right now, but the app" +
" can't. Tell your page admin to allow non-logged in access for your confessions page.");
aDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
aDialog.dismiss();
}
});
aDialog.show();
And remove everything from the doInBackground.
Alternatively you can put this into your AsyncTask's onPostExecute too and change the result type of the task to Boolean. in the onPostExecute check the result. If it's false and you need to display this error. display it from there.
Note that onPostExecute is executed by the UI thread so you don't need the runOnUiThread stuff.
I have an alert dialog box in my application for login authentication. While sending the request i want to show a progress bar and want to dismiss if the response is success.please help me if anyone knows.Iam using the below code:
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
LinearLayout login = new LinearLayout(this);
TextView tvUserName = new TextView(this);
TextView tvPassword = new TextView(this);
TextView tvURL = new TextView(this);
final EditText etUserName = new EditText(this);
final EditText etPassword = new EditText(this);
final EditText etURL = new EditText(this);
login.setOrientation(1); // 1 is for vertical orientation
tvUserName.setText(getResources().getString(R.string.username));
tvPassword.setText(getResources().getString(R.string.password));
tvURL.setText("SiteURL");
login.addView(tvURL);
login.addView(etURL);
login.addView(tvUserName);
login.addView(etUserName);
login.addView(tvPassword);
etPassword.setInputType(InputType.TYPE_CLASS_TEXT
| InputType.TYPE_TEXT_VARIATION_PASSWORD);
login.addView(etPassword);
alert.setView(login);
alert.setTitle(getResources().getString(R.string.login));
alert.setCancelable(true);
alert.setPositiveButton(getResources().getString(R.string.login),
new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog,
int whichButton) {
strhwdXml = etURL.getText().toString();
strUserName = etUserName.getText().toString();
XmlUtil.username = strUserName;
strPassword = etPassword.getText().toString();
if ((strUserName.length() == 0)
&& (strPassword.length() == 0)
&& (strhwdXml.length() == 0)) {
Toast.makeText(
getBaseContext(),
getResources().getString(
R.string.userPassword),
Toast.LENGTH_SHORT).show();
onStart();
} else {
final SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor prefsEditor = prefs
.edit();
try {
StringBuffer inStreamBuf = new StringBuffer();
inStreamBuf = XmlUtil
.getLoginAuthResponse(strUserName,
strPassword, strhwdXml);
strXmlResponse = inStreamBuf.toString();
Log.e("Response:", strXmlResponse);
String parsedXML = ParseResponse(strXmlResponse);
if (parsedXML
.equalsIgnoreCase(getResources()
.getString(R.string.success))) {
}
It might be easier to use this
ProgressDialog dialog = ProgressDialog.show(MyActivity.this, "",
"Loading. Please wait...", true);
You can read more about progress dialogs here
To cancel would be
dialog.dismiss();
This class was deprecated in API level 26. ProgressDialog is a modal
dialog, which prevents the user from interacting with the app. Instead
of using this class, you should use a progress indicator like
ProgressBar, which can be embedded in your app's UI. Alternatively,
you can use a notification to inform the user of the task's progress.For more details Click Here
Since the ProgressDialog class is deprecated, here is a simple way to display ProgressBar in AlertDialog:
Add fields in your Activity:
AlertDialog.Builder builder;
AlertDialog progressDialog;
Add getDialogProgressBar() method in your Activity:
public AlertDialog.Builder getDialogProgressBar() {
if (builder == null) {
builder = new AlertDialog.Builder(this);
builder.setTitle("Loading...");
final ProgressBar progressBar = new ProgressBar(this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
progressBar.setLayoutParams(lp);
builder.setView(progressBar);
}
return builder;
}
Initialize progressDialog:
progressDialog = getDialogProgressBar().create();
Show/Hide AlertDialog whenever u want using utility methods:
progressDialog.show() and progressDialog.dismiss()
If you want the progress bar to show, try the following steps and also you can copy and paste the entire code the relevant portion of your code and it should work.
//the first thing you need to to is to initialize the progressDialog Class like this
final ProgressDialog progressBarDialog= new ProgressDialog(this);
//set the icon, title and progress style..
progressBarDialog.setIcon(R.drawable.ic_launcher);
progressBarDialog.setTitle("Showing progress...");
progressBarDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//setting the OK Button
progressBarDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,
int whichButton){
Toast.makeText(getBaseContext(),
"OK clicked!", Toast.LENGTH_SHORT).show();
}
});
//set the Cancel button
progressBarDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int whichButton){
Toast.makeText(getApplicationContext(), "Cancel clicked", Toast.LENGTH_SHORT).show();
}
});
//initialize the dialog..
progressBarDialog.setProgress(0);
//setup a thread for long running processes
new Thread(new Runnable(){
public void run(){
for (int i=0; i<=15; i++){
try{
Thread.sleep(1000);
progressBarDialog.incrementProgressBy((int)(5));
}
catch(InterruptedException e){
e.printStackTrace();
}
}
//dismiss the dialog
progressBarDialog.dismiss();
}
});
//show the dialog
progressBarDialog.show();
The cancel button should dismiss the dialog.
Try below code
private class DownloadingProgressTask extends
AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog = new ProgressDialog(ShowDescription.this);
/** progress dialog to show user that the backup is processing. */
/** application context. */
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
}
protected Boolean doInBackground(final String... args) {
try {
// write your request code here
**StringBuffer inStreamBuf = new StringBuffer();
inStreamBuf = XmlUtil
.getLoginAuthResponse(strUserName,
strPassword, strhwdXml);
strXmlResponse = inStreamBuf.toString();
Log.e("Response:", strXmlResponse);
String parsedXML = ParseResponse(strXmlResponse);
if (parsedXML
.equalsIgnoreCase(getResources()
.getString(R.string.success))) {**
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) {
Toast.makeText(ShowDescription.this,
"File successfully downloaded", Toast.LENGTH_LONG)
.show();
imgDownload.setVisibility(8);
} else {
Toast.makeText(ShowDescription.this, "Error", Toast.LENGTH_LONG)
.show();
}
}
}
and call this in onclick event
new DownloadingProgressTask().execute();