Search code examples
javaandroidfirebasefirebase-realtime-databaseandroid-textinputedittext

Disabling Edittexts at start and Navigate to another activity if data not available


I have two activities SetupActivity , DashboardActivity. I'm Using Firebase Authentication and checking user existence. The flow of application for a new user is open App->MainActivity->RegisterFragment->SetupActivity->DashboardActivity. This is my SetupActivity.Java


import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.kloadingspin.KLoadingSpin;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import br.com.simplepass.loadingbutton.customViews.CircularProgressButton;
import de.hdodenhof.circleimageview.CircleImageView;

public class SetupActivity extends AppCompatActivity implements LocationListener, View.OnClickListener {

    private static final int REQUEST_LOCATION = 1 ;
    private TextInputLayout TIPFullname, TIPCurrentLocation, TIPMobile, TIPBloodGroup, TIPLastDonated;
    private TextInputEditText FullName, CurrentLocation, Mobile, BloodGroup, LastDonated;
    private AutoCompleteTextView PermanentLocation;
    private CircularProgressButton SaveInformationButton;
    private CircleImageView ProfileImage;
    private SimpleDateFormat dateFormatter;
    private LocationManager locationManager;
    private LocationListener locationListener;
    private DatePickerDialog datePickerDialog;
    private FirebaseAuth mAuth;
    private DatabaseReference UsersRef;
    private StorageReference UserProfileImageRef;
    private ValidationHelper validation;
    KLoadingSpin a;

    String currentUserID;
    final static int Gallery_Pick = 1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setup);

        String[] cities = getResources().getStringArray(R.array.cities);
