How to fetch image path file to one Activity to other Activity - java

I have an App that verifies the ID card by clicking photos from both sides, after clicking the picture front-side of the id card the user moves to another activity for clicking the picture back-side of the id card after completing those prosses the user redirect to another activity that the user sees both sides of the document into different ImageView but I don't know how to fetch or pass
those images on this Activity that user can see their ID card for confirmation.
Here is my front side-scan activity
public class Front_Scan extends AppCompatActivity {
ActivityResultLauncher<Intent> activityResultLauncher;
private static final int PERMISSION_CODE = 101;
public String currentPhotoPath;
Button frontImgCap;
Button frontImgCapAgain;
Button frontNext;
ImageView frontImg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_front_scan);
frontImg = findViewById(R.id.Image_id_front);
frontImgCap = findViewById(R.id.imgCapture_front);
frontImgCap.setVisibility(VISIBLE);
frontImgCapAgain = findViewById(R.id.Front_imgCapture_again);
frontImgCapAgain.setVisibility(GONE);
frontNext = findViewById(R.id.front_next);
frontNext.setVisibility(INVISIBLE);
activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult()
, new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
File f = new File(currentPhotoPath);
frontImgCapAgain.setVisibility(VISIBLE);
frontImgCap.setVisibility(INVISIBLE);
frontNext.setVisibility(VISIBLE);
frontImg.setImageURI(Uri.fromFile(f));
}
}
});
frontImgCap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//if system os is >= marshmallow, request runtime permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CAMERA) ==
PackageManager.PERMISSION_DENIED ||
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_DENIED) {
//permission not enable, request it
String[] permission = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
//show popup to request permissions
requestPermissions(permission, PERMISSION_CODE);
} else {
//permission already given
dispatchTakePictureIntent();
}
} else {
//system os < marshmallow
dispatchTakePictureIntent();
}
}
});
}
public void next(View view) {
Intent myIntent = new Intent(Front_Scan.this, back_scan.class);
Front_Scan.this.startActivity(myIntent);
finish();
}
public void scanAgain(View view) {
clearMyFiles();
onCreateLayouts();
frontImg.setImageDrawable(getResources().getDrawable(R.drawable.id_front));
}
void clearMyFiles() {
File imgFile = new File(currentPhotoPath);
if (imgFile != null) {
imgFile.delete();
}
}
public void onCreateLayouts() {
frontImgCap.setVisibility(VISIBLE);
frontImgCapAgain.setVisibility(GONE);
frontNext.setVisibility(INVISIBLE);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSION_CODE:
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
dispatchTakePictureIntent();
} else {
Toast.makeText(this, "permission denied...", Toast.LENGTH_SHORT).show();
}
return;
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "FRONT_ID_JPEG" + timeStamp;
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.nyabaapplication.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
activityResultLauncher.launch(takePictureIntent);
}
}
}
}
Front Scan XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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/background"
android:orientation="vertical"
android:padding="30dp"
tools:context=".Front_Scan">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp"
android:gravity="center"
android:text="Scan Front Side"
android:textAlignment="center"
android:textAllCaps="false"
android:textColor="#color/yellow"
android:textSize="28sp"
android:textStyle="bold" />
<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_gravity="center"
android:layout_marginTop="60dp"
app:cardBackgroundColor="#color/background"
app:cardCornerRadius="22dp"
app:cardElevation="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center">
<ImageView
android:id="#+id/Image_id_front"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:scaleType="fitXY"
android:src="#drawable/id_front" />
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
<android.widget.Button
android:id="#+id/Front_imgCapture_again"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#drawable/flag_transparent"
android:text="Scan Again"
android:onClick="scanAgain"
android:layout_marginTop="8dp"
android:textAllCaps="false"
android:textColor="#color/yellow"
android:textSize="17sp"
android:visibility="gone" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="Position your document inside the frame. Make sure that all the data is clearly visible."
android:textAlignment="center"
android:textColor="#color/gray"
android:textSize="16sp"/>
<android.widget.Button
android:id="#+id/imgCapture_front"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="60dp"
android:background="#drawable/button_style_ylo"
android:text="Scan Now"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="19sp"
android:textStyle="bold"
android:visibility="visible"/>
<android.widget.Button
android:id="#+id/front_next"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="-50dp"
android:background="#drawable/button_style_ylo"
android:text="Next Step"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="19sp"
android:textStyle="bold"
android:onClick="next"
android:visibility="invisible"/>
</LinearLayout>
Here is Back side-scan activity
public class back_scan extends AppCompatActivity {
ActivityResultLauncher<Intent> activityResultLauncher1;
private static final int PERMISSION_CODE = 101;
public String currentPhotoPath1;
Button backImgCap;
Button backImgCapAgain;
Button backNext;
ImageView backImg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_back_scan);
backImg = findViewById(R.id.Image_id_back);
backImgCap = findViewById(R.id.imgCapture_back);
backImgCap.setVisibility(VISIBLE);
backImgCapAgain = findViewById(R.id.Back_imgCapture_again);
backImgCapAgain.setVisibility(GONE);
backNext = findViewById(R.id.back_next);
backNext.setVisibility(INVISIBLE);
activityResultLauncher1 = registerForActivityResult(new ActivityResultContracts.StartActivityForResult()
, new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
File f1 = new File(currentPhotoPath1);
backImgCapAgain.setVisibility(VISIBLE);
backImgCap.setVisibility(INVISIBLE);
backNext.setVisibility(VISIBLE);
backImg.setImageURI(Uri.fromFile(f1));
}
}
});
backImgCap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//if system os is >= marshmallow, request runtime permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CAMERA) ==
PackageManager.PERMISSION_DENIED ||
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_DENIED) {
//permission not enable, request it
String[] permission = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
//show popup to request permissions
requestPermissions(permission, PERMISSION_CODE);
} else {
//permission already given
dispatchTakePictureIntent1();
}
} else {
//system os < marshmallow
dispatchTakePictureIntent1();
}
}
});
}
public void next1(View view) {
Intent myIntent = new Intent(back_scan.this, scanned_copy.class);
back_scan.this.startActivity(myIntent);
finish();
}
public void scanAgainBack(View view) {
clearMyFiles1();
onCreateLayouts1();
backImg.setImageDrawable(getResources().getDrawable(R.drawable.id_back));
}
void clearMyFiles1() {
File imgFile1 = new File(currentPhotoPath1);
if (imgFile1 != null) {
imgFile1.delete();
}
}
public void onCreateLayouts1() {
backImgCap.setVisibility(VISIBLE);
backImgCapAgain.setVisibility(GONE);
backNext.setVisibility(INVISIBLE);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSION_CODE:
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
dispatchTakePictureIntent1();
} else {
Toast.makeText(this, "permission denied...", Toast.LENGTH_SHORT).show();
}
return;
}
}
private File createImageFile1() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "BACK_ID_JPEG_" + timeStamp;
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath1 = image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent1() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile1();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.nyabaapplication.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
activityResultLauncher1.launch(takePictureIntent);
}
}
}
}
Back Scan XML file is almost same as front side XML
Here is the activity that shows both sides of the ID Card together
public class scanned_copy extends AppCompatActivity {
Button finishBtn;
ImageView scanIDBack;
ImageView scanIDFront;
String storeFrontScan;
String storeBackScan="BACK_ID_JPEG.jpg";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scanned_copy);
readFrontImgFromFile();
readBackImgFromFile();
scanIDBack = findViewById(R.id.Scan_id_back);
scanIDFront = findViewById(R.id.Scan_id_front);
finishBtn = findViewById(R.id.ScanfinishBtn);
finishBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(scanned_copy.this, WellDone.class);
startActivity(intent);
finish();
}
});
}
public void readFrontImgFromFile()
{
File imgFileFront = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES)+storeFrontScan);
if(imgFileFront.exists())
{
scanIDFront.setImageURI(Uri.fromFile(imgFileFront));
}
}
public void readBackImgFromFile()
{
File imgFileBack = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES)+storeBackScan);
if(imgFileBack.exists())
{
scanIDBack.setImageURI(Uri.fromFile(imgFileBack));
}
}
}
The XML File of this 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"
android:background="#color/background"
android:scrollbars="none"
tools:context=".scanned_copy">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp"
android:gravity="center"
android:text="Scanned ID Card"
android:textAlignment="center"
android:textAllCaps="false"
android:textColor="#color/yellow"
android:textSize="28sp"
android:textStyle="bold" />
<ProgressBar
android:id="#+id/progressBar4"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="174dp"
android:layout_height="26dp"
android:layout_gravity="center"
android:layout_marginTop="16dp"
android:progress="85"
android:progressTint="#color/yellow" />
<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginHorizontal="20dp"
app:cardBackgroundColor="#color/primary_gray"
app:cardCornerRadius="22dp"
app:cardElevation="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:padding="10dp"
android:text="Have a final check if all data is clearly visible and that it matches the information you have entered in previous steps."
android:textAlignment="center"
android:textColor="#color/gray"
android:textSize="16sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_gravity="center_horizontal"
android:text="Front Side"
android:textSize="26dp"
android:textStyle="bold"
android:textColor="#color/light_gray"
android:layout_marginTop="30dp"/>
<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:layout_marginHorizontal="10dp"
app:cardBackgroundColor="#color/primary_gray"
app:cardCornerRadius="22dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center">
<ImageView
android:id="#+id/Scan_id_front"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:scaleType="fitXY"
android:src="#drawable/id_front" />
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_gravity="center_horizontal"
android:text="Back Side"
android:textSize="26dp"
android:textStyle="bold"
android:textColor="#color/light_gray"
android:layout_marginTop="30dp"/>
<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_marginHorizontal="10dp"
app:cardBackgroundColor="#color/primary_gray"
app:cardCornerRadius="22dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center">
<ImageView
android:id="#+id/Scan_id_back"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:scaleType="fitXY"
android:src="#drawable/id_back" />
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
<android.widget.Button
android:id="#+id/ScanfinishBtn"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginBottom="40dp"
android:background="#drawable/button_style_ylo"
android:text="Finish Verification"
android:textAllCaps="false"
android:textColor="#color/white"
android:layout_gravity="center_horizontal"
android:textSize="19sp"
android:textStyle="bold"/>
</LinearLayout>
</ScrollView>

