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();
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 usually work on .Net but I need to develop an Android app. So I am new on Android, sorry for mistakes in advance! :)
Here is my story,
I am populating a customer list(creating ui elements in code behind) with views in a button click. I am doing that pulling datas from database. So it takes some time to pull the data and creating views. What I wanna do is showing a progress dialog while customer list is being populated. Currently I am able to make it run. But the problem is it doesn't show the progress dialog immediately, then customerlist and progress dialog are displayed at the same time.
Here is my button click;
public void ShowCustomers(View view){
final ProgressDialog dialog = new ProgressDialog(MainActivity.this);
runOnUiThread(new Runnable() {
#Override
public void run() {
dialog.setTitle("Title");
dialog.setMessage("Loading...");
if(!dialog.isShowing()){
dialog.show();
}
}
});
new Thread() {
public void run() {
try{
runOnUiThread(new Runnable() {
#Override
public void run() {
PopulateRecentGuests(); //Creates customer list dynamically
dialog.dismiss();
}
});
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
}.start();
}
And populating the customers;
public void PopulateRecentGuests(){
LinearLayout customers = (LinearLayout)findViewById(R.id.customers);
String query = "SELECT * from Table";
ModelCustomer customerModel = new ModelCustomer();
ArrayList<HashMap<String, String>> recentGuests = customerModel.RetrievingQuery(query);
customersCount = recentGuests.size();
Context context = getApplicationContext();
if(customersCount < 1)
Toast.makeText(context, "There is no available customer in database!", Toast.LENGTH_LONG);
else if(!recentGuests.get(0).containsKey("err")) {
for(int i = 0; i < recentGuests.size(); i++){
HashMap<String, String> guest = recentGuests.get(i);
Button button = new Button(context);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.setMargins(0,5,0,5);
button.setLayoutParams(params);
button.setWidth(800);
button.setHeight(93);
button.setTag(guest.get("id"));
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("New button clicked! ID: " + v.getTag());
Intent intent = new Intent(getApplicationContext(), ProductPageActivity.class);
intent.putExtra("CustomerID", v.getTag().toString());
startActivity(intent);
}
});
button.setBackgroundColor(Color.parseColor("#EFEFEF"));
button.setText(guest.get("FirstName") + " " + guest.get("LastName") + " " + guest.get("GuideName"));
button.setTextColor(Color.BLACK);
button.setTextSize(20);
button.setEnabled(false);
customers.addView(button); // customers is a linear layout and button is being added to customers
Button guest_list_btn = (Button)findViewById(R.id.guest_list_btn);
guest_list_btn.setEnabled(true);
}
}
else{
CharSequence text = recentGuests.get(0).get("err");
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
Button guest_list_btn = (Button)findViewById(R.id.guest_list_btn);
Button guest_list_close_btn = (Button)findViewById(R.id.guest_list_close_btn);
customers.setVisibility(View.VISIBLE);
AnimationSet aset = new AnimationSet(true);
aset.setFillEnabled(true);
aset.setInterpolator(new LinearInterpolator());
AlphaAnimation alpha = new AlphaAnimation(0.0F, 1.0F);
alpha.setDuration(400);
aset.addAnimation(alpha);
TranslateAnimation trans = new TranslateAnimation(200, 0, 0, 0);
trans.setDuration(400);
aset.addAnimation(trans);
customers.startAnimation(aset);
guest_list_btn.setEnabled(false);
guest_list_close_btn.setEnabled(true);
for(int i = 0; i < customers.getChildCount(); i++){
View child = customers.getChildAt(i);
child.setEnabled(true);
}
}
After my research, I understand that runonuithread is called after looper. My question is How can I display the progress dialog immediately and then I can populate the customer list (creating ui elements). By the way, I tried to do that with asynctask first but I wasn't able to.
Thans in advance!
But the problem is it doesn't show the progress dialog immediately,
then customerlist and progress dialog are displayed at the same time.
That's because you do the long operation(and closing the dialog sequentially) on the main UI thread. Instead you should separate things between retrieving the data(which takes time) and building the views(along with closing the dialog).
//...
new Thread() {
public void run() {
// do the long operation on this thread
final ArrayList<HashMap<String, String>> recentGuests = customerModel.RetrievingQuery(query);
// after retrieving the data then use it to build the views and close the dialog on the main UI thread
try{
runOnUiThread(new Runnable() {
#Override
public void run() {
// remove the retrieving of data from this method and let it just build the views
PopulateRecentGuests(recentGuests);
dialog.dismiss();
}
});
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
}.start();
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.
I want to create a dialogBuilder with a text field and a button on it. The idea is to make the program wait for any further actions until the text in the field is entered and the OK button is clicked. Below is the code:
private static final Object wait = new int[0];
private static String result = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Handler h = new Handler();
final Context context = MainActivity.this;
h.post(new Runnable() {
public void run() {
final Builder dialogBuilder = new AlertDialog.Builder(context);
dialogBuilder.setTitle(R.string.app_name);
final LinearLayout panel = new LinearLayout(context);
panel.setOrientation(LinearLayout.VERTICAL);
final TextView label = new TextView(context);
label.setId(1);
label.setText(R.string.app_name);
panel.addView(label);
final EditText input = new EditText(context);
input.setId(2);
input.setSingleLine();
input.setInputType(InputType.TYPE_CLASS_TEXT
| InputType.TYPE_TEXT_VARIATION_URI
| InputType.TYPE_TEXT_VARIATION_PHONETIC);
final ScrollView view = new ScrollView(context);
panel.addView(input);
view.addView(panel);
dialogBuilder
.setCancelable(true)
.setPositiveButton(R.string.app_name,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
result = input.getText().toString();
synchronized (wait) {
wait.notifyAll();
}
dialog.dismiss();
}
}).setView(view);
dialogBuilder.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface arg0) {
result = null;
synchronized (wait) {
wait.notifyAll();
}
}
});
dialogBuilder.create().show();
}
});
String localResult = null;
try {
synchronized (wait) {
Log.d("Waiting", "Waiting " + localResult);
wait.wait();
}
localResult = result;
result = null;
if (localResult == null) {
// user is requesting cancel
throw new RuntimeException("Cancelled by user");
}
Log.d("RESULT ", "RESULT " + localResult);
} catch (InterruptedException e) {
localResult = result;
result = null;
if (localResult == null) {
// user is requesting cancel
Log.d("CANCELED ", "CANCELED " + localResult);
throw new RuntimeException("Cancelled by user");
}
}
Log.d("RESULT AFTER THE DIALOG", "RESULT AFTER THE DIALOG " + result);
}
The program is going to Log.d("Waiting", "Waiting " + localResult); and after that just waiting. NO DIALOG BUILDER IS SHOWN on the activity window. I used the debug mode and saw that the program flow is not entering the run() method, but the value of the Handler.post() is true. And for this reason the dialog is not shown, and the program is waiting.
I have tried to remove the moment with waiting (remove the Handler.post()), just to see if the dialog will show, and it showed and all moved well, but the result was not I am needing - I want the program to wait the input from the dialog ... I am really out of ideas.
Would you please give me some suggestions as I am really out of ideas.
Thanks a lot!
Handlers don't run in a separate thread. So when you call wait() :
synchronized (wait) {
Log.d("Waiting", "Waiting " + localResult);
wait.wait();
}
It waits indefinitely since the handler runs on the same thread as the current thread. Your Runnable can only be executed after the onCreate() method finishes but this will never happen because you just called wait().
You should reconsider your idea and find a workaround (for example, show the dialog the usual way and disable the "OK" button as long as the user does not enter a valid text). But calling wait() on the UI thread cannot go well.
You should be running the display of the Dialog in the UI Thread, not a seperate thread.
An example would be something like this:
In the onCreate()
runOnUiThread(new Runnable() {
#Override
public void run() {
// Display progress dialog when loading contacts
dialog = new ProgressDialog(this);
// continue with config of Dialog
}
});
// Execute the Asynchronus Task
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
// code to execute in background
return null;
}
#Override
protected void onPostExecute(Void result) {
// Dismiss the dialog after inBackground is done
if (dialog != null)
dialog.dismiss();
super.onPostExecute(result);
}
}.execute((Void[]) null);
Specifically what is happening here is the Dialog is being displayed on the UI thread and then the AsyncTask is executing in the background while the Dialog is running. Then at the end of the execution we dismiss the dialog.