//        Toast.makeText(this, "First select profile image and then enter details", Toast.LENGTH_LONG).show();
        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_LOCATION);

        dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
        mAuth = FirebaseAuth.getInstance();
        currentUserID = mAuth.getCurrentUser().getUid();
        UsersRef = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID);
        UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("Profile Images");
        a = findViewById(R.id.KLoadingSpin);
        TIPFullname = findViewById(R.id.tip_fullname);
        TIPCurrentLocation = findViewById(R.id.tip_curr_location);
        TIPBloodGroup = findViewById(R.id.tip_blood_group);
        TIPLastDonated = findViewById(R.id.tip_last_donated);
        TIPMobile = findViewById(R.id.tip_mobile);
        FullName = findViewById(R.id.reg_fullname);
        CurrentLocation = findViewById(R.id.reg_curr_location);
        Mobile = findViewById(R.id.reg_mobile);
        BloodGroup = findViewById(R.id.reg_blood_group);
        PermanentLocation = findViewById(R.id.reg_per_location);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.dropdown_menu_popup_item,cities);
        PermanentLocation.setAdapter(adapter);
        PermanentLocation.setThreshold(2);
        LastDonated = findViewById(R.id.reg_last_donated);
        LastDonated.setInputType(InputType.TYPE_NULL);
        SaveInformationButton = findViewById(R.id.btn_save);
        ProfileImage = findViewById(R.id.setup_profile_image);
        validation = new ValidationHelper(this);



        TIPCurrentLocation.setEndIconOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                getLocation();
            }
        });

         SetDateTimeField();


        SaveInformationButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                checkValidation();
                SaveAccountSetupInformation();
            }
        });

        ProfileImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent galleryIntent = new Intent();
                galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
                galleryIntent.setType("image/*");
                startActivityForResult(galleryIntent, Gallery_Pick);
            }
        });


        UsersRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()) {
                    if (dataSnapshot.hasChild("profileimage")) {
                        String image = dataSnapshot.child("profileimage").getValue().toString();
                        Picasso.with(SetupActivity.this).load(image).placeholder(R.drawable.default_profile).into(ProfileImage);
                    } else {
                        Toast.makeText(SetupActivity.this, "Please select profile image first.", Toast.LENGTH_LONG).show();
                        tipDisabled();
                    }
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }

    private void SetDateTimeField() {

        LastDonated.setOnClickListener(this);
        Calendar newCalendar = Calendar.getInstance();
        datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {

            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                Calendar newDate = Calendar.getInstance();
                newDate.set(year, monthOfYear, dayOfMonth);
                LastDonated.setText(dateFormatter.format(newDate.getTime().toString()));
            }

        },newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));

    }

    @Override
    public void onClick(View view) {
        if(view == LastDonated) {
           datePickerDialog.show();
        }
    }

    private void checkValidation() {
        if (!validation.isEditTextFilled(BloodGroup, TIPBloodGroup, "Enter Blood Group")) {
            return;
        }

        if (!validation.isEditTextBloodGroup(BloodGroup, TIPBloodGroup, "Enter Correct BloodGroup!!")) {
            return;
        }

    }

    private void getLocation() {

        if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
        ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_BACKGROUND_LOCATION) != PackageManager.PERMISSION_GRANTED)

        {
            ActivityCompat.requestPermissions(
                    this,
                    new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_BACKGROUND_LOCATION},
                    75
            );
        }

        isLocationEnabled();
        Location loc=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        String longitude = "Longitude: " +loc.getLongitude();
        String latitude = "Latitude: " +loc.getLatitude();

        /*----------to get City-Name from coordinates ------------- */
        String cityName=null;
        Geocoder gcd = new Geocoder(getBaseContext(),
                Locale.getDefault());
        List<Address> addresses;
        try {
            addresses = gcd.getFromLocation(loc.getLatitude(), loc
                    .getLongitude(), 1);
            if (addresses.size() > 0)
                System.out.println(addresses.get(0).getLocality());
            cityName=addresses.get(0).getLocality();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String s = " "+cityName;
        CurrentLocation.setText(s);


    }


    private boolean isLocationEnabled(){
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(
                LocationManager.NETWORK_PROVIDER
        );
    }







    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == Gallery_Pick && resultCode == RESULT_OK && data != null) {
            Uri imageUri = data.getData();

            CropImage.activity(imageUri)
                    .setGuidelines(CropImageView.Guidelines.ON)
                    .setAspectRatio(1, 1)
                    .start(this);
        }

        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);

            if (resultCode == RESULT_OK) {

                a.setVisibility(View.VISIBLE);
                a.startAnimation();
                a.setIsVisible(true);

                Uri resultUri = result.getUri();

                StorageReference filePath = UserProfileImageRef.child(currentUserID + ".jpg");

                filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                        if (task.isSuccessful()) {

                            Toast.makeText(SetupActivity.this, "Please Wait", Toast.LENGTH_SHORT).show();

                            Task<Uri> result = task.getResult().getMetadata().getReference().getDownloadUrl();

                            result.addOnSuccessListener(new OnSuccessListener<Uri>() {
                                @Override
                                public void onSuccess(Uri uri) {
                                    final String downloadUrl = uri.toString();

                                    UsersRef.child("profileimage").setValue(downloadUrl)
                                            .addOnCompleteListener(new OnCompleteListener<Void>() {
                                                @Override
                                                public void onComplete(@NonNull Task<Void> task) {
                                                    if (task.isSuccessful()) {
                                                        Toast.makeText(SetupActivity.this, "Please Wait", Toast.LENGTH_LONG).show();
                                                        Intent selfIntent = new Intent(SetupActivity.this, SetupActivity.class);
                                                        startActivity(selfIntent);
                                                        tipEnabled();
                                                        Toast.makeText(SetupActivity.this, "Your Profile image looks great!!!...", Toast.LENGTH_SHORT).show();
                                                        a.stopAnimation();
                                                        a.setVisibility(View.GONE);
                                                        a.setIsVisible(false);

                                                    } else {
                                                        String message = task.getException().getMessage();
                                                        Toast.makeText(SetupActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
                                                        tipDisabled();
                                                        a.stopAnimation();
                                                        a.setVisibility(View.GONE);
                                                        a.setIsVisible(false);
                                                    }
                                                }
                                            });
                                }
                            });
                        }
                    }
                });
            } else {
                Toast.makeText(SetupActivity.this, "Error: Image not selected or not cropped", Toast.LENGTH_SHORT).show();
                tipDisabled();
                a.stopAnimation();
                a.setVisibility(View.GONE);
                a.setIsVisible(false);
            }
        }
    }

    private void SaveAccountSetupInformation() {
        String fullname = FullName.getText().toString();
        String currentlocation = CurrentLocation.getText().toString();
        String mobile = Mobile.getText().toString();
        String permanentlocation = PermanentLocation.getText().toString();
        String bloodgroup = BloodGroup.getText().toString();
        String lastdonated = LastDonated.getText().toString();

        if (TextUtils.isEmpty(currentlocation)) {
            Toast.makeText(this, "Please click button and get your current city...", Toast.LENGTH_SHORT).show();
        } else if (TextUtils.isEmpty(mobile)) {
            Toast.makeText(this, "Please write your mobile no...", Toast.LENGTH_SHORT).show();
        } else if (TextUtils.isEmpty(permanentlocation)) {
            Toast.makeText(this, "Please enter your permanent city...", Toast.LENGTH_SHORT).show();
        } else if (TextUtils.isEmpty(fullname)) {
            Toast.makeText(this, "Please enter your full name...", Toast.LENGTH_SHORT).show();
        } else if (TextUtils.isEmpty(bloodgroup)) {
            Toast.makeText(this, "Please enter your bloodgroup...", Toast.LENGTH_SHORT).show();
        }


        else {
            a.setVisibility(View.VISIBLE);
            a.startAnimation();
            a.setIsVisible(true);
            SaveInformationButton.startAnimation();
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                    WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);

            HashMap userMap = new HashMap();
            userMap.put("bloodgroup", bloodgroup);
            userMap.put("fullname", fullname);
            userMap.put("mobile", mobile);
            userMap.put("currentlocation", currentlocation);
            userMap.put("permanentlocation", permanentlocation);
            userMap.put("timesdonated","0");
            userMap.put("lastdonatedon",lastdonated);
            UsersRef.updateChildren(userMap).addOnCompleteListener(new OnCompleteListener() {
                @Override
                public void onComplete(@NonNull Task task) {
                    if (task.isSuccessful()) {
                        SendUserToMainActivity();
                        Toast.makeText(SetupActivity.this, "your Account is created Successfully.", Toast.LENGTH_LONG).show();
                    } else {
                        a.stopAnimation();
                        a.setVisibility(View.GONE);
                        a.setIsVisible(false);
                        SaveInformationButton.revertAnimation();
                        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
                        String message = task.getException().getMessage();
                        Toast.makeText(SetupActivity.this, "Error Occured: " + message, Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    }

    private void tipDisabled()
    {
        TIPCurrentLocation.setEnabled(false);
        TIPMobile.setEnabled(false);
        TIPBloodGroup.setEnabled(false);
        TIPFullname.setEnabled(false);
        TIPLastDonated.setEnabled(false);
        PermanentLocation.setEnabled(false);
    }

    private void tipEnabled()
    {
        TIPCurrentLocation.setEnabled(true);
        TIPMobile.setEnabled(true);
        TIPBloodGroup.setEnabled(true);
        TIPFullname.setEnabled(true);
        TIPLastDonated.setEnabled(true);
        PermanentLocation.setEnabled(true);
    }


    private void SendUserToMainActivity() {
        Intent mainIntent = new Intent(SetupActivity.this, DashboardActivity.class);
        mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(mainIntent);
        finish();
    }

    @Override
    public void onLocationChanged(Location loc) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

        Toast.makeText(this,"Enable Location and Internet to get Location",Toast.LENGTH_LONG);

    }
}

` Here i want the user to select the profile picture first and then have to fill text in edittexts. So,i need to disable all the edittexts and after the profile image is set i have to enable them. for this purpose i have written tipdisabled() and tipEnabled() methods. But i donno where to use them correctly. Please Clarify this.


Solution

  • You can merge your code like this:

    private void tipEnabled(Boolean isEnabled)
        {
            TIPCurrentLocation.setEnabled(isEnabled);
            TIPMobile.setEnabled(isEnabled);
            TIPBloodGroup.setEnabled(isEnabled);
            TIPFullname.setEnabled(isEnabled);
            TIPLastDonated.setEnabled(isEnabled);
            PermanentLocation.setEnabled(isEnabled);
        }
    

    To achieve your flow, put tipEnabled(false) inside your choose image click Listener and tipEnabled(true) in the onResult, which i think in your case is onActivityResult().

    You should seggerate you code as right now your activity looks like a data dump which is handling too many responsibilities at the moment. Try creating Presenter classes, Controller classes or ViewModel classes to delegate all this functioning to them. You Activity should only act as a container and should not be doing validations or any logical processing but rather doing delegation.