gpt4 book ai didi

java - 在我的应用程序中,我可以进入图库,但在选择图像后,它不会覆盖 "OnActivityResult"方法

转载 作者:行者123 更新时间:2023-12-01 16:22:32 25 4
gpt4 key购买 nike

我正在尝试更改我的应用程序中的个人资料图片和封面图片。我的代码中一切都很好,除了我的封面和个人资料图片没有改变。

这是我的代码文件附件。

在我的应用程序中,我可以进入图库,但在选择图像后,它不会使用“OnActivityResult”覆盖方法。虽然它停留在 ProfileFragment Activity 上,但不会转到 OnActivityResult 方法。在 ProfileFragment 中,它永远不会转到“OnActivityResult”方法。 RESULT_OK 始终为 -1。

这是我的 ProfileActivity.java

public class ProfileActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
FirebaseAuth firebaseAuth;
private TextView welcomeUserTv;
ActionBar actionBar;

ExpandableListAdapter expandableListAdapter;
ExpandableListView expandableListView;
List<MenuModel> headerList = new ArrayList<>();
HashMap<MenuModel, List<MenuModel>> childList = new HashMap<>();

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

Toolbar mtoolbar_3p = findViewById(R.id.toolbar_3p);
setSupportActionBar(mtoolbar_3p);

expandableListView = findViewById(R.id.expNav_3p);

DrawerLayout drawer_3p = findViewById(R.id.drawer_layout_3p);
ActionBarDrawerToggle toggle_3p = new ActionBarDrawerToggle(
this, drawer_3p, mtoolbar_3p, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
if (drawer_3p != null) {
drawer_3p.addDrawerListener(toggle_3p);
}
toggle_3p.syncState();

NavigationView navigationView = findViewById(R.id.navView_3p);
if (navigationView != null) {
navigationView.setNavigationItemSelectedListener(this);
}

firebaseAuth = FirebaseAuth.getInstance();
checkUserStatus();

//Bottom Navigation
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_nav);
bottomNavigationView.setOnNavigationItemSelectedListener(selectedListener);
//Home fragment transaction, Default on Startup
FirebaseUser user = firebaseAuth.getCurrentUser();

ProfileFragment profileFragment = new ProfileFragment();
FragmentTransaction pft1 = getSupportFragmentManager().beginTransaction();
pft1.replace(R.id.content_frameLayout_inProfile, profileFragment, "");
pft1.commit();
}

private BottomNavigationView.OnNavigationItemSelectedListener selectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
//FirebaseUser user = firebaseAuth.getCurrentUser();
switch(item.getItemId()) {
case (R.id.bottom_home):
//Home Fragment Transaction
//actionBar.setTitle("Home");
/*final View addView = getLayoutInflater().inflate(R.layout.nav_header_profile, null);
//set up for model selection
TextView modelTextview = addView.findViewById(R.id.welcomeUser);
modelTextview.setText(user.getEmail());*/
HomeFragment homeFragment = new HomeFragment();
FragmentTransaction hft1 = getSupportFragmentManager().beginTransaction();
hft1.replace(R.id.content_frameLayout_inProfile, homeFragment, "");
hft1.commit();
return true;
case (R.id.bottom_profile):
//Profile Fragment Transaction
//actionBar.setTitle("Profile");
ProfileFragment profileFragment = new ProfileFragment();
FragmentTransaction pft1 = getSupportFragmentManager().beginTransaction();
pft1.replace(R.id.content_frameLayout_inProfile, profileFragment, "");
pft1.commit();
return true;
case (R.id.bottom_mylist):
//MyList Fragment transaction
//actionBar.setTitle("My List");
MyListFragment mylistFragment = new MyListFragment();
FragmentTransaction mlft1 = getSupportFragmentManager().beginTransaction();
mlft1.replace(R.id.content_frameLayout_inProfile, mylistFragment, "");
mlft1.commit();
return true;
}
return false;
}
};

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_logout,menu);
return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if(item.getItemId() == R.id.action_logout) {
Toast.makeText(this, "You've been logged out", Toast.LENGTH_SHORT).show();
firebaseAuth.signOut();
checkUserStatus();
return true;
}
return super.onOptionsItemSelected(item);
}

private void checkUserStatus() {
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user != null) {
//mProfileTv.setText(user.getEmail());
//Toast.makeText(this, "Your Profile", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Not Your Profile", Toast.LENGTH_SHORT).show();
startActivity(new Intent(ProfileActivity.this, MainActivity.class));
finish();
}
}

@Override
protected void onStart() {
checkUserStatus();
super.onStart();
}

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
DrawerLayout drawer = findViewById(R.id.drawer_layout_3p);
drawer.closeDrawer(GravityCompat.START);
return true;
}

}

这是我的 ProfileFragment.java 代码

