So I am developing one android application in which I have created one custom dialog box. but the problem arises that, this dialog box is showing correct in my phone and on emulator also. But it can't get display properly on redmi or other phones.
Here is screenshot on my mobile device
and [![On other device][2]][2]
On other device
[2]: https://i.stack.imgur.com/b3H4J.jpg
Here is my code:-
custom_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFF538"
android:padding="10dp">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Would you like to continue"
android:textColor="#color/black"
android:textSize="30dp"
android:textStyle="bold" />
<TextView
android:id="#+id/bld"
android:layout_width="269dp"
android:layout_height="wrap_content"
android:textColor="#color/black" />
<EditText
android:id="#+id/txt_input"
android:layout_width="382dp"
android:layout_height="69dp"
android:layout_marginTop="10dp"
android:background="#drawable/back"
android:hint="Why are you sending this request?"
android:maxLength="100"
android:textSize="20sp" />
<!-- In given textview we have used maxlength =100
because we have to display small information so we use limited characters.-->
<TextView
android:layout_width="wrap_content"
android:layout_height="117dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="11dp"
android:text="Your request will display publicly in blood request section.And if your any request is present in Blood Request will be deleted"
android:textColor="#FF0303"
android:textSize="20dp" />
<Button
android:id="#+id/btn_okay"
android:layout_width="134dp"
android:layout_height="60dp"
android:layout_weight="0"
android:layout_marginTop="10dp"
android:backgroundTint="#color/black"
android:text="yes"
android:textColor="#ffffff"
android:textSize="18sp" />
<Button
android:id="#+id/btn_cancel"
android:layout_width="136dp"
android:layout_height="60dp"
android:layout_gravity="right"
android:layout_marginTop="-58dp"
android:layout_weight="0"
android:backgroundTint="#color/black"
android:gravity="center"
android:text="no"
android:textColor="#ffffff"
android:textSize="18sp" />
</LinearLayout>
donor.java
private void alertDialog() {
final AlertDialog.Builder alert = new AlertDialog.Builder(Bloodbank.this);
View mView = getLayoutInflater().inflate(R.layout.custom_dialog2, null);
Button btn_cancel = (Button) mView.findViewById(R.id.btn_cancel);
Button btn_okay = (Button) mView.findViewById(R.id.btn_okay);
TextView bld = (TextView) mView.findViewById(R.id.bld);
bld.setText("selected blood group is "+item);
alert.setView(mView);
final AlertDialog alertDialog = alert.create();
alertDialog.setCanceledOnTouchOutside(false);
btn_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Request dismissed", Toast.LENGTH_SHORT).show();
alertDialog.dismiss();
}
});
btn_okay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
SQLiteDatabase db = dbHandler.getWritableDatabase();
String sql1 = "delete from request where time < date('now','-2 day') AND Username = '" + MainActivity.getValue() + "'";
db.execSQL(sql1);
String sql = "select Name,contactNo from request where Username = '" + MainActivity.getValue() + "'";
Cursor cursor = db.rawQuery(sql, null);
if (cursor.moveToFirst()) {
do {
runOnUiThread(new Runnable() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void run() {
Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
vibrator.vibrate(VibrationEffect.createOneShot(1000, VibrationEffect.DEFAULT_AMPLITUDE));
Toast.makeText(getApplicationContext(), "your request is pending. Please delete that first.", Toast.LENGTH_SHORT).show();
}
});
}
});
}
while (cursor.moveToNext());
}
catch (Exception e) {
runOnUiThread(new Runnable() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void run() {
Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
vibrator.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));
Toast.makeText(getApplicationContext(), "Please select blood group first", Toast.LENGTH_SHORT).show();
}
});
}
}
} catch (Exception e) {
e.printStackTrace();
}
alertDialog.dismiss();
}
});
alertDialog.show();
alertDialog.getWindow().setLayout(700, 833); //Controlling width and height.
}
Try to change these lines
alertDialog.show();
alertDialog.getWindow().setLayout(700, 833); //Controlling width and height.
With these line
int width = (int) (getResources().getDisplayMetrics().widthPixels * 0.90);
int height = (int) (getResources().getDisplayMetrics().heightPixels * 0.60);
if (alertDialog.getWindow() != null) {
alertDialog.getWindow().setLayout(width, height);
}
alertDialog.show();
Related
I would like to show an error message within an alert dialog box for password reset, however no error message shows inside the dialog pop up.
Alert Dialog Box
When clicking "Reset" the dialog box will close. However, entering in a valid email does show the toast message "Reset Email Sent"
The validations are 1) leaving the email address empty , 2)not giving a proper email
Login.java
//onclick for forgot password
forgotPText = findViewById(R.id.forgotPassText);
forgotPText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//start alert dialog
View view = inflater.inflate(R.layout.reset_popup,null);
reset_alert.setTitle("Forgot Password ?")
.setMessage("Enter Email For Password Reset Link.")
.setPositiveButton("Reset", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//validate the email address is not empty or not valid email
EditText email = view.findViewById(R.id.reset_popup_Email);
String emailChar = email.getText().toString();
if (email.getText().toString().isEmpty()){
email.setError("Required Field!");
return;
}
if(!Patterns.EMAIL_ADDRESS.matcher(emailChar).matches()){
email.setError("Please provide valid email!");
email.requestFocus();
return;
}
//send reset link
firebaseAuth.sendPasswordResetEmail(email.getText().toString())
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
//FirebaseUser user = firebaseAuth.getCurrentUser();
//updateUI(user);
Toast.makeText(LoginActivity.this
, "Reset Email Sent", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(LoginActivity.this, e.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
}
}).setNegativeButton("Cancel",null)
.setView(view)
.create().show();
}
});
Use this code:
forgotPText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//start alert dialog
LayoutInflater inflater = getLayoutInflater();
AlertDialog.Builder reset_alert = new AlertDialog.Builder(MainActivity.this);
View view = inflater.inflate(R.layout.reset_popup,null);
reset_alert.setView(view);
EditText email = view.findViewById(R.id.email);
TextView tv_cancel = view.findViewById(R.id.tv_cancel);
TextView tv_submit = view.findViewById(R.id.tv_submit);
tv_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
new Handler().postDelayed(new Runnable() {
#Override
public void run() { alertDialog.dismiss(); }}, 200);
}
});
email.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
});
tv_submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
String emailChar = email.getText().toString();
if (email.getText().toString().isEmpty()){
email.setError("Required Field!");
return;
}
if (!Patterns.EMAIL_ADDRESS.matcher(emailChar).matches()){
email.setError("Please provide valid email!");
email.requestFocus();
return;
}
//send reset link
firebaseAuth.sendPasswordResetEmail(email.getText().toString())
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
//FirebaseUser user = firebaseAuth.getCurrentUser();
//updateUI(user);
Toast.makeText(LoginActivity.this
, "Reset Email Sent", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(LoginActivity.this, e.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
}
});
alertDialog = reset_alert.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
}
});
//////// reset_popup.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/reset_alert"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="Forgot Password?"
android:textColor="#color/black"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/des"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:textColor="#color/black"
android:text="Enter Email For Password Reset Link."
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/reset_alert" />
<EditText
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:hint="Email Address"
android:inputType="textEmailAddress"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/des" />
<TextView
android:id="#+id/tv_cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="Cancel"
android:textColor="#color/black"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/tv_submit"
app:layout_constraintTop_toBottomOf="#+id/email" />
<TextView
android:id="#+id/tv_submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:layout_marginEnd="353dp"
android:text="Reset"
android:textColor="#color/black"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/email" />
</androidx.constraintlayout.widget.ConstraintLayout>
I'm new to android studio. Currently I'm working on a medlabtut app on android for over 3 months now. I'm having an issue on the login button on the MedLabStartUpScreen that actually supposed to launch the login screen when clicked on. Rather it crashes the app completely and shows a runtimeException at my //Connection Hooks "progressbar = findViewById(R.id.login_progress_bar);" of my login.java class file, that android.widget.ProgressBar cannot be cast to android.widget.RelativeLayout. I need your help please
My Login layout activity
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Common.LoginSignup.Login"
android:orientation="vertical"
android:background="#fff"
android:padding="25dp"
android:transitionName="transition_login">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/logo_name"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="Welcome Back! Login Here"
android:textSize="40sp"
android:transitionName="logo_text"
android:fontFamily="#font/bungee"
android:textColor="#000"
android:layout_marginTop="20dp"/>
<TextView
android:id="#+id/slogan_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sign In to continue"
android:textSize="18sp"
android:layout_marginTop="10dp"
android:fontFamily="#font/muli_black"
android:transitionName="logo_desc"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:layout_marginBottom="20dp">
<com.hbb20.CountryCodePicker
android:id="#+id/login_country_code_picker"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:ccp_autoDetectCountry="true"
app:ccp_showFlag="true"
app:ccp_showNameCode="true"
app:ccp_showFullName="true"
android:padding="5dp"
android:background="#drawable/black_border"/>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_below="#+id/login_country_code_picker"
android:id="#+id/login_phone_number"
android:layout_height="wrap_content"
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:hint="#string/phone_number"
android:textColorHint="#color/Black"
app:boxStrokeColor="#color/Black"
app:boxStrokeWidthFocused="2dp"
app:endIconMode="clear_text"
app:endIconTint="#color/Black"
app:hintTextColor="#color/Black"
app:startIconDrawable="#drawable/field_phone_number_icon"
app:startIconTint="#color/Black">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/login_phone_number_editText"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="phone" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/login_password"
android:layout_below="#+id/login_phone_number"
android:hint="#string/password"
app:startIconDrawable="#drawable/field_password_icon"
app:startIconTint="#color/Black"
android:transitionName="password_tran"
app:passwordToggleEnabled="true"
app:passwordToggleTint="#color/Black"
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/login_password_editText"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fontFamily="#font/muli_bold"
android:inputType="textPassword" />
</com.google.android.material.textfield.TextInputLayout>
<RelativeLayout
android:id="#+id/forget_password_block"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/login_password"
android:layout_marginTop="10dp">
<CheckBox
android:id="#+id/remember_me"
style="#style/Widget.AppCompat.CompoundButton.CheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:text="#string/remember_me" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/forget_password"
android:background="#00000000"
android:layout_alignParentEnd="true"
android:onClick="callForgetPassword"
android:layout_alignParentRight="true"/>
</RelativeLayout>
<Button
android:id="#+id/letTheUserLogin"
android:layout_below="#+id/forget_password_block"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginTop="5dp"
android:background="#000"
android:text="#string/login"
android:onClick="letTheUserLoggedIn"
android:textColor="#fff"
android:transitionName="button_tran" />
<RelativeLayout
android:id="#+id/login_sign_google_box"
android:layout_width="match_parent"
android:layout_height="50dp"
android:padding="10dp"
android:layout_margin="5dp"
android:background="#drawable/rounded_rectangle"
android:layout_below="#+id/letTheUserLogin">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/signin_with_google_icon"
android:layout_centerVertical="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SIGN IN WITH GOOGLE"
android:layout_centerHorizontal="true"
android:layout_centerInParent="true"
android:fontFamily="#font/muli_bold"
android:layout_margin="5dp"
android:textColor="#000"/>
<Button
android:id="#+id/google_signIn"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/transparent" />
</RelativeLayout>
<Button
android:id="#+id/signup_screen"
android:layout_below="#+id/login_sign_google_box"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#00000000"
android:text="Create Account"
android:layout_centerHorizontal="true"
android:elevation="0dp"
android:layout_margin="5dp"
android:textColor="#000"
android:transitionName="login_signup_tran"/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="20dp"
android:layout_centerInParent="true"
android:background="#drawable/white_circle"
android:elevation="10dp">
<ProgressBar
android:id="#+id/login_progress_bar"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerInParent="true"/>
</RelativeLayout>
<ImageView
android:id="#+id/social_fb"
android:layout_below="#+id/signup_screen"
android:layout_width="50dp"
android:layout_height="45dp"
android:src="#drawable/social_facebook_icon"
android:layout_marginLeft="130dp" />
<ImageView
android:id="#+id/social_tw"
android:layout_below="#id/signup_screen"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_centerHorizontal="true"
android:layout_marginLeft="150dp"
android:src="#drawable/social_twitter_icon" />
<ImageView
android:id="#+id/social_wh"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_below="#id/signup_screen"
android:layout_marginLeft="250dp"
android:src="#drawable/social_whatsapp_icon" />
</RelativeLayout>
</LinearLayout>
And the code for login.java class file
public class Login extends AppCompatActivity {
CountryCodePicker countryCodePicker;
Button callSignUp, login_btn;
TextView logoText, sloganText;
TextInputLayout username, phoneNumber, password;
RelativeLayout progressbar;
CheckBox rememberMe;
EditText phoneNumberEditText, passwordEditText;
private GoogleSignInClient mGoogleSignInClient;
private final static int RC_SIGN_IN = 123; // request code
Button verify;
private FirebaseAuth mAuth;
#Override
protected void onStart() {
super.onStart();
FirebaseUser user = mAuth.getCurrentUser();
if (user!=null){
Intent intent = new Intent(getApplicationContext(), MedLabDashboard.class);
startActivity(intent);
}
}
#SuppressLint("WrongViewCast")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_login);
mAuth = FirebaseAuth.getInstance();
createRequest();
//when the user clicks the google button,call the signIn method
findViewById(R.id.google_signIn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
signIn();
}
});
//Connection Hooks
countryCodePicker = findViewById(R.id.country_code_picker);
phoneNumber = findViewById(R.id.login_phone_number);
progressbar = findViewById(R.id.login_progress_bar);
callSignUp = findViewById(R.id.signup_screen);
image = findViewById(R.id.logo_image);
logoText = findViewById(R.id.logo_name);
sloganText = findViewById(R.id.slogan_name);
password = findViewById(R.id.login_password);
login_btn = findViewById(R.id.Login_btn);
rememberMe = findViewById(R.id.remember_me);
phoneNumberEditText = findViewById(R.id.login_phone_number_editText);
passwordEditText = findViewById(R.id.login_password_editText);
//Check whether phone number and password is already saved in Shared Preference or not
SessionManager sessionManager = new SessionManager(Login.this, SessionManager.SESSION_REMEMBERME);
if (sessionManager.checkRemeberMe()){
HashMap<String,String> rememberMeDetails = sessionManager.getRememberMeDetailFromSession();
phoneNumberEditText.setText(rememberMeDetails.get(SessionManager.KEY_SESSIONPHONENUMBER));
passwordEditText.setText(rememberMeDetails.get(SessionManager.KEY_SESSIONPASSWORD));
}
callSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Login.this, SignUp.class);
Pair[] pairs = new Pair[7];
pairs[0] = new Pair<View, String>(image, "logo_image");
pairs[1] = new Pair<View, String>(logoText, "logo_name");
pairs[2] = new Pair<View, String>(sloganText, "logo_desc");
pairs[3] = new Pair<View, String>(username, "username_tran");
pairs[4] = new Pair<View, String>(password, "password_tran");
pairs[5] = new Pair<View, String>(login_btn, "button_tran");
pairs[6] = new Pair<View, String>(callSignUp, "login_signup_tran");
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
try {
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
//Setting Auto Google Sign In request
private void createRequest() {
// Configure Google Sign In
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
// Build a GoogleSignInClient with the options specified by gso.
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}
//SignIn with google method that'll pop-up user google accounts (Intent)
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
//Google Sign in was successful, authenticate with firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e){
//Sign in failed, update UI appropriately
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
FirebaseUser user = mAuth.getCurrentUser();
Intent intent = new Intent(getApplicationContext(), MedLabDashboard.class);
startActivity(intent);
} else {
Toast.makeText(Login.this, "Sorry authentication failed", Toast.LENGTH_SHORT).show();
}
}
});
}
//login the user in app
public void letTheUserLoggedIn(View view) {
//Check the internet connection
CheckInternet checkInternet = new CheckInternet();
if (!isConnected(Login.this)) {
showCustomDialog();
}
//validate user and password
if (!validateFields()) {
return;
}
progressbar.setVisibility(View.VISIBLE);
//get value from fields
String _phoneNumber = phoneNumber.getEditText().getText().toString().trim();
final String _password = password.getEditText().getText().toString().trim();
if (_phoneNumber.charAt(0) == '0') { //if the user uses proceeding zero (0)
_phoneNumber = _phoneNumber.substring(1);
}
final String _completePhoneNumber = "+" + countryCodePicker.getFullNumber() + _phoneNumber;
//Remember me checkbox
if (rememberMe.isChecked()){
SessionManager sessionManager = new SessionManager(Login.this,SessionManager.SESSION_REMEMBERME);
sessionManager.createRememberMeSession(_phoneNumber, _password);
}
//database query if user exist or not
Query checkUser = FirebaseDatabase.getInstance().getReference("Users").orderByChild("phoneNo").equalTo(_completePhoneNumber);
checkUser.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) { //if the data has arrived or exists
phoneNumber.setError(null); //if there's any error on the phoneNumber, remove
phoneNumber.setErrorEnabled(false); //if there is error space, set to false
String systemPassword = dataSnapshot.child(_completePhoneNumber).child("password").getValue(String.class);
//if password exist and matches with users password, then get other fields from firebase database
if (systemPassword.equals(_password)) {
password.setError(null); //if there's any error on the password, remove
password.setErrorEnabled(false); //if there is error space, set to false
String _fullname = dataSnapshot.child(_completePhoneNumber).child("fullName").getValue(String.class);
String _username = dataSnapshot.child(_completePhoneNumber).child("username").getValue(String.class);
String _email = dataSnapshot.child(_completePhoneNumber).child("email").getValue(String.class);
String _phoneNo = dataSnapshot.child(_completePhoneNumber).child("phoneNo").getValue(String.class);
String _password = dataSnapshot.child(_completePhoneNumber).child("password").getValue(String.class);
String _dateOfBirth = dataSnapshot.child(_completePhoneNumber).child("date").getValue(String.class);
String _gender = dataSnapshot.child(_completePhoneNumber).child("gender").getValue(String.class);
//Create a session
SessionManager sessionManager = new SessionManager(Login.this, SessionManager.SESSION_USERSESSION);
sessionManager.createLoginSession(_fullname, _username, _email, _phoneNo, _password, _dateOfBirth, _gender);
startActivity(new Intent(getApplicationContext(), MedLabDashboard.class));
Toast.makeText(Login.this, _fullname + "\n" + _email + "\n" + _phoneNo + "\n" + _dateOfBirth, Toast.LENGTH_SHORT).show();
progressbar.setVisibility(View.GONE);
} else {
progressbar.setVisibility(View.GONE);
Toast.makeText(Login.this, "Password does not match!", Toast.LENGTH_SHORT).show();
}
} else {
progressbar.setVisibility(View.GONE);
Toast.makeText(Login.this, "No such user exist", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
progressbar.setVisibility(View.GONE);
Toast.makeText(Login.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
//check internet connection
private boolean isConnected(Login login) {
ConnectivityManager connectivityManager = (ConnectivityManager) login.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiConn = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobileConn = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if ((wifiConn != null && wifiConn.isConnected()) || (mobileConn != null && mobileConn.isConnected())) {
return true;
} else {
return false;
}
}
private void showCustomDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(Login.this);
builder.setMessage("Please connect to the internet to continue");
builder.setCancelable(false)
.setPositiveButton("Connect", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
startActivity(new Intent(getApplicationContext(), MedLabStartUpScreen.class));
finish();
}
});
}
private boolean validateFields() {
String _phoneNumber = phoneNumber.getEditText().getText().toString().trim();
String _password = password.getEditText().getText().toString().trim();
if (_phoneNumber.isEmpty()) {
phoneNumber.setError("Phone number cannot be empty");
phoneNumber.requestFocus();
return false;
} else if (_password.isEmpty()) {
password.setError("Password cannot be empty");
password.requestFocus();
return false;
} else {
password.setError(null);
password.setErrorEnabled(false);
return true;
}
}
public void callForgetPassword(View view){
startActivity(new Intent(getApplicationContext(), ForgetPassword.class));
}
#Override
public void onBackPressed() {
Intent a = new Intent(Intent.ACTION_MAIN);
a.addCategory(Intent.CATEGORY_HOME);
a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(a);
finish();
}}
MedLabStartUpScreen Activity screen
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/White"
android:padding="30dp"
tools:context=".Common.LoginSignup.MedLabStartUpScreen">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:layout_width="match_parent"
android:layout_height="300dp"
android:src="#drawable/splash_screen" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="120dp"
android:fontFamily="#font/muli_black"
android:text="#string/medlab_heading"
android:textAlignment="center"
android:textAllCaps="true"
android:textColor="#color/Black"
android:textSize="36sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:fontFamily="#font/muli_light"
android:text="#string/medlab_tab_line"
android:textAlignment="center"
android:textColor="#color/Black" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp">
<Button
android:id="#+id/login_btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:layout_marginEnd="10dp"
android:onClick="callLoginScreen"
android:layout_weight="1"
android:background="#color/colorPrimaryDark"
android:text="#string/login"
android:textColor="#color/Black"
tools:ignore="ButtonStyle"
android:transitionName="transition_login"/>
<Button
android:id="#+id/signup_btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_weight="1"
android:background="#color/colorPrimaryDark"
android:text="#string/sign_up"
android:textColor="#color/Black" />
</LinearLayout>
<Button
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="#string/how_we_work"
android:textColor="#color/Black"
android:layout_marginTop="20dp"
android:background="#00000000"/>
</LinearLayout>
</ScrollView>
MedLabStartUPScreen.java class that has the login button
public class MedLabStartUpScreen extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_med_lab_start_up_screen);
}
public void callLoginScreen(View view){
Intent intent = new Intent(getApplicationContext(), Login.class);
Pair[] pairs = new Pair[1];
pairs[0] = new Pair<View,String>(findViewById(R.id.login_btn), "transition_login");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(MedLabStartUpScreen.this, pairs);
startActivity(intent, options.toBundle());
}
else {
startActivity(intent);
}
}
}
On around line 7 you declare this variable:
RelativeLayout progressbar;
You then correctly go on to initialise this variable with:
progressbar = findViewById(R.id.login_progress_bar);
The issue is that in the xml, the view (widget) with this ID is a ProgressBar, but the type declaration for progressbar in the Java code is RelativeLayout. Your code is therefore trying to cast the ProgressBar in the layout file into a RelativeLayout, which can't be done.
You can fix this by changing the declaration on line 7 to:
ProgressBar progressbar;
(And then adding the necessary import at the top of your Java file: import android.widget.ProgressBar;).
Hope this helped.
I have a custom dialog in which I include another layout. In this layout there are 3 buttons and a TextView none of these is null. If I click the buttons they work correctly. But the TextView doesn't show any text. The text should appears when I click another button. That's how it should works
Custom dialog layout:
<LinearLayout
............
.....
<androidx.cardview.widget.CardView
android:id="#+id/result_card"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardElevation="2dp"
card_view:cardMaxElevation="2dp"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="8dp"
android:visibility="gone"
app:cardCornerRadius="8dp">
<include android:id="#+id/result_layout" layout="#layout/result_block" />
</androidx.cardview.widget.CardView>
....
....
</LinearLayout>
The result_block layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:background="#color/colorPrimary"
android:orientation="vertical">
<TextView
android:id="#+id/result_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="17dp"
android:text=""
android:textColor="#color/colorWhite"
android:fontFamily="sans-serif-medium"
android:padding="8dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="end"
android:orientation="horizontal">
<ImageButton
android:id="#+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_copy_24px_outlined"
android:layout_marginEnd="16dp"
android:tint="#color/colorWhite"
android:background="?attr/selectableItemBackgroundBorderless"
/>
<ImageButton
android:id="#+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:tint="#color/colorWhite"
android:src="#drawable/ic_share_24px_outlined"
android:background="?attr/selectableItemBackgroundBorderless"
/>
<ImageButton
android:id="#+id/btn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:tint="#color/colorWhite"
android:src="#drawable/ic_volume_up_24px_outlined"
android:background="?attr/selectableItemBackgroundBorderless"
/>
</LinearLayout>
</LinearLayout>
And now the dialog
private void showDiag() {
final View dialogView = View.inflate(getActivity(), R.layout.custom_dialog_layout,null);
final View resultLayout = View.inflate(getActivity(), R.layout.result_block,null);
final Dialog dialog = new Dialog(getActivity(), R.style.MyAlertDialogStyle);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(dialogView);
final TextView resultTxt = resultLayout.findViewById(R.id.result_txt);
final ImageButton btn1 = resultLayout.findViewById(R.id.btn1);
final CardView resultCardView = dialog.findViewById(R.id.result_card_view);
final TextInputEditText editText = dialog.findViewById(R.id.text_edit);
final ImageButton clearText = dialog.findViewById(R.id.clear_text);
MaterialButton resultConfirm = dialog.findViewById(R.id.result_confirm);
ImageButton btn2 = dialogView.findViewById(R.id.copy_btn);
ImageButton btn3 = dialogView.findViewById(R.id.share_btn);
resultConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!editText.getText().toString().equals("")) {
String theWord = editText.getText().toString();
String result = Utils.getSecondWord(theWord);
// result it shows me the correct string with no errors or something else
resultTxt.setText(result); // doesn't work. Not set the text
insertWord(theWord, result);
resultCardView.setVisibility(View.VISIBLE);
resultCardView.setVisibility(View.VISIBLE);
} else {
Toast.makeText(getActivity(), "Error", Toast.LENGTH_SHORT).show();
}
}
});
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i(TAG, "result: " + resultTxt.getText().toString());
}
});
// Share btn
bt2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i(TAG, "result: " + resultTxt.getText().toString());
}
});
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i(TAG, "result: " + resultTxt.getText().toString());
}
});
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialogInterface) {
Utils.revealShow(dialogView, true, null, resultConfirm);
}
});
dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
if (i == KeyEvent.KEYCODE_BACK){
Utils.revealShow(dialogView, false, dialog, resultConfirm);
return true;
}
return false;
}
});
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.show();
}
Everything inside the dialog works correctly but the TextView not. Even if I try to write something else like resultTxt.setText("Hello there"); the text not appears. Any suggestions?
Please you remove the android:text=""in TextView because textview is get default text is empty or you write anything in TextView like android:text="abc"
I successfully integrated the Google sign-in and successful in showing data in another Activity. But When I am going back to that activity where I passed the data it showing empty screen. I Want to Save user details in Profile Activity. Please help me. Thanks in Advance for a proper Solution. Below are my java files and XML files.
activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".Main2Activity">
<LinearLayout
android:id="#+id/prof_section"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="50dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/prof_pic"
android:layout_width="90dp"
android:layout_height="125dp"
android:src="#drawable/profilep" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="28dp"
android:layout_marginTop="20dp"
android:orientation="vertical">
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Disply Name Here"
android:textSize="18dp"
android:textStyle="bold" />
<TextView
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:text="Disply Email Here"
android:textSize="18dp"
android:textStyle="bold" />
<Button
android:id="#+id/butn_logout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Logout"/>
</LinearLayout>
</LinearLayout>
<com.google.android.gms.common.SignInButton
android:id="#+id/butn_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:layout_marginTop="60dp" >
</com.google.android.gms.common.SignInButton>
activity_profile.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".Profile">
<ImageView
android:id="#+id/dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp" />
<TextView
android:id="#+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp" />
<Button
android:id="#+id/button_save"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SAVE" />
Profile.Java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
dp = (ImageView) findViewById(R.id.dp);
name = (TextView) findViewById(R.id.name);
email = (TextView) findViewById(R.id.email);
Intent i = getIntent();
final String i_name, i_email, i_url;
i_name = i.getStringExtra("p_name");
i_email = i.getStringExtra("p_email");
i_url = i.getStringExtra("p_url");
name.setText(i_name);
email.setText(i_email);
new Thread(new Runnable() {
#Override
public void run() {
try {
URL url = new URL(i_url);
InputStream is = url.openConnection().getInputStream();
final Bitmap bmp = BitmapFactory.decodeStream(is);
runOnUiThread(new Runnable() {
#Override
public void run() {
dp.setImageBitmap(bmp);
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
Main2Activity.Java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
preferenceConfig = new SharedPreferenceConfig(getApplicationContext());
if (preferenceConfig.readLoginStatus()) {
startActivity(new Intent(this, Main3Activity.class));
finish();
}
Prof_Section = (LinearLayout) findViewById(R.id.prof_section);
SignOut = (Button) findViewById(R.id.butn_logout);
SignIn = (SignInButton) findViewById(R.id.butn_login);
Name = (TextView) findViewById(R.id.name);
Email = (TextView) findViewById(R.id.email);
Prof_Pic = (ImageView) findViewById(R.id.prof_pic);
SignIn.setOnClickListener(this);
SignOut.setOnClickListener(this);
Prof_Section.setVisibility(View.GONE);
GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().requestProfile().build();
googleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this, this).addApi(Auth.GOOGLE_SIGN_IN_API, signInOptions).build();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.butn_login:
signIn();
break;
case R.id.butn_logout:
signOut();
break;
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
private void signIn() {
Intent intent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
startActivityForResult(intent, REQ_CODE);
}
private void signOut() {
Auth.GoogleSignInApi.signOut(googleApiClient).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
updateUI(false);
}
});
}
private void updateUI(boolean isLogin) {
if (isLogin) {
Prof_Section.setVisibility(View.VISIBLE);
SignIn.setVisibility(View.GONE);
} else {
Prof_Section.setVisibility(View.GONE);
SignIn.setVisibility(View.VISIBLE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQ_CODE) {
GoogleSignInResult googleSignInResult = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
GoogleSignInAccount account = googleSignInResult.getSignInAccount();
String name = account.getDisplayName();
String email = account.getEmail();
String img_url = account.getPhotoUrl().toString();
Name.setText(name);
Email.setText(email);
Glide.with(this).load(img_url).into(Prof_Pic);
updateUI(true);
preferenceConfig.writeLoginStatus(true);
try {
Intent sendData = new Intent(Main2Activity.this, Profile.class);
name = account.getDisplayName();
email = account.getEmail();
img_url = account.getPhotoUrl().toString();
sendData.putExtra("p_name", name);
sendData.putExtra("p_email", email);
sendData.putExtra("p_url", img_url);
startActivity(sendData);
} catch (Exception e) {
Toast.makeText(Main2Activity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(Main2Activity.this, "Login Failed", Toast.LENGTH_SHORT).show();
}
}
Instead of passing the data to the Profile activity use the GoogleSignIn.getLastSignedInAccount(getActivity()); method to get user profile data.
Replace your,
Intent i = getIntent();
final String i_name, i_email, i_url;
i_name = i.getStringExtra("p_name");
i_email = i.getStringExtra("p_email");
i_url = i.getStringExtra("p_url");
with the following code,
GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(getActivity());
if (acct != null) {
String i_name = acct.getDisplayName();
String i_email = acct.getEmail();
Uri i_url = acct.getPhotoUrl();
}
For more information check this documentation
As a beginner I have some questions about optimizing my application speed. I'm building a simple quiz app there I have an sqlite database inside with some information. With that information I'm generating my questions in quiz page.
It was working pretty fine and fast until I fixed some buttons/background in sketch and use them. Now it's working much more slower and I'm getting error messages at logcat like "Skipped xxx frames! The application may be doing too much work on its main thread." I have searched on google for a while and found out that the bitmaps are slowing down my application. Have read about async and using a new thread to make it run faster.
As a solution I have resized some of my bitmaps, but then I'm getting less quality in my design, so I decided to fix it. I have googled some more about loading my layout with async or a new thread but didn't really find out how/where to do it. What makes me confused is that I don't know if it's to load layout with a new thread is the best solution or to load other processes with new thread. Need some recommendation about how to optimize my app. Here is my code, at least the quiz page that is slowest. I'm not really sure what to optimize there with a new thread. Under a question it's just countdowntimer that is running, and when next clicked countdowntimer starts over and the gui updates with the new question.
My quizpage code:
public class QuizPage extends ActionBarActivity
{
DatabaseHelper dbHelper = new DatabaseHelper(this);
Cursor kommunCrs, lanCrs, riktCrs;
ArrayList<Kommuner> kommunLista = new ArrayList<Kommuner>();
ArrayList<Lan> lanLista = new ArrayList<Lan>();
ArrayList<Riktnummer> riktLista = new ArrayList<Riktnummer>();
ArrayList<Fragar> fragaLista = new ArrayList<Fragar>();
Fragar svList = new Fragar();
Fragar frageObj = new Fragar();
int buttonRaknare = 0;
CountDownTimer cd;
long millisLeft;
long totalMillis = 10100;
int pBarProgress;
TextView pageNr, fraga, cdText;
RadioButton valA, valB, valC, valD;
RadioGroup rg;
Button avsluta, nasta;
ProgressBar pBar;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_page);
checkDB(); // Checking the DB
getCursorData(); // Getting data to cursors
setCrsdataList(); // Setting cursor data to lists
setViewElements(); // Set textview, buttons etc.
setButtonListeners();
getNastaFragaData(); // Refresing the gui with the next question
startCountdownTimer(totalMillis, false); // Countdowntimer starts
}
private void getCursorData()
{
kommunCrs = dbHelper.getDatabase().query("Kommuner ORDER BY RANDOM() LIMIT 50", new String[]{"kommun_id", "kommun_namn", "kommun_lan", "kommun_befolkning"}, null, null, null, null, null);
lanCrs = dbHelper.getDatabase().query("Lan ORDER BY RANDOM()", new String[]{"lan_namn", "lan_befolkning", "lan_antal_kommun", "lan_yta", "lan_id"}, null, null, null, null, null);
riktCrs = dbHelper.getDatabase().query("Riktnummer ORDER BY RANDOM() LIMIT 50", new String[]{"riktnr", "riktnr_omrade", "riktnr_id"}, null, null, null, null, null);
}
private void setCrsdataList()
{
if (kommunCrs.getCount() != 0 && lanCrs.getCount() != 0 && riktCrs.getCount() != 0) {
kommunCrs.moveToFirst();
lanCrs.moveToFirst();
riktCrs.moveToFirst();
for (int i = 0; i < kommunCrs.getCount(); i++) {
Kommuner tempKommun = new Kommuner();
tempKommun.setKommun_namn(kommunCrs.getString(kommunCrs.getColumnIndex("kommun_namn")));
tempKommun.setKommun_lan(kommunCrs.getString(kommunCrs.getColumnIndex("kommun_lan")));
tempKommun.setKommun_befolkning(kommunCrs.getString(kommunCrs.getColumnIndex("kommun_befolkning")));
tempKommun.setKommun_id(kommunCrs.getInt(kommunCrs.getColumnIndex("kommun_id")));
kommunLista.add(tempKommun);
kommunCrs.moveToNext();
}
for (int i = 0; i < lanCrs.getCount(); i++) {
Lan tempLan = new Lan();
tempLan.setLan_namn(lanCrs.getString(lanCrs.getColumnIndex("lan_namn")));
tempLan.setLan_befolkning(lanCrs.getString(lanCrs.getColumnIndex("lan_befolkning")));
tempLan.setLan_antal_kommun(lanCrs.getString(lanCrs.getColumnIndex("lan_antal_kommun")));
tempLan.setLan_yta(lanCrs.getString(lanCrs.getColumnIndex("lan_yta")));
tempLan.setLan_id(lanCrs.getInt(lanCrs.getColumnIndex("lan_id")));
lanLista.add(tempLan);
lanCrs.moveToNext();
}
for (int i = 0; i < riktCrs.getCount(); i++) {
Riktnummer tempRiktnr = new Riktnummer();
tempRiktnr.setRiktnr(riktCrs.getString(riktCrs.getColumnIndex("riktnr")));
tempRiktnr.setRiktnr_omrade(riktCrs.getString(riktCrs.getColumnIndex("riktnr_omrade")));
tempRiktnr.setRiktnr_id(riktCrs.getInt(riktCrs.getColumnIndex("riktnr_id")));
riktLista.add(tempRiktnr);
riktCrs.moveToNext();
}
//Generating my questions here and taking in to a list
fragaLista = frageObj.slumpaFragor(kommunLista, lanLista, riktLista);
Collections.shuffle(fragaLista);
}
else
{
Toast.makeText(getApplicationContext(), "Finns ingen data i databasen!", Toast.LENGTH_SHORT).show();
}
}
private void getNastaFragaData()
{
fraga.setText(fragaLista.get(buttonRaknare).getFraga());
valA.setText(fragaLista.get(buttonRaknare).getSvarArr().get(0).toString());
valB.setText(fragaLista.get(buttonRaknare).getSvarArr().get(1).toString());
valC.setText(fragaLista.get(buttonRaknare).getSvarArr().get(2).toString());
valD.setText(fragaLista.get(buttonRaknare).getSvarArr().get(3).toString());
pageNr.setText(Integer.toString(buttonRaknare+1) + "/20");
}
private void rattSvarCheck()
{
if (valA.isChecked())
{
fragaLista.get(buttonRaknare).userInput = valA.getText().toString();
if (valA.getText().hashCode() == fragaLista.get(buttonRaknare).getRattSvar().hashCode())
{
svList.antalRattSvar++;
}
else
{
svList.antalFelSvar++;
}
}
else if (valB.isChecked())
{
fragaLista.get(buttonRaknare).userInput = valB.getText().toString();
if (valB.getText().hashCode() == fragaLista.get(buttonRaknare).getRattSvar().hashCode())
{
svList.antalRattSvar++;
}
else
{
svList.antalFelSvar++;
}
}
else if (valC.isChecked())
{
fragaLista.get(buttonRaknare).userInput = valC.getText().toString();
if (valC.getText().hashCode() == fragaLista.get(buttonRaknare).getRattSvar().hashCode())
{
svList.antalRattSvar++;
}
else
{
svList.antalFelSvar++;
}
}
else if (valD.isChecked())
{
fragaLista.get(buttonRaknare).userInput = valD.getText().toString();
if (valD.getText().hashCode() == fragaLista.get(buttonRaknare).getRattSvar().hashCode())
{
svList.antalRattSvar++;
}
else
{
svList.antalFelSvar++;
}
}
else
{
fragaLista.get(buttonRaknare).userInput = "";
svList.antalTomtSvar++;
}
}
private void resultatToDatabas()
{
dbHelper.resultatToDatabas(svList.antalRattSvar, svList.antalFelSvar, svList.antalTomtSvar);
Intent i = new Intent(getBaseContext(),QuizResultat.class);
i.putExtra("rslist", fragaLista);
i.putExtra("sl", svList);
finish();
startActivity(i);
}
private void startCountdownTimer(long millis, final boolean isResume)
{
if (!isResume)
{
pBar.setProgress(100);
pBar.setProgressDrawable(pBar.getResources().getDrawable(R.drawable.nypbar));
}
else
{
pBar.setProgress(pBarProgress);
pBar.setProgressDrawable(pBar.getResources().getDrawable(R.drawable.nypbar));
if (pBar.getProgress() < 55 && pBar.getProgress() > 23 )
{
pBar.getProgressDrawable().setColorFilter(Color.parseColor("#FFFFB800"), PorterDuff.Mode.SRC_IN);
}
else if (pBar.getProgress() < 23)
{
pBar.getProgressDrawable().setColorFilter(Color.parseColor("#FFE71000"), PorterDuff.Mode.SRC_IN);
}
}
int callInterval = 100;
cd = new CountDownTimer(millis, callInterval)
{
public void onTick(long millisUntilFinished)
{
millisLeft = millisUntilFinished;
pBarProgress = pBar.getProgress();
int secondsRemaining = (int) millisUntilFinished / 100;
float fraction = millisUntilFinished / (float) totalMillis;
// progress bar is based on scale of 1 to 100;
pBar.setProgress((int) (fraction * 100));
cdText.setText(String.format("%2.1f", secondsRemaining / 10.0, Integer.toString(secondsRemaining)));
if (pBar.getProgress() < 55 && pBar.getProgress() > 23 )
{
pBar.getProgressDrawable().setColorFilter(Color.parseColor("#FFFFB800"), PorterDuff.Mode.SRC_IN);
}
else if (pBar.getProgress() < 23)
{
pBar.getProgressDrawable().setColorFilter(Color.parseColor("#FFE71000"), PorterDuff.Mode.SRC_IN);
}
}
public void onFinish() {
nasta.performClick();
}
}.start();
}
// Deklarera knappar, textview osv.
private void setViewElements()
{
pageNr = (TextView) findViewById(R.id.pageNumberTxt);
fraga = (TextView) findViewById(R.id.fragaTxt);
valA = (RadioButton) findViewById(R.id.valAbtn);
valB = (RadioButton) findViewById(R.id.valBbtn);
valC = (RadioButton) findViewById(R.id.valCbtn);
valD = (RadioButton) findViewById(R.id.valDbtn);
rg = (RadioGroup) findViewById(R.id.valRadioGrupp);
avsluta = (Button) findViewById(R.id.avslutaBtn);
nasta = (Button) findViewById(R.id.nastaBtn);
pBar = (ProgressBar) findViewById(R.id.progressBar);
cdText = (TextView) findViewById(R.id.counterTxt);
}
private void setButtonListeners()
{
// Nästaknapp onClick
nasta.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
cd.cancel(); // Avslutar countdowntimer
rattSvarCheck(); // Kontrollerar om svaret är rätt
if (buttonRaknare > 17)
{
nasta.setBackground(getResources().getDrawable(R.drawable.avsluta_selector));
}
if (buttonRaknare != 19) // Så länge det inte är sista frågan
{
buttonRaknare++;
rg.clearCheck(); // Tar bort check från valknapparna
startCountdownTimer(totalMillis, false); // Startar om den avslutade countdowntimer
getNastaFragaData(); // Tar nästa frågans innehåll till view
}
else if (buttonRaknare == 19)
{
resultatToDatabas(); // Sparar resultaten till databasen
}
}
});
// Avslutaknapp onClick
avsluta.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
cd.cancel(); // Pausar cooldowntimer först
visaAlertDialog(); // Visar alert dialog
}
});
}
// Visa alertDialog
private void visaAlertDialog()
{
AlertDialog.Builder adBuild = new AlertDialog.Builder(this)
.setTitle("Avsluta")
.setMessage("Vill du avsluta quizet?")
.setIcon(android.R.drawable.ic_delete)
.setPositiveButton(new String(Character.toChars(0x1F616)) + " Japp! ", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton(new String(Character.toChars(0x1F60A)) + " Nej", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
cd.cancel();
//RESUME COUNTDOWNTIMER
startCountdownTimer(millisLeft, true);
}
})
.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
dialog.cancel();
cd.cancel();
//RESUME COUNTDOWNTIMER
startCountdownTimer(millisLeft, true);
}
});
AlertDialog alertDialog = adBuild.create();
alertDialog.show();
}
private void checkDB()
{
try
{
dbHelper.createDataBase();
dbHelper.openDataBase();
} catch (IOException a) {
a.printStackTrace();
} catch (SQLException b) {
b.printStackTrace();
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
{
setContentView(R.layout.activity_quiz_page);
setViewElements();
setButtonListeners();
getNastaFragaData();
}
else
{
setContentView(R.layout.activity_quiz_page);
setViewElements();
setButtonListeners();
getNastaFragaData();
}
}
// onBackPressed metod som visar alertDialog
#Override
public void onBackPressed()
{
cd.cancel();
visaAlertDialog();
}
// onStop METHOD
#Override
protected void onStop()
{
super.onStop();
dbHelper.close();
}
}
My quizpage layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:background="#drawable/quizpage_bg"
tools:context="com.example.onur.quiz.QuizPage">
<TextView
android:layout_width="60dp"
android:layout_height="wrap_content"
android:text="1/20"
android:id="#+id/pageNumberTxt"
android:textSize="18dp"
android:textColor="#ffab6200"
android:background="#drawable/pagenumberbg"
android:textStyle="italic|bold"
android:gravity="center"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:paddingTop="2dp"
android:paddingBottom="5dp"
android:paddingRight="3dp"
android:paddingLeft="3dp" />
<Button
android:layout_width="135dp"
android:layout_height="50dp"
android:id="#+id/nastaBtn"
android:focusable="false"
android:nestedScrollingEnabled="false"
android:background="#drawable/nasta_selector"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="15dp" />
<Button
android:layout_width="30dp"
android:layout_height="30dp"
android:id="#+id/avslutaBtn"
android:background="#drawable/exit_selector"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true" />
<RadioGroup
android:id="#+id/valRadioGrupp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="false"
android:gravity="center_vertical"
android:layout_marginTop="20dp"
android:layout_alignParentStart="false"
android:layout_below="#+id/progressBar"
android:divider="#00FFFFFF"
android:layout_above="#+id/nastaBtn"
android:layout_marginBottom="10dp"
android:background="#drawable/svarbg" >
<RadioButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="valAtxt"
android:id="#+id/valAbtn"
android:checked="false"
android:textSize="22dp"
android:layout_alignParentLeft="true"
android:paddingBottom="12dp"
android:paddingTop="12dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#drawable/custom_rg_drawer"
android:paddingLeft="15dp" />
<RadioButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="valBbtn"
android:id="#+id/valBbtn"
android:checked="false"
android:textSize="22dp"
android:layout_alignLeft="#+id/nastaBtn"
android:paddingBottom="12dp"
android:paddingTop="12dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#drawable/custom_rg_drawer"
android:paddingLeft="15dp" />
<RadioButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="valCbtn"
android:id="#+id/valCbtn"
android:checked="false"
android:textSize="22dp"
android:paddingBottom="12dp"
android:paddingTop="12dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#drawable/custom_rg_drawer"
android:paddingLeft="15dp" />
<RadioButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="valDbtn"
android:id="#+id/valDbtn"
android:checked="false"
android:textSize="22dp"
android:layout_alignParentLeft="true"
android:paddingBottom="12dp"
android:paddingTop="12dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"
android:background="#drawable/custom_rg_drawer"
android:paddingLeft="15dp" />
</RadioGroup>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Hur många personer bor i Trollhättan?"
android:id="#+id/fragaTxt"
android:textColor="#ffc37800"
android:textSize="24dp"
android:layout_marginTop="20dp"
android:layout_below="#+id/avslutaBtn"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="false"
android:gravity="center"
android:background="#drawable/fragabg"
android:paddingLeft="10dp"
android:paddingRight="10dp" />
<ProgressBar
style="#android:style/Widget.ProgressBar.Horizontal"
android:progressDrawable = "#drawable/nypbar"
android:layout_width="290dp"
android:layout_height="10dp"
android:id="#+id/progressBar"
android:layout_marginTop="15dp"
android:layout_below="#+id/fragaTxt" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="10.00"
android:id="#+id/counterTxt"
android:layout_alignParentRight="true"
android:layout_below="#+id/fragaTxt"
android:layout_marginTop="11dp" />
</RelativeLayout>
I don't think it has much to do with bitmaps, especially if you are pulling them from Drawable resources. The source of your lag is likely your database queries, which are happening in onCreate, which are blocking the main thread to do disk access. Instead, use a CursorLoader as described in https://developer.android.com/training/load-data-background/setup-loader.html