After press SignUp button, Display error : unfortunately app has stopped
LogCat error : java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lolacupcakes/com.example.lolacupcakes.HomeActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
SignUpActivity: Java Code
public class SignUpActivity extends AppCompatActivity {
EditText emailId, password;
Button btnSignUp;
TextView tvSignIn;
FirebaseAuth mFirebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
mFirebaseAuth = FirebaseAuth.getInstance();
emailId = findViewById(R.id.emailIDSignUp);
password = findViewById(R.id.pwdIDSignUp);
btnSignUp = findViewById(R.id.btnIDSignUp);
tvSignIn = findViewById(R.id.textView);
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = emailId.getText().toString();
String pwd = password.getText().toString();
if(email.isEmpty())
{
emailId.setError("Please Enter Email Id");
emailId.requestFocus();
}
else if (pwd.isEmpty())
{
password.setError("Please Enter Email Id");
password.requestFocus();
}
else if (email.isEmpty() && pwd.isEmpty())
{
Toast.makeText(SignUpActivity.this, "Fields are Empty",Toast.LENGTH_SHORT).show();
}
else if (!(email.isEmpty() && pwd.isEmpty()))
{
mFirebaseAuth.createUserWithEmailAndPassword(email,pwd).addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful())
{
Toast.makeText(SignUpActivity.this, "SignUp Unsuccessful, Please Try Again",Toast.LENGTH_SHORT).show();
}
else
{
startActivity(new Intent(SignUpActivity.this,HomeActivity.class));
}
}
});
}
else
{
Toast.makeText(SignUpActivity.this, "Error Occurred!",Toast.LENGTH_SHORT).show();
}
}
});
tvSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(SignUpActivity.this, LoginActivity.class);
startActivity(i);
}
});
}
}
SignUpActivity XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".SignUpActivity">
<Button
android:id="#+id/btnIDSignUp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="132dp"
android:text="Sign Up" />
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="62dp"
android:src="#drawable/logo_lola" />
<EditText
android:id="#+id/pwdIDSignUp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="206dp"
android:ems="10"
android:hint="Password"
android:inputType="textPassword" />
<EditText
android:id="#+id/emailIDSignUp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="269dp"
android:ems="10"
android:hint="Email"
android:inputType="textEmailAddress" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="87dp"
android:text="Already have an account? Sign in here." />
</RelativeLayout>
HomeActivity Java Code:
public class HomeActivity extends AppCompatActivity {
Button btnlogout;
FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
btnlogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
Intent intoMain = new Intent(HomeActivity.this, SignUpActivity.class);
startActivity(intoMain);
}
});
}
}
HomeActivityXML:
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HomeActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Welcome"
android:textSize="50dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0" />
<Button
android:id="#+id/btnLogout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Logout"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="424dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
You missed initializing btnlogout. Add this line in HomeActivity onCreate before setting View.OnClickListener
btnlogout = findViewById(R.id.btnLogout);
You need to create btnSignUp object before setonlicklistener for button
btnSignUp = findViewById(R.id.btnLogout);
You need to create the btnSignUp object before setonclicklistener.
Related
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.
In my main page I have 3 different buttons.
Login (loginB)
Create a new account (createB)
Terms of conduct (termsB)
So far it has worked just fine, but for some reason I have now faced a problem with the create new account button. It did go to the right page before but now it goes to a wrong page. It should be going to the CreateAccount -page but it is going to the Menu -page.
I have the java code in the MainActivity were the buttons are here:
public class MainActivity extends AppCompatActivity {
Button loginB;
Button termsB;
Button createB;
EditText emailL,passwordL;
FirebaseAuth fAuth;
ProgressBar progressB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createB = findViewById(R.id.createB);
createB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openCreateAccount();
}
});
termsB = findViewById(R.id.termsB);
termsB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openTermsOfConduct();
}
});
emailL = findViewById(R.id.emailL);
passwordL = findViewById(R.id.passwordL);
fAuth = FirebaseAuth.getInstance();
loginB = findViewById(R.id.loginB);
progressB = findViewById(R.id.progressB);
loginB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = emailL.getText().toString().trim();
String password = passwordL.getText().toString().trim();
if(TextUtils.isEmpty(email)){
emailL.setError("Email is required.");
return;
}
if(TextUtils.isEmpty(password)){
passwordL.setError("Password is required.");
return;
}
if(password.length() <6){
passwordL.setError("Password must be at least 6 characters.");
}
progressB.setVisibility(View.VISIBLE);
//authenticate the user
fAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(MainActivity.this, "Logged in successfully", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),Menu.class));
}
else{
Toast.makeText(MainActivity.this, "Error " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
progressB.setVisibility(View.INVISIBLE);
}
}
});
}
});
}
public void openCreateAccount(){
Intent intent = new Intent(this, CreateAccount.class);
startActivity(intent);
}
public void openTermsOfConduct(){
Intent intent = new Intent(this, TermsOfConduct.class);
startActivity(intent);
}
}
Main Activity xml:
<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"
tools:context=".MainActivity"
android:background="#drawable/tausta">
<TextView
android:layout_width="match_parent"
android:layout_height="180dp"
android:fontFamily="sans-serif"
android:paddingVertical="30dp"
android:text="Login"
android:textAlignment="center"
android:textColor="#000"
android:textSize="90sp"
android:layout_marginBottom="25dp"
/>
<EditText
android:id="#+id/emailL"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="30dp"
android:layout_marginBottom="30dp"
android:textColor="#fff"
android:textSize="25sp"
android:hint="Email"
android:textColorHint="#fff"
/>
<EditText
android:id="#+id/passwordL"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="30dp"
android:inputType="textPassword"
android:layout_marginBottom="30dp"
android:textColor="#fff"
android:textSize="25sp"
android:hint="Password"
android:textColorHint="#fff"
/>
<Button
android:id="#+id/loginB"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="Login"
android:layout_marginHorizontal="30dp"
android:layout_marginBottom="25dp"
android:background="#drawable/button_bg"
/>
<Button
android:id="#+id/createB"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="Create a new account"
android:layout_marginHorizontal="30dp"
android:layout_marginBottom="25dp"
android:background="#drawable/button_bg"
/>
<Button
android:id="#+id/termsB"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Terms and conditions"
android:layout_marginHorizontal="30dp"
android:textColor="#0070ff"
android:textAlignment="center"
android:background="#android:color/transparent"
/>
<ProgressBar
android:id="#+id/progressB"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="invisible"
/>
</LinearLayout>
CreateAccount java:
public class CreateAccount extends AppCompatActivity {
Button registerB;
EditText nameR,emailR,pnumberR,passwordR;
FirebaseAuth fAuth;
ProgressBar progressB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_account2);
nameR = findViewById(R.id.nameR);
emailR = findViewById(R.id.emailR);
pnumberR = findViewById(R.id.pnumberR);
passwordR = findViewById(R.id.passwordR);
progressB = findViewById(R.id.progressB);
fAuth = FirebaseAuth.getInstance();
//check if user registered
if(fAuth.getCurrentUser() != null){
startActivity(new Intent(getApplicationContext(),Menu.class));
finish();
}
registerB = findViewById(R.id.registerB);
registerB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = emailR.getText().toString().trim();
String password = passwordR.getText().toString().trim();
if(TextUtils.isEmpty(email)){
emailR.setError("Email is required.");
return;
}
if(TextUtils.isEmpty(password)){
passwordR.setError("Password is required.");
return;
}
if(password.length() <6){
passwordR.setError("Password must be ata least 6 characters.");
return;
}
progressB.setVisibility(View.VISIBLE);
//register the user to FireBase
fAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(CreateAccount.this, "User created.", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),Menu.class));
}
else{
Toast.makeText(CreateAccount.this, "Error " +task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
}
CreateAccount xml:
<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"
tools:context=".CreateAccount"
android:background="#drawable/tausta"
>
<TextView
android:layout_width="match_parent"
android:layout_height="100dp"
android:fontFamily="sans-serif"
android:paddingVertical="20dp"
android:text="Create new account"
android:textAlignment="center"
android:textColor="#000"
android:textSize="40sp"
android:layout_marginBottom="25dp"
/>
<EditText
android:id="#+id/nameR"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Full name"
android:textColorHint="#fff"
android:textSize="25sp"
android:layout_marginHorizontal="25dp"
android:layout_marginBottom="30dp"
/>
<EditText
android:id="#+id/emailR"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Email"
android:textColorHint="#fff"
android:textSize="25sp"
android:layout_marginHorizontal="25dp"
android:layout_marginBottom="30dp"
/>
<EditText
android:id="#+id/pnumberR"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Phone number"
android:textColorHint="#fff"
android:textSize="25sp"
android:layout_marginHorizontal="25dp"
android:layout_marginBottom="30dp"
/>
<EditText
android:id="#+id/passwordR"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:textColorHint="#fff"
android:textSize="25sp"
android:layout_marginHorizontal="25dp"
android:layout_marginBottom="30dp"
/>
<Button
android:id="#+id/registerB"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="Register"
android:layout_marginHorizontal="30dp"
android:layout_marginBottom="25dp"
android:background="#drawable/button_bg"
/>
<ProgressBar
android:id="#+id/progressB"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="invisible"
/>
</LinearLayout>
I guess you should definitely check(R.layout.activity_create_account2)and whether it is the correct xml for the CreateAccount.java
P.S. While posting questions, always mention the correct name of the xml too.
The following code might be the cause:
if(fAuth.getCurrentUser() != null){
startActivity(new Intent(getApplicationContext(),Menu.class));
finish();
}
Can you check if it's going into the if block?
All I want to do is start a new intent on click of a button. Here is my code(I have removed irrelevant parts):
activity_login.xml:
<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:gravity="center_horizontal"
tools:context="com.example.android.altro.LoginActivity">
<!-- Login progress -->
<ProgressBar
android:id="#+id/login_progress"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:visibility="gone" />
<ScrollView
android:id="#+id/login_form"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/email_login_form"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<AutoCompleteTextView
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/prompt_email"
android:inputType="textEmailAddress"
android:maxLines="1"
android:textColor="#color/colorWhite"
android:singleLine="true" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/prompt_password"
android:imeActionId="#+id/login"
android:imeActionLabel="#string/action_sign_in_short"
android:imeOptions="actionUnspecified"
android:inputType="textPassword"
android:maxLines="1"
android:singleLine="true" />
</android.support.design.widget.TextInputLayout>
<Button
android:id="#+id/email_sign_up_button"
style="?android:textAppearanceMedium"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/rounded_button"
android:onClick="registerNewUser"
android:text="#string/action_sign_up"
android:textAllCaps="false" />
</LinearLayout>
</ScrollView>
</LinearLayout>
On clicking #+id/email_sign_up_button registerNewUser is called. I have defined this fuction in LoginActivity.java:
public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<Cursor> {
/**
* Id to identity READ_CONTACTS permission request.
*/
private static final int REQUEST_READ_CONTACTS = 0;
/**
* A dummy authentication store containing known user names and passwords.
* TODO: remove after connecting to a real authentication system.
*/
private static final String[] DUMMY_CREDENTIALS = new String[]{
"foo#example.com:hello", "bar#example.com:world"
};
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private UserLoginTask mAuthTask = null;
// UI references.
private AutoCompleteTextView mEmailView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Set up the login form.
mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
populateAutoComplete();
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
mEmailSignInButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
/* Button mRegisterButton = (Button) findViewById(R.id.email_sign_up_button);
mRegisterButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), RegisterActivity.class);
startActivity(intent);
}
});*/
}
public void registerNewUser(View view) {
Intent intent = new Intent(this, RegisterActivity.class);
startActivity(intent);
}
}
I also tried doing it by finding view and then creating an intent (the code is commented out in onCreate() method. That also gave me the same error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.altro/com.example.android.altro.RegisterActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
You have only one Button with id email_sign_up_button
Please check your layout. Also try replacing
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
With
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_up_button);
Why I cannot retrieve data from SQLite? Have I missed out something? I have read many documentation and tried to work it out, but still fail.
WorkDetailsTable.java
Button btn1=(Button)findViewById(R.id.button2);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
AlertDialog.Builder builder=new AlertDialog.Builder(WorkDetailsTable.this);
builder.setTitle("Data Saved");
builder.setMessage("Are you sure you want to save?");
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int ii) {
long ab = ts.insertTimeSheet(name, weather, date, status);
Toast.makeText(context, "Data Saved", Toast.LENGTH_SHORT).show();
Intent intent=new Intent(WorkDetailsTable.this,DisplayData.class);
intent.putExtra("name",name); //name will be used in another class
startActivity(intent);
DisplayDate.java
public class DisplayData extends AppCompatActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.displaydata);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
final String name1 = getIntent().getExtras().getString("name");
Toast.makeText(getApplicationContext(),name1, Toast.LENGTH_SHORT).show();
if(name1.equals("John"))
{
SQLiteDatabase db=(new MyDatabaseHelper(this)).getReadableDatabase();
Cursor cursor=db.rawQuery("SELECT Weather,Date,Status FROM Information WHERE Name = ?",new String[]{""+name1});
if(cursor.getCount()==1)
{
String weather=cursor.getString(cursor.getColumnIndex("Weather"));
String date=cursor.getString(cursor.getColumnIndex("Date"));
String status=cursor.getString(cursor.getColumnIndex("Status"));
}
db.close();
}
displaydata.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<HorizontalScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dp" >
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:stretchColumns="|"
android:layout_marginBottom="25dp">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/tableRow1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView10"
android:background="#drawable/cell_shape"
android:textSize="17sp"
android:text="weather"/>
<TextView android:id="#+id/textView111"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="17sp"
android:background="#drawable/cell_shape"
android:text="date"/>
<TextView android:id="#+id/textView11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="17sp"
android:background="#drawable/cell_shape"
android:text="status"/>
</TableRow>
// <TableRow>
// <TextView android:id="#+id/textView1111"
// android:layout_width="wrap_content"
// android:layout_height="wrap_content"
// android:textSize="17sp"
// android:background="#drawable/cell_shape"/>
</TableRow>
</TableLayout>
</HorizontalScrollView>
</LinearLayout>
</ScrollView>
I also tried with this but no luck
TextView tvTemp=(TextView)findViewById(R.id.textView1111);
tvTemp.setText(weather + date + status);
The data should be retrieved and display in another class by row, not on editText. How can I do to achieve this?
Once you clicked yes,then you are moving to next activity and passing name to it:
public class DisplayData extends AppCompatActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.displaydata);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
Bundle bundle=getIntent().getExtras();
String name="";
if(bundle!=null)
{
name=bundle.getString("name");
}
//check whether you get the name value here or not..(use log)
SQLiteDatabase db=(new MyDatabaseHelper(this)).getReadableDatabase();
Cursor cursor=db.rawQuery("SELECT Weather,Date,Status FROM Information WHERE Name = ?",new String[]{""+name1});
if(cursor.getCount()==1)
{
String weather=cursor.getString(cursor.getColumnIndex("Weather"));//give the proper index of weather and same for rest.
String date=cursor.getString(cursor.getColumnIndex("Date"));
String status=cursor.getString(cursor.getColumnIndex("Status"));
}
db.close();
}
I want to get Values from EditText dynamically.. I have a lot of EditText generated when user press add button..When User presses add Button it generates 3 Edittext each time. I dont know how to get the values from this dynamically generated EdiTtext . Now My question is how can i get the values from The 3 Edittext on each row. ALso I need to verify that if user removed the view or not. Please help I am new android development.This should happen when a user presses on Save Button. Thanks in advance!
This is class .
public class SecondActivity extends Activity {
Button saveBtn,cancelBtn,addBtn;
RelativeLayout layout;
EditText third,first,second;
LinearLayout Container;
int counter=0;
int all=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
saveBtn=(Button) findViewById(R.id.save);
cancelBtn=(Button) findViewById(R.id.cancel);
Container=(LinearLayout) findViewById(R.id.container);
addBtn=(Button) findViewById(R.id.addBtn);
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(SecondActivity.this,MainActivity.class);
startActivity(intent);
Toast.makeText(SecondActivity.this, "The Result: "+all,Toast.LENGTH_LONG).show();
finish();
}
});
cancelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(SecondActivity.this,MainActivity.class);
startActivity(intent);
finish();
}
});
addBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
LayoutInflater layoutInflater =
(LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View addView = layoutInflater.inflate(R.layout.row, null);
Button buttonRemove = (Button)addView.findViewById(R.id.remove);
// EditText ed1=(EditText) findViewById(R.id.editText1);
// EditText ed2=(EditText) findViewById(R.id.editText2);
// EditText ed3=(EditText) findViewById(R.id.editText3);
// all=all+Integer.parseInt(ed1.getText().toString())+Integer.parseInt(ed2.getText().toString())+Integer.parseInt(ed3.getText().toString());
buttonRemove.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((LinearLayout)addView.getParent()).removeView(addView);
}});
Container.addView(addView);
}});
}
}
This is my row.xml .which i am using as a view in java code.
<?xml version="1.0" encoding="utf-8"?>
<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:layout_margin="10dip" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Field 1" />
<EditText
android:id="#+id/editText1"
android:layout_width="70dip"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:inputType="numberPassword" >
</EditText>
<EditText
android:id="#+id/editText2"
android:layout_width="70dip"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/editText1"
android:layout_alignBottom="#+id/editText1"
android:layout_toRightOf="#+id/editText1"
android:inputType="numberPassword" />
<Button
android:id="#+id/remove"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/editText2"
android:layout_alignParentRight="true"
android:text="Remove" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/editText2"
android:layout_alignLeft="#+id/editText2"
android:text="Field 2" />
<EditText
android:id="#+id/editText3"
android:layout_width="70dip"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/editText2"
android:layout_alignBottom="#+id/editText2"
android:layout_toRightOf="#+id/editText2"
android:editable="false"
tools:ignore="Deprecated" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/editText3"
android:layout_alignLeft="#+id/editText3"
android:text="Field 3" />
</RelativeLayout>
This is my layout which is attached with my activity class.
<?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:layout_alignParentTop="true"
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=".SecondActivity" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/addBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Add" />
</RelativeLayout>
<ScrollView
android:layout_width="wrap_content"
android:layout_height="300dp" >
<LinearLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="#+id/save"
android:layout_width="146dip"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:text="Save" />
<Button
android:id="#+id/cancel"
android:layout_width="146dip"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:text="Cancel" />
<EditText
android:id="#+id/editText1"
android:layout_width="70dip"
android:layout_height="wrap_content"
android:layout_above="#+id/save"
android:layout_alignParentLeft="true"
android:editable="false"
android:hint="T 1"
tools:ignore="Deprecated" >
</EditText>
<EditText
android:id="#+id/editText2"
android:layout_width="70dip"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/editText1"
android:layout_toRightOf="#+id/editText1"
android:editable="false"
android:hint="T 2"
tools:ignore="Deprecated" >
</EditText>
<EditText
android:id="#+id/editText3"
android:layout_width="70dip"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/editText2"
android:layout_toRightOf="#+id/editText2"
android:editable="false"
android:hint="T 3"
tools:ignore="Deprecated" />
<EditText
android:id="#+id/editText4"
android:layout_width="70dip"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/editText3"
android:layout_alignParentRight="true"
android:editable="false"
android:hint="T 4"
tools:ignore="Deprecated,HardcodedText" />
</RelativeLayout>
</LinearLayout>
This is your edited SecondActivity.java
public class SecondActivity extends Activity {
Button saveBtn, cancelBtn, addBtn;
RelativeLayout layout;
EditText third, first, second;
LinearLayout Container;
int counter = 0;
int all = 0;
int tag = 0;
ArrayList<Integer> dynamicLayoutsTags;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
saveBtn = (Button) findViewById(R.id.save);
cancelBtn = (Button) findViewById(R.id.cancel);
Container = (LinearLayout) findViewById(R.id.container);
addBtn = (Button) findViewById(R.id.addBtn);
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (dynamicLayoutsTags.size() > 0) {
for (int i = 0; i < dynamicLayoutsTags.size(); i++) {
View getView = Container
.findViewWithTag(dynamicLayoutsTags.get(i));
EditText editText1 = (EditText) getView
.findViewById(R.id.editText1);
EditText editText2 = (EditText) getView
.findViewById(R.id.editText2);
EditText editText3 = (EditText) getView
.findViewById(R.id.editText3);
Toast.makeText(
SecondActivity.this,
"Row " + i + " : " + "editext 1 is : "
+ editText1.getText()
+ " editext 2 is : "
+ editText2.getText()
+ " editext 3 is : "
+ editText3.getText(),
Toast.LENGTH_LONG).show();
}
}
Intent intent = new Intent(SecondActivity.this,
MainActivity.class);
startActivity(intent);
Toast.makeText(SecondActivity.this, "The Result: " + all,
Toast.LENGTH_LONG).show();
finish();
}
});
cancelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SecondActivity.this,
MainActivity.class);
startActivity(intent);
finish();
}
});
addBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View addView = layoutInflater.inflate(R.layout.row, null);
Button buttonRemove = (Button) addView
.findViewById(R.id.remove);
addView.setTag(tag);
buttonRemove.setTag(tag);
dynamicLayoutsTags.add(tag);
Container.addView(addView);
tag++;
buttonRemove.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// ((LinearLayout) addView.getParent())
// .removeView(addView);
Integer removeTag = (Integer) v.getTag();
View deleteView = Container.findViewWithTag(removeTag);
Container.removeView(deleteView);
dynamicLayoutsTags.remove(removeTag);
}
});
}
});
}
#Override
protected void onResume() {
super.onResume();
tag = 0;
dynamicLayoutsTags = new ArrayList<Integer>();
}
}