I've one MainActivity, and few fragments on it.
I am trying to change a ImageView in a fragment using Gallery. But once image is selected, the MainActivity get refresh, which changes the MainActivity back to the default fragment.
Getting permission
textViewChangeImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG,"Select Image executed");
requestPermissions(
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_CODE);
}
});
On Request permission
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Log.d(TAG,"Select Image Permission executed");
if(requestCode == REQUEST_CODE){
progressDialogUploadDp.setMessage("Uploading...");
progressDialogUploadDp.show();
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
intent.putExtra("imageUpdate","true");
startActivityForResult(intent,REQUEST_CODE);
}else{
Toast.makeText(getActivity(), "No Permission Granted", Toast.LENGTH_SHORT).show();
}
return;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
On Activity Result
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK && data != null){
try {
Uri uri = data.getData();
StorageReference filepath =
storageReference.child("Photos").child("DPs").child(ID).child("profilepicture.jpg");
InputStream inputStream = getActivity().getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imageviewpropic.setImageBitmap(bitmap);
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialogUploadDp.hide();
progressDialogUploadDp.dismiss();
}
});
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Looking forward for a solution!
Updated ---
MainActivity
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState==null) {
mRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("questioners")) {
adapter = new SectionStatePagerAdapter(getSupportFragmentManager());
adapter.addFragment(new HomeFragment(), "HomeFragment");
viewPager.setAdapter(adapter);
}}
}
Back form gallery , activity will run onActivityResult then it will run onResume .
so you can set a FLAG at onActivityResult and make an IF in onResume to set your fragment.
From what you've said it looks like your activity is calling onCreate method and setting default fragment again. What you can do is to in onCreate() create new fragment only if there is no saved state.
if(savedInstanceState==null) setFragment(fragment);
Related
After login successful this returns to Main2Activity and I can log in again and again.but start app again after closing and removing from recent list it start in MainActivity. how to directly navigate Main2Activity to MainActivity after if condition is true.
Main2Activity code
public class Main2Activity extends AppCompatActivity {
private static final String TAG = "Main2Activity";
int AUTHUI_REQUEST_CODE = 1001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
if (FirebaseAuth.getInstance().getCurrentUser() != null) {
startActivity(new Intent(this, MainActivity.class));
this.finish();
}
}
public void loginRegister(View view) {
List<AuthUI.IdpConfig> providers = Arrays.asList(
new AuthUI.IdpConfig.EmailBuilder().build(),
new AuthUI.IdpConfig.GoogleBuilder().build(),
new AuthUI.IdpConfig.PhoneBuilder().build()
);
Intent intent = AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(providers)
.setTosAndPrivacyPolicyUrls("https://example.com","https://example.com")
.setLogo(R.drawable.i789)
.build();
startActivityForResult(intent, AUTHUI_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == AUTHUI_REQUEST_CODE){
if (requestCode == RESULT_OK){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
Log.d(TAG, "onActivityResult: "+ user.getEmail());
if (user.getMetadata().getCreationTimestamp() == user.getMetadata().getLastSignInTimestamp()){
Toast.makeText(this, "Welcome", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Welcome back again", Toast.LENGTH_SHORT).show();
}
Intent t = new Intent(this,MainActivity.class);
startActivity(t);
this.finish();
}else{
IdpResponse response =IdpResponse.fromResultIntent(data);
if (response == null){
Log.d(TAG, "onActivityResult: the user has cancelled the sign in request");
}else {
Log.e(TAG, "onActivityResult: ",response.getError() );
}
}
}
}
}
code- Main Activity
public class MainActivity extends AppCompatActivity implements FirebaseAuth.AuthStateListener {
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private void startLogin(){
Intent intent = new Intent(this,Main2Activity.class);
startActivity(intent);
finish();
}
public void signout(View view){
AuthUI.getInstance().signOut(this);
}
#Override
protected void onStart() {
super.onStart();
FirebaseAuth.getInstance().addAuthStateListener(this);
}
#Override
protected void onStop() {
super.onStop();
FirebaseAuth.getInstance().removeAuthStateListener(this);
}
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() == null){
startLogin();
return;
}
firebaseAuth.getCurrentUser().getIdToken(true)
.addOnSuccessListener(new OnSuccessListener<GetTokenResult>() {
#Override
public void onSuccess(GetTokenResult getTokenResult) {
Log.d(TAG, "onSuccess: "+getTokenResult.getToken());
}
});
}
}
I will suggest you that you create a splash screen (startup screen) which will initially on start check for the authentication whether user is logged in or not from the server. All this will be handled in a background thread and the ui thread will carry on the splash screen animation(if you wish any).So if the user is logged in, you navigate to mainActivity else navigate to loginActivity. Hope this helps you.
I'm still new at programming and I tried to build a code scanner for my project.
The problem is the result only show a text. It can't be click or direct to browser.
public class ReaderActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reader);
Button scan_btn = findViewById(R.id.scan_btn);
final Activity activity = this;
IntentIntegrator qrScan = new IntentIntegrator(this);
scan_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
IntentIntegrator integrator = new IntentIntegrator(activity);
integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
integrator.setPrompt("Scan");
integrator.setCameraId(0);
integrator.setBeepEnabled(false);
integrator.setBarcodeImageEnabled(false);
integrator.initiateScan();
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null){
if(result.getContents()==null){
Toast.makeText(this, "You cancelled the scanning", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(this, result.getContents(), Toast.LENGTH_LONG).show();
}
}
else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
can somebody fix this?
you can check if result.getContents() start with "http" or "https" use string.indexOf, get it and put to your browser.
I have an app that scans QR code. And it to show in another activity. How to pass QR Code text to another activity? Or save it in memory?
MainActivity
public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler{
private ZXingScannerView zXingScannerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
zXingScannerView = new ZXingScannerView(getApplicationContext());
setContentView(zXingScannerView);
zXingScannerView.setResultHandler(this);
zXingScannerView.startCamera();
}
#Override
protected void onPause() {
super.onPause();
zXingScannerView.stopCamera();
}
#Override
public void handleResult(Result result) {
Toast.makeText(getApplicationContext(), result.getText(),Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Result");
builder.setMessage(result.getText());
AlertDialog alertDialog = builder.create();
alertDialog.show();
zXingScannerView.resumeCameraPreview(this);
}
}
Call method startActivityForResult(new Intent(this, YourCallbackActivity.class), 1001);
Use setResult() method for get call back in another activity.
#Override
public void handleResult (Result result) {
Intent returnIntent = new Intent();
returnIntent.putExtra("result",String.valueOf(rawResult));
setResult(Activity.RESULT_OK,returnIntent);
finish();
}
now
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1001) {
if (resultCode == RESULT_OK && data != null) {
String result = data.getStringExtra("result");
//do whatever you want
}
}
}
I already did, hope it will help you!!
I just need help on my codes, I'm using Android Studio. Everything is working fine but the recorded video won't show in viewVideo on my layout.
Here's the code:
public class MainActivity extends AppCompatActivity {
static final int REQUEST_VIDEO_CAPTURE = 1;
VideoView resultvideo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button click = (Button)findViewById(R.id.videorec);
resultvideo = (VideoView)findViewById(R.id.videoView);
}
public void dispatchTakeVideoIntent(View v) {
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takeVideoIntent, REQUEST_VIDEO_CAPTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_VIDEO_CAPTURE && resultCode == RESULT_OK) {
Uri videoUri = data.getData();
resultvideo.setVideoURI(videoUri);
}
}
}
Uri videoUri = data.getData();
resultvideo.setVideoURI(videoUri);
// start call missing
resultvideo.start();
I have a fragment and I filled a RecyclerView in it, a post contains a camera and I need to take the information it brings when I take the photo. I do not know how to do it.
Please help.
This is mi code:
PostAdapter.java
public HeaderViewHolder (View itemView) {
super (itemView);
this.mCamera = (ImageView) itemView.findViewById(R.id.ivCamera);
mCameraPhoto = new CameraPhoto(itemView.getContext());
this.mCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
((Activity) v.getContext()).startActivityForResult(mCameraPhoto.takePhotoIntent(), CAMERA_REQUEST_ASIST);
}catch (Exception e){
Log.e("Error camera permission", e.getMessage());
}
}
});
}
MainActivity.java
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
String photoPath = mCameraPhoto.getPhotoPath();
for (Fragment fragment : getSupportFragmentManager().getFragments()) {
fragment.onActivityResult(requestCode, resultCode, data);
Log.d("Result in fragment",":D --> "+photoPath);
}
}
MyFragment.java
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d("Result in fragment",":D");
}
Pass fragment into PostAdapter's constructor.
class PostAdapter {
private Fragment fragment;
public PostAdapter(Fragment fragment) {
this.fragment = fragment;
}
}
then inside onclick
this.mCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
fragment.startActivityForResult(mCameraPhoto.takePhotoIntent(), CAMERA_REQUEST_ASIST);
}catch (Exception e){
Log.e("Error camera permission", e.getMessage());
}
}
});
Use one of getFragmentById() or getFragmentByTag() methods to get the reference to your fragment
You can get the information of the photo you took as the following.
In your fragment
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK){
if(requestCode == CAMERA_REQUEST_ASIST ){
String photoPath = mCameraPhoto.getPhotoPath();
try {
// Update data in your Custom RecyclerView Adapter
// and call notifyDatasetChanged
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}//end if resultCode
}
And more information https://github.com/kosalgeek/PhotoUtil/blob/master/README.md