gpt4 book ai didi

java - 如果数据不可用,则在开始时禁用 Edittexts 并导航到另一个 Activity

转载 作者:行者123 更新时间:2023-12-01 17:17:54 26 4
gpt4 key购买 nike

我有两个 Activity SetupActivity 和 DashboardActivity。我正在使用 Firebase 身份验证并检查用户是否存在。新用户申请流程为打开App->MainActivity->RegisterFragment->SetupActivity->DashboardActivity。这是我的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);

}
}

` 这里我希望用户首先选择个人资料图片,然后必须在编辑文本中填充文本。因此,我需要禁用所有编辑文本,并且在设置个人资料图像后我必须启用它们。为此,我编写了tipdisabled() 和tipEnabled() 方法。但我不知道在哪里正确使用它们。请澄清这一点。

最佳答案

您可以像这样合并代码:

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

要实现您的流程,请将 tipEnabled(false) 放在您选择的图像中,单击监听器并将 tipEnabled(true) 放在 onResult 中,我认为在您的情况下是 <强>onActivityResult()。

您应该隔离代码,因为现在您的 Activity 看起来像一个数据转储,目前正在处理太多的职责。尝试创建 Presenter 类、Controller 类或 ViewModel 类,将所有这些功能委托(delegate)给它们。您的 Activity 应该只充当容器,不应该进行验证或任何逻辑处理,而应该进行委托(delegate)。

关于java - 如果数据不可用,则在开始时禁用 Edittexts 并导航到另一个 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61349918/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com