You have the path to the files that were saved. Pass them through to the last activity as intent extras.
https://developer.android.com/training/basics/firstapp/starting-activity

Related

Attempt to invoke virtual method 'void android.widget.Button.setVisibility(int)' on a null object

I have 3 buttons on my layout 1 visible and 2 invisible at the time when the app is open,
when I click the 1st visible button it's open the camera to click the picture after the picture was clicked the picture was displayed at an ImageView on that same layout. After the picture was displayed at that ImageView I want to make the 2 invisible buttons visible and the 1 visible button invisible but when I try to do this I gating this error.
here is my XML file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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/background"
android:orientation="vertical"
android:padding="30dp"
tools:context=".Front_Scan">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp"
android:gravity="center"
android:text="Scan Front Side"
android:textAlignment="center"
android:textAllCaps="false"
android:textColor="#color/yellow"
android:textSize="28sp"
android:textStyle="bold" />
<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="230dp"
android:layout_gravity="center"
android:layout_marginTop="30dp"
app:cardBackgroundColor="#color/background"
app:cardCornerRadius="22dp"
app:cardElevation="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:orientation="vertical">
<ImageView
android:id="#+id/Image_id_front"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:scaleType="fitXY"
android:src="#drawable/id_front" />
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
<Button
android:id="#+id/Front_imgCapture_again"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#drawable/flag_transparent"
android:text="Scan Again"
android:textAllCaps="false"
android:textColor="#color/yellow"
android:visibility="invisible"
android:textSize="17sp" />
<android.widget.Button
android:id="#+id/imgCapture_front"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="16dp"
android:background="#drawable/button_style_ylo"
android:text="Scan Now"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="19sp"
android:textStyle="bold"
android:visibility="visible"/>
<android.widget.Button
android:id="#+id/front_next"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="8dp"
android:background="#drawable/button_style_ylo"
android:text="Next Step"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="19sp"
android:textStyle="bold"
android:onClick="next"
android:visibility="invisible"/>
</LinearLayout>
enter image description here
here is my java class Code
public class Front_Scan extends AppCompatActivity {
private static final int PERMISSION_CODE = 1000;
private static final int IMAGE_CAPTURE_CODE = 1001;
Button frontImgCap;
Button frontImgCapAgain;
Button frontNext;
ImageView frontImg;
Uri image_uri;
private int REQUEST_CODE_PERMISSIONS = 101;
private String[] REQUIRED_PERMISSIONS = new String[]{"android.permission.CAMERA",
"android.permission.WRITE_EXTERNAL_STORAGE"};
AutoFitTextureView textureView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_front_scan);
frontImg = findViewById(R.id.Image_id_front);
frontImgCap = findViewById(R.id.imgCapture_front);
frontImgCapAgain = findViewById(R.id.imgCapture_again);
frontNext = findViewById(R.id.front_next);
frontImgCap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//if system os is >= marshmallow, request runtime permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CAMERA) ==
PackageManager.PERMISSION_DENIED ||
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_DENIED) {
//permission not enable, request it
String[] permission = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
//show popup to request permissions
requestPermissions(permission, PERMISSION_CODE);
} else {
//permission already given
openCamera();
}
} else {
//system os < marshmallow
openCamera();
}
}
});
}
private void openCamera() {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From the camera");
image_uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
//Camera intent
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent,IMAGE_CAPTURE_CODE);
}
public void next(View view) {
Intent myIntent = new Intent(Front_Scan.this, back_scan.class);
Front_Scan.this.startActivity(myIntent);
finish();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSION_CODE:
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED){
openCamera();
}else {
Toast.makeText(this, "permission denied...", Toast.LENGTH_SHORT).show();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #NonNull Intent data) {
//called when image was captured from camera
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
frontImg.setImageURI(image_uri);
//geting error at this line//
frontImgCapAgain.setVisibility(VISIBLE);
frontImgCap.setVisibility(INVISIBLE);
frontNext.setVisibility(VISIBLE);
}
}
}
I think You should change something in Your AndroidManifest.xml file. Try adding the singleTop attribute to the Front_Scan <activity>. I've encountered a similar problem once and the attribute helped because, as the docs say:
If, when starting the activity, there is already an instance of the same activity class in the foreground that is interacting with the user, then re-use that instance.
So the code fragment in Your case should look like this:
<activity
android:name=".Front_Scan"
android:launchMode="singleTop"
...>
...
</activity>

java.lang.IllegalArgumentException: uri cannot be null

I am getting and error while uploading an image and storing data to Firebase. I am using Bitmap to display the images. After submitting the data the app crashes and returns to the previous Activity. Also, when I pick an image from the device it is not displaying in the ImageView.
My error:
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bloodsavelife, PID: 6642
java.lang.IllegalArgumentException: uri cannot be null
at com.google.android.gms.common.internal.Preconditions.checkArgument(com.google.android.gms:play-services-basement##17.2.1:35)
at com.google.firebase.storage.StorageReference.putFile(StorageReference.java:238)
at com.example.bloodsavelife.Activities.MakeRequest.uploadToFirebase(MakeRequest.java:153)
at com.example.bloodsavelife.Activities.MakeRequest.access$000(MakeRequest.java:47)
at com.example.bloodsavelife.Activities.MakeRequest$2.onClick(MakeRequest.java:121)
at android.view.View.performClick(View.java:7125)
at android.view.View.performClickInternal(View.java:7102)
at android.view.View.access$3500(View.java:801)
at android.view.View$PerformClick.run(View.java:27336)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) I/Process: Sending signal. PID: 6642 SIG: 9
XML file:
<?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=".Activities.MakeRequest">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="18dp"
android:text="Write your message and add an image for the community, somebody will
defintely help you if possible"
android:textColor="#android:color/black"
android:textSize="24sp"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/post_image"
android:layout_width="192dp"
android:layout_height="150dp"
android:padding="8dp"
android:src="#drawable/ic_launcher_background_image" />
<Button
android:id="#+id/browse"
android:layout_width="141dp"
android:layout_height="57dp"
android:layout_marginLeft="50dp"
android:layout_marginTop="60dp"
android:background="#drawable/button_bg"
android:gravity="center"
android:text="Browse"
android:textAlignment="gravity"
android:textColor="#color/colorPrimary"
android:textSize="24sp"
android:textStyle="bold" />
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:background="#drawable/border_background">
<EditText
android:id="#+id/message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#null"
android:cursorVisible="true"
android:gravity="top"
android:hint="Message to donors and mention for what purpose blood needed Include your
contact and location here."
android:maxLines="15"
android:minLines="7"
android:padding="10dp"
android:textAlignment="gravity"
android:textColor="#android:color/black"
android:textColorHint="#color/DarkGreen"
android:textSize="15sp"
android:textStyle="bold" />
</FrameLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/bloodgroup"
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.ExposedDropdownMenu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:hint="Required Blood Group"
android:inputType="text"
android:textColor="#android:color/black"
android:textSize="20sp"
app:boxBackgroundMode="outline"
app:endIconMode="dropdown_menu">
<AutoCompleteTextView
android:id="#+id/dropdown_text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/quantity"
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:hint="Quantity Needed(in ml)"
android:inputType="text"
android:textColor="#android:color/black"
android:textSize="20sp"
app:boxBackgroundMode="outline"
app:endIconMode="clear_text">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text" />
</com.google.android.material.textfield.TextInputLayout>
</LinearLayout>
<Button
android:id="#+id/btn_post"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="30dp"
android:background="#drawable/button_bg"
android:text="Post Request"
android:textAllCaps="false"
android:textColor="#android:color/white"
android:textSize="18sp"
android:textStyle="bold" />
</LinearLayout>
</ScrollView>
Java code:
public class MakeRequest extends AppCompatActivity {
EditText message;
TextInputLayout bloodgroup, quantity;
TextView title;
ImageView image;
Uri filepath;
Bitmap bitmap;
Button postReq, browse;
private AutoCompleteTextView dropDownText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_make_request);
message = findViewById(R.id.message);
bloodgroup = findViewById(R.id.bloodgroup);
quantity = findViewById(R.id.quantity);
browse = findViewById(R.id.browse);
title = findViewById(R.id.title);
image = findViewById(R.id.image);
postReq = findViewById(R.id.btn_post);
dropDownText = findViewById(R.id.dropdown_text);
String[] item = new String[]{
"A+Ve",
"A-Ve",
"B+Ve",
"B-Ve",
"AB+Ve",
"AB-Ve",
"O+Ve",
"O-Ve"
};
ArrayAdapter<String> adapter = new ArrayAdapter<>(
MakeRequest.this,
R.layout.dropdown_item,
item
);
dropDownText.setAdapter(adapter);
browse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Dexter.withActivity(MakeRequest.this)
.withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "select image"), 1);
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission,
PermissionToken token) {
token.continuePermissionRequest();
}
}).check();
}
});
postReq.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadToFirebase();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == 1 && requestCode == RESULT_OK) {
filepath = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(filepath);
bitmap = BitmapFactory.decodeStream(inputStream);
image.setImageBitmap(bitmap);
} catch (Exception ex) {
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void uploadToFirebase() {
ProgressDialog dialog = new ProgressDialog(this);
dialog.setTitle("File Uploader");
dialog.show();
enter code here
message = findViewById(R.id.message);
bloodgroup = findViewById(R.id.bloodgroup);
quantity = findViewById(R.id.quantity);
FirebaseStorage storage = FirebaseStorage.getInstance();
//need improvement by using date and time instead of random method.
StorageReference uploader = storage.getReference("Image1" + new Random().nextInt(100));
uploader.putFile(filepath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
uploader.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
dialog.dismiss();
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference root = db.getReference("RequestPost");
RequestHelper obj = new RequestHelper(message.getText().toString(),
bloodgroup.getEditText().getText().toString(), quantity.getEditText().getText().toString(),
uri.toString());
root.child(bloodgroup.getEditText().getText().toString()).setValue(obj);
message.setText("");
bloodgroup.getEditText().setText("");
quantity.getEditText().setText("");
image.setImageResource(R.drawable.ic_image_black_24dp);
Toast.makeText(getApplicationContext(), "Uploaded",
Toast.LENGTH_LONG).show();
}
});
}
})
.addOnProgressListener(snapshot -> {
float percent = (100 * snapshot.getBytesTransferred()) /
snapshot.getTotalByteCount();
dialog.setMessage("Uploaded:" + (int) percent + "%");
});
}
Try with this code
Pick an image from gallery
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT)
startActivityForResult(intent, 1001);
onActivityforresult get Uri
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1001 && requestCode == RESULT_OK) {
filepath = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(filepath);
bitmap = BitmapFactory.decodeStream(inputStream);
image.setImageBitmap(bitmap);
} catch (Exception ex) {
// You can catch the exception here
}
}
}

How to solve this error: Android resource linking failed?

These two codes below are in the same MainActivity, in my Android Studio project
1) Recoding the audio from smartphone and playing it when pressing Play button:
public class Main2Activity extends AppCompatActivity {
//Declare variables
Button btnRecord, btnStopRecord, btnPlay, btnStop;
//String pathSave ="";
private static String pathSave;
MediaRecorder mediaRecorder;
MediaPlayer mediaPlayer;
final int REQUEST_PERMISSION_CODE=1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
//Request Runtime permission
if(!checkPermissionFromDevice()){
requestPermission();
}
//Init View
btnPlay = (Button) findViewById(R.id.btnPlay);
btnRecord = (Button) findViewById(R.id.btnStartRecord);
btnStop = (Button) findViewById(R.id.btnStop);
btnStopRecord = (Button) findViewById(R.id.btnStopRecord);
btnRecord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View view){
if (checkPermissionFromDevice())
{
pathSave = Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+ UUID.randomUUID().toString()+"audio_record.3gp";
setupMediaRecorder();
try{
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IOException e){
e.printStackTrace();
}
btnPlay.setEnabled(false);
btnStop.setEnabled(false);
Toast.makeText(Main2Activity.this, "Recording...", Toast.LENGTH_SHORT).show();
}
else{
requestPermission();
}
}
});
btnStopRecord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mediaRecorder.stop();
btnStopRecord.setEnabled(false);
btnPlay.setEnabled(true);
btnRecord.setEnabled(true);
btnStop.setEnabled(false);
}
});
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btnStop.setEnabled(true);
btnStopRecord.setEnabled(false);
btnRecord.setEnabled(false);
mediaPlayer = new MediaPlayer();
try{
mediaPlayer.setDataSource(pathSave);
mediaPlayer.prepare();
} catch (IOException e){
e.printStackTrace();
}
mediaPlayer.start();
Toast.makeText(Main2Activity.this, "Playing...", Toast.LENGTH_SHORT).show();
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btnStopRecord.setEnabled(false);
btnRecord.setEnabled(true);
btnStop.setEnabled(false);
btnPlay.setEnabled(true);
if (mediaPlayer != null){
mediaPlayer.stop();
mediaPlayer.release();
setupMediaRecorder();
}
}
});
}
private void setupMediaRecorder(){
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(pathSave);
}
private void requestPermission() {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.RECORD_AUDIO
} ,REQUEST_PERMISSION_CODE);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode)
{
case REQUEST_PERMISSION_CODE:
{
if(grantResults.length>0 && grantResults[0]== PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText( this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
break;
}
}
private boolean checkPermissionFromDevice(){
int write_external_storage_result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
int record_audio_result = ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO);
return write_external_storage_result == PackageManager.PERMISSION_GRANTED &&
record_audio_result == PackageManager.PERMISSION_GRANTED;
}
2) Saving the directory where the audio file is created and converting it to a vector:
String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+UUID.randomUUID().toString()+"audio_record.3gp";
public byte[] convert(String path) throws IOException {
FileInputStream fis = new FileInputStream(path);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
for (int readNum; (readNum = fis.read(b)) != -1; ) {
bos.write(b, 0, readNum);
}
byte[] bytes = bos.toByteArray();
return bytes;
}
Problems
Build Output:
Build: build failed
AAPT errors: (1 error)
Android resource linking failed
Example of error messages: (1) AAPT: C:\Users\cmorais.gradle\caches\transforms-2\files-2.1\cb634fe4b4d1fdfcd5255e485d30a0c1\material-1.0.0\res\anim-v21\design_bottom_sheet_slide_in.xml:17: error: resource integer/bottom_sheet_slide_duration (aka com.example.appsom:integer/bottom_sheet_slide_duration) not found. (2) C:\Users\cmorais.gradle\caches\transforms-2\files-2.1\cb634fe4b4d1fdfcd5255e485d30a0c1\material-1.0.0\res\anim-v21\design_bottom_sheet_slide_out.xml:17: error: resource integer/bottom_sheet_slide_duration (aka com.example.appsom:integer/bottom_sheet_slide_duration) not found. – moraiscarolinav 2 days ago
(3) C:\Users\cmorais.gradle\caches\transforms-2\files-2.1\cb634fe4b4d1fdfcd5255e485d30a0c1\material-1.0.0\res\animator-v21\design_appbar_state_list_animator.xml:19: error: attribute state_liftable (aka com.example.appsom:state_liftable) not found. (4) C:\Users\cmorais.gradle\caches\transforms-2\files-2.1\cb634fe4b4d1fdfcd5255e485d30a0c1\material-1.0.0\res\animator-v21\design_appbar_state_list_animator.xml:19: error: attribute state_lifted (aka com.example.appsom:state_lifted) not found. ... The project has (20) error messages with "not found" at the end.
3) My MainActivity XML file (Text):
<?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"
android:background="#color/maxwellBackground"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="#+id/btnStartRecord"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="60dp"
android:background="#FC9B03"
android:text="#string/button_start"
android:textColor="#android:color/background_light"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView2" />
<Button
android:id="#+id/btnStopRecord"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="55dp"
android:background="#FC9B03"
android:text="#string/button_stop"
android:textColor="#android:color/background_light"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#+id/textView3"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/btnStartRecord"
app:layout_constraintVertical_bias="0.161" />
<Button
android:id="#+id/btnPlay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/ColorYellow"
android:text="#string/button_play"
android:textColor="#android:color/background_light"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#+id/btnStop"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.507"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView3"
app:layout_constraintVertical_bias="0.504" />
<Button
android:id="#+id/btnStop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="128dp"
android:background="#color/ColorYellow"
android:text="#string/button_stop_play"
android:textColor="#android:color/background_light"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.507"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/record_area"
android:textColor="#android:color/background_light"
android:textSize="24sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.088" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/play_area"
android:textColor="#android:color/background_light"
android:textSize="24sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.573" />
</androidx.constraintlayout.widget.ConstraintLayout>
Buttons associated (XML Design)
[https://i.stack.imgur.com/uiO6F.png][1]
the is not file or resource named com.example.appsom:integer/bottom_sheet_slide_duration).
Create integers.xml file in your project's \res\values folder. In the file create your integer:
<resources>
<integer name="bottom_sheet_slide_duration">value</integer></resources>

Android Studio No view found for id Error

I am developing a project at Android Studios and I have encountered an error Like This no view ........................................................................................................................................................
E/AndroidRuntime: FATAL EXCEPTION: main Process: com.mixerchat.dating, PID: 7525
java.lang.IllegalArgumentException: No view found for id 0x7f080014 (com.mixerchat.dating:id/Login_A) for fragment Enable_location_F{3a7c810 #1 id=0x7f080014}
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1454)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:802)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
at androidx.fragment.app.FragmentManagerImpl$1.run(FragmentManager.java:733)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
Error Returned Java Code
private void enable_location() {
Enable_location_F enable_location_f = new Enable_location_F();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left,R.anim.in_from_left,R.anim.out_to_right);
getSupportFragmentManager().popBackStackImmediate();
transaction.replace(R.id.Login_A, enable_location_f).addToBackStack(null).commit();
}
The Activity_Login.xml codes
<?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:id="#+id/Login_A"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#color/white"
tools:context="com.mixerchat.dating.Accounts.Login_A">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:fillViewport="true">
<androidx.percentlayout.widget.PercentRelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="vertical"
android:layout_marginTop="15dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_heightPercent="62%"
android:id="#+id/upperlayout"
android:layout_weight="1">
<androidx.viewpager.widget.ViewPager
android:id="#+id/pager"
android:background="#color/white"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:overScrollMode="always"
android:layout_above="#+id/indicator"/>
<com.google.android.material.tabs.TabLayout
android:id="#+id/indicator"
android:layout_width="match_parent"
android:layout_height="30dp"
app:tabBackground="#drawable/d_indicator_background"
app:tabGravity="center"
app:tabIndicatorHeight="0dp"
android:layout_alignParentBottom="true"
/>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_below="#+id/upperlayout"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="10dp"
android:background="#drawable/ic_fb_btn_background">
<ImageView
android:layout_width="28dp"
android:layout_height="28dp"
app:srcCompat="#drawable/ic_facebook"
android:layout_marginLeft="10dp"
android:layout_centerVertical="true"/>
<Button
android:layout_width="match_parent"
android:layout_height="50dp"
android:textColor="#color/white"
android:textAllCaps="true"
android:textSize="14dp"
android:text="Facebook ile Giriş Yap"
style="?android:attr/borderlessButtonStyle"
android:onClick="Login"
/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="10dp"
android:id="#+id/gmail_login_layout"
android:background="#drawable/ic_google_background">
<ImageView
android:layout_width="28dp"
android:layout_height="28dp"
app:srcCompat="#drawable/ic_gmail"
android:layout_marginLeft="10dp"
android:layout_centerVertical="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="#color/black"
android:clickable="false"
android:textAllCaps="true"
android:textSize="14dp"
style="?android:attr/borderlessButtonStyle"
android:background="#color/transparent"
android:text="Google ile Giriş Yap"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_marginTop="10dp"
android:id="#+id/phone_login_layout">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="#color/black"
android:clickable="false"
android:textSize="13dp"
android:background="#color/transparent"
style="?android:attr/borderlessButtonStyle"
android:text="Telefon Numaram ile Giriş Yap"/>
</RelativeLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="center"
android:textColor="#color/dimgray"
android:text="Bize güvenebilirsiniz \n Bilgileriniz 3. Part Kişilerle Paylaşılmamaktadır."
android:layout_marginTop="10dp"
android:lineSpacingExtra="7dp"/>
</LinearLayout>
</androidx.percentlayout.widget.PercentRelativeLayout>
</ScrollView>
</RelativeLayout>
Enable_Location_F Code
public class Enable_location_F extends Fragment {
View view;
Context context;
Button enable_location_btn;
SharedPreferences sharedPreferences;
IOSDialog iosDialog;
String gpsText;
public Enable_location_F() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
if(Functions.isTurkish())
view= inflater.inflate(R.layout.fragment_enable_location, container, false);
else
view= inflater.inflate(R.layout.fragment_enable_location_eng, container, false);
context=getContext();
iosDialog = new IOSDialog.Builder(context)
.setCancelable(false)
.setSpinnerClockwise(false)
.setMessageContentGravity(Gravity.END)
.build();
sharedPreferences= context.getSharedPreferences(Variables.pref_name, MODE_PRIVATE);
enable_location_btn=view.findViewById(R.id.enable_location_btn);
enable_location_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getLocationPermission();
}
});
if(Functions.isTurkish())
gpsText = getString(R.string.gpstext_tr);
else
gpsText = getString(R.string.gpstext_eng);
return view;
}
#Override
public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
if (enter) {
Animation anim= MoveAnimation.create(MoveAnimation.LEFT, enter, 300);
anim.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {}
#Override
public void onAnimationEnd(Animation animation) {
// after all the animation done we will call this mothod for get the location of user
GPSStatus();
}
#Override
public void onAnimationRepeat(Animation animation) {}
});
return anim;
} else {
return MoveAnimation.create(MoveAnimation.RIGHT, enter, 300);
}
}
private void getLocationPermission() {
requestPermissions(new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
123);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch(requestCode){
case 123:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
GetCurrentlocation();
} else {
TastyToast.makeText(context,gpsText,TastyToast.LENGTH_LONG,TastyToast.DEFAULT);
}
break;
}
}
private FusedLocationProviderClient mFusedLocationClient;
public void GPSStatus(){
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean GpsStatus = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(!GpsStatus) {
TastyToast.makeText(context,gpsText,TastyToast.LENGTH_LONG,TastyToast.DEFAULT);
startActivityForResult(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS),2);
}
else {
GetCurrentlocation();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==2){
GPSStatus();
}
}
// main method used for get the location of user
private void GetCurrentlocation() {
iosDialog.show();
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(context);
// first check the location permission if not give then we will ask for permission
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
iosDialog.cancel();
getLocationPermission();
return;
}
// if the user gives the permission then this method will call and get the current location of user
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
iosDialog.cancel();
if (location != null) {
// save the location inlocal and move to main activity
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString(Variables.current_Lat,""+location.getLatitude());
editor.putString(Variables.current_Lon,""+location.getLongitude());
editor.commit();
GoToNext_Activty();
}else {
if(sharedPreferences.getString(Variables.current_Lat,"").equals("") || sharedPreferences.getString(Variables.current_Lon,"").equals("") ){
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString(Variables.current_Lat,"33.738045");
editor.putString(Variables.current_Lon,"73.084488");
editor.commit();
}
GoToNext_Activty();
}
}
});
}
public void GoToNext_Activty(){
startActivity(new Intent(getActivity(), MainMenuActivity.class));
getActivity().overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
getActivity().finishAffinity();
}
}
I Can Wait For Your Help...

How to Save google profile after google signin in another activity

I am new to Android Programming. I successfully integrated the Google sign-in and successful in Passing data to another Activity. But When I am going back to the activity through the navigation drawer where I passed the data it sowing empty screen. I Want to Save user Profile in that Activity. I want to save user details by clicking the save button permanently in the app to show as a user profile. Please help me in solving this Problem. Thanks, in Advance for the Solution.
Here are my java files and XML files.
activity_main3.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:id="#+id/activity_main3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".Main3Activity">
<LinearLayout
android:id="#+id/prof_section"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="50dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/prof_pic"
android:layout_width="90dp"
android:layout_height="125dp"
android:src="#drawable/profilep" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="28dp"
android:layout_marginTop="20dp"
android:orientation="vertical">
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Disply Name Here"
android:textSize="18dp"
android:textStyle="bold" />
<TextView
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:text="Disply Email Here"
android:textSize="18dp"
android:textStyle="bold" />
<Button
android:id="#+id/butn_logout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Logout"
/>
</LinearLayout>
</LinearLayout>
<com.google.android.gms.common.SignInButton
android:id="#+id/butn_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:layout_marginTop="60dp" >
</com.google.android.gms.common.SignInButton>
activity_detail.xml
<?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: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=".Detail">
<ImageView
android:id="#+id/dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp" />
<TextView
android:id="#+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp" />
<Button
android:id="#+id/button_save"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SAVE" />
Detail.Java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
dp = (ImageView) findViewById(R.id.dp);
name = (TextView) findViewById(R.id.name);
email = (TextView) findViewById(R.id.email);
Intent i = getIntent();
final String i_name, i_email, i_url;
i_name = i.getStringExtra("p_name");
i_email = i.getStringExtra("p_email");
i_url = i.getStringExtra("p_url");
name.setText(i_name);
email.setText(i_email);
new Thread(new Runnable() {
#Override
public void run() {
try {
URL url = new URL(i_url);
InputStream is = url.openConnection().getInputStream();
final Bitmap bmp = BitmapFactory.decodeStream(is);
runOnUiThread(new Runnable() {
#Override
public void run() {
dp.setImageBitmap(bmp);
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
Main3Activity.Java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
preferenceConfig = new SharedPreferenceConfig(getApplicationContext());
if (preferenceConfig.readLoginStatus()) {
startActivity(new Intent(this, Main2Activity.class));
finish();
}
Prof_Section = (LinearLayout) findViewById(R.id.prof_section);
SignOut = (Button) findViewById(R.id.butn_logout);
SignIn = (SignInButton) findViewById(R.id.butn_login);
Name = (TextView) findViewById(R.id.name);
Email = (TextView) findViewById(R.id.email);
Prof_Pic = (ImageView) findViewById(R.id.prof_pic);
SignIn.setOnClickListener(this);
SignOut.setOnClickListener(this);
Prof_Section.setVisibility(View.GONE);
GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().requestProfile().build();
googleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this, this).addApi(Auth.GOOGLE_SIGN_IN_API, signInOptions).build();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.butn_login:
signIn();
break;
case R.id.butn_logout:
signOut();
break;
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
private void signIn() {
Intent intent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
startActivityForResult(intent, REQ_CODE);
}
private void signOut() {
Auth.GoogleSignInApi.signOut(googleApiClient).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
updateUI(false);
}
});
}
private void updateUI(boolean isLogin) {
if (isLogin) {
Prof_Section.setVisibility(View.VISIBLE);
SignIn.setVisibility(View.GONE);
} else {
Prof_Section.setVisibility(View.GONE);
SignIn.setVisibility(View.VISIBLE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQ_CODE) {
GoogleSignInResult googleSignInResult = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
GoogleSignInAccount account = googleSignInResult.getSignInAccount();
String name = account.getDisplayName();
String email = account.getEmail();
String img_url = account.getPhotoUrl().toString();
Name.setText(name);
Email.setText(email);
Glide.with(this).load(img_url).into(Prof_Pic);
updateUI(true);
preferenceConfig.writeLoginStatus(true);
try {
Intent sendData = new Intent(Main3Activity.this, Detail.class);
name = account.getDisplayName();
email = account.getEmail();
img_url = account.getPhotoUrl().toString();
sendData.putExtra("p_name", name);
sendData.putExtra("p_email", email);
sendData.putExtra("p_url", img_url);
startActivity(sendData);
} catch (Exception e) {
Toast.makeText(Main3Activity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(Main3Activity.this, "Login Failed", Toast.LENGTH_SHORT).show();
}
}
Use shared preferences for your purpose. You can read more about it here.
An example is provided here sharedPreferences

Categories