public class ProfileFragment extends Fragment {
//Firebase auth
FirebaseAuth firebaseAuth;
FirebaseUser user;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
//Firebase storage
StorageReference storageReference;
//path where images of user profile and cover will be stored
String storagePath = "Users_Profile_Cover_Imgs/";

//Views from xml
ImageView mavatarTv, mcoverPic;
TextView mnameTv, memailTv, mphoneTv;
FloatingActionButton mfab;

//Progress Dialog
ProgressDialog pd;

//Permissions constant
private static final int CAMERA_REQUEST_CODE = 100;
private static final int STORAGE_REQUEST_CODE = 200;
private static final int IMAGE_PICK_GALLERY_CODE = 300;
private static final int IMAGE_PICK_CAMERA_CODE = 400;

//Arrays of permission to be required
String cameraPermission[];
String storagePermission[];

//uri of picked image
Uri image_uri;

String profileOrCoverPhoto;

public ProfileFragment() {
// Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_profile, container, false);
firebaseAuth = FirebaseAuth.getInstance();
user = firebaseAuth.getCurrentUser();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("Users");
storageReference = getInstance().getReference();

//init arrays of permission
cameraPermission = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
storagePermission = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
//init views
mavatarTv = view.findViewById(R.id.avatarTv);
mcoverPic = view.findViewById(R.id.coverPic);
memailTv = view.findViewById(R.id.emailTv);
mphoneTv = view.findViewById(R.id.phoneTv);
mnameTv = view.findViewById(R.id.nameTv);
mfab = view.findViewById(R.id.fab);

//init progress dialog
pd = new ProgressDialog(getActivity());

Query query = databaseReference.orderByChild("email").equalTo(user.getEmail());
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
//check until required data get
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ""+ ds.child("name").getValue();
String email = ""+ ds.child("email").getValue();
String phone = ""+ ds.child("phone").getValue();
String image = ""+ ds.child("image").getValue();
String cover = ""+ ds.child("cover").getValue();
//set data
mnameTv.setText(name);
memailTv.setText(email);
mphoneTv.setText(phone);
try {
//If image is received then
Picasso.get().load(image).into(mavatarTv);
} catch (Exception e) {
Picasso.get().load(R.drawable.ic_default_img_white).into(mavatarTv);
}
try {
//If image is received then
Picasso.get().load(cover).into(mcoverPic);
} catch (Exception e) {
}
}
}

@Override
public void onCancelled(@NonNull DatabaseError databaseError) {

}
});

//Fab button click
mfab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showEditProfileDialog();
}
});


return view;

}

private boolean checkStoragePermission() {
//Check if storage permission is enabled or not
//return true if enabled else false
boolean result = ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result;
}

private void requestStoragePermission() {
//request runtime storage permission
requestPermissions(storagePermission, STORAGE_REQUEST_CODE);
}

private boolean checkCameraPermission() {
//Check if storage permission is enabled or not
//return true if enabled else false
boolean result1 = ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.CAMERA)
== (PackageManager.PERMISSION_GRANTED);
boolean result2 = ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result1 && result2;
}

private void requestCameraPermission() {
//request runtime storage permission
requestPermissions(cameraPermission, CAMERA_REQUEST_CODE);
}

private void showEditProfileDialog() {
//Show Dialog containing options: 1.Edit ProfilePic, 2. Edit cover, 3. Edit name, 4. Edit Phone

//Options to show in dialog
String[] options = {"Edit Profile Picture", "Edit Cover Picture", "Edit Name", "Edit Phone Number"};
//alert dialog
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
//set title
builder.setTitle("Choose Action");
//set items to dialog
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(which == 0) {
//Edit Profile pic
pd.setMessage("Updating Profile picture");
profileOrCoverPhoto = "image"; //i.e, changing profile pic, make sure to assign same value
showImagePicDialog();
}
else if (which == 1) {
//Edit cover pic
pd.setMessage("Updating Cover Picture");
profileOrCoverPhoto = "cover"; //i.e, changing profile pic, make sure to assign same value
showImagePicDialog();
}
else if (which == 2) {
//Edit name pic
pd.setMessage("Updating Name");
showNamePhoneUpdateDialog("name");
}
else if (which == 3) {
//Edit phone pic
pd.setMessage("Updating Phone number ");
showNamePhoneUpdateDialog("phone");
}
}
});
//create n show dialog
builder.create().show();

}

private void showNamePhoneUpdateDialog(final String key) {
//
//Custom dialog
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Update "+key);
//set layout of dialog
LinearLayout linearLayout = new LinearLayout(getActivity());
linearLayout.setOrientation(LinearLayout.VERTICAL);
//add edit text
final EditText editText = new EditText(getActivity());
editText.setHint("Enter "+key);
linearLayout.addView(editText);

builder.setView(linearLayout);
//Adding buttons to update
builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = editText.getText().toString().trim();
//validate
if (!TextUtils.isEmpty(value)) {
pd.show();
HashMap<String, Object> result = new HashMap<>();
result.put(key, value);
databaseReference.child(user.getUid()).updateChildren(result)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
pd.dismiss();
Toast.makeText(getActivity(), "Updated...", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
pd.dismiss();
Toast.makeText(getActivity(), ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(getActivity(), "Please enter "+key, Toast.LENGTH_SHORT).show();
}
}
});
//Adding buttons to cancel
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}

private void showImagePicDialog() {
//Show dialog containing options camera and gallery to pic the image
//Options to show in dialog
String[] options = {"Camera", "Gallery"};
//alert dialog
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
//set title
builder.setTitle("Pick Image From");
//set items to dialog
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(which == 0) {
//Camera clicked (Permission required)
if (!checkCameraPermission()) {
requestCameraPermission();
} else {
pickFromCamera();
}
}
else if (which == 1) {
//Gallery clicked (Permission required)
if (!checkStoragePermission()) {
requestStoragePermission();
} else {
pickFromGallery();
}
}
}
});
//create n show dialog
builder.create().show();
}
//First check firebase storage rules

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//This method called when user press allow or deny from permission request dialog
//here we'll handle permission cases
switch (requestCode) {
case CAMERA_REQUEST_CODE: {
//picking from camera, 1st check camera n storage permission allowed or not
if (grantResults.length > 0) {
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean writeStorageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (cameraAccepted && writeStorageAccepted) {
//Permission enabled
pickFromCamera();
}
else {
//Permission denied
Toast.makeText(getActivity(), "Please enable Camera & Storage permission", Toast.LENGTH_SHORT).show();
}
}
}
break;
case STORAGE_REQUEST_CODE: {
//picking from gallery, 1st check storage permission allowed or not
if (grantResults.length > 0) {
boolean writeStorageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (writeStorageAccepted) {
//Permission enabled
Toast.makeText(getActivity(), "req code:"+requestCode, Toast.LENGTH_SHORT).show();
System.out.println("req code:"+requestCode);
pickFromGallery();
}
else {
//Permission denied
Toast.makeText(getActivity(), "Please enable Storage permission", Toast.LENGTH_SHORT).show();
}
}
}
break;
}
}

@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (requestCode == RESULT_OK ) {
Toast.makeText(getActivity(), "OnActivityResult method", Toast.LENGTH_SHORT).show();

if (requestCode == IMAGE_PICK_GALLERY_CODE) {
//image is picked from gallery, get uri of image
image_uri = data.getData();
Toast.makeText(getActivity(), "Gallery Pic Selected", Toast.LENGTH_SHORT).show();
uploadProfileCoverPhoto(image_uri);
}
/*if (requestCode == IMAGE_PICK_CAMERA_CODE) {
//image is picked from gallery, get uri of image
image_uri = data.getData();
uploadProfileCoverPhoto(image_uri);
}*/
}

super.onActivityResult(requestCode, resultCode, data);
}

private void uploadProfileCoverPhoto(Uri uri) {
pd.show();

String filePathNName = storagePath+ ""+ profileOrCoverPhoto+ ""+ user.getUid();
StorageReference storageReference2nd = storageReference.child(filePathNName);
storageReference2nd.putFile(uri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//image is uploaded to storage, now gets its url and store in usrs database
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful());
Uri downloadUri = uriTask.getResult();

//check if image is uploaded or not and url is received
if(uriTask.isSuccessful()) {
//image uploaded, so add/update url in users db
HashMap<String, Object> results = new HashMap<>();

results.put(profileOrCoverPhoto, downloadUri.toString());
databaseReference.child(user.getUid()).updateChildren(results)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
pd.dismiss(); //image url in db of user added
Toast.makeText(getActivity(), "Image Updated...", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
pd.dismiss();
Toast.makeText(getActivity(), "Error updating image", Toast.LENGTH_SHORT).show();
}
});
} else {
pd.dismiss();
Toast.makeText(getActivity(), "Some error occurred", Toast.LENGTH_SHORT).show();
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
pd.dismiss();
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}

private void pickFromCamera() {
//intent of picking image from device camera
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Temp Pic");
values.put(MediaStore.Images.Media.DESCRIPTION, "Temp Description");

//put image uri
image_uri = getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

//Intent to start camera
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, IMAGE_PICK_CAMERA_CODE);
}

private void pickFromGallery() {
//pick from gallery
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
//Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, IMAGE_PICK_GALLERY_CODE);

Toast.makeText(getActivity(), "Gallery Image", Toast.LENGTH_SHORT).show();
System.out.println("Hello Gallery: "+getTargetRequestCode()+" result_ok:"+RESULT_OK);

//Intent intent = new Intent(Intent.ACTION_PICK, Media.EXTERNAL_CONTENT_URI);
//getParent().startActivityForResult(intent, GALLERY);


}
}

所有导入均正确。

这是我的 list 文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.shortlisted">

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".LoginActivity"></activity>
<activity android:name=".ProfileActivity"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".RegisterActivity" />
<activity android:name=".InfoActivity" />
<activity
android:name=".MainActivity"
android:theme="@style/AppTheme.NoActionBar">

</activity>
</application>

</manifest>

最佳答案

尝试重写ProfileActivity中的onActivityResult方法。

首先会调用 ProfileActivity 的 onActivityResult 方法。因此,当您重写 ProfileActivity 中的方法时,它会调用 super(),而 super() 又会为相应的 fragment 提供结果。

希望对您有帮助!

关于java - 在我的应用程序中,我可以进入图库,但在选择图像后,它不会覆盖 "OnActivityResult"方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62232716/

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