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>
Related
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
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
}
}
}
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
The app keeps crashing whenever edit Text is empty. When I enter an e-mail it works fine. I don't know what I'm doing wrong, I already tried changing height value, checked manually when it's empty but still, the issue remains. Can anyone please let me know if there's something wrong with the code.
Error:
--------- beginning of crash
09-07 10:39:53.791 15985-15985/com.app.androidnewsapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.app.androidnewsapp, PID: 15985
android.view.InflateException: Binary XML file line #17: Binary XML file line #17: Error inflating class TextView
at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.widget.Editor.showError(Editor.java:430)
at android.widget.Editor.setError(Editor.java:466)
at android.widget.TextView.setError(TextView.java:4960)
at android.widget.TextView.setError(TextView.java:4945)
at com.app.androidnewsapp.activities.ActivityForgotPassword.onValidationFailed(ActivityForgotPassword.java:132)
at com.app.androidnewsapp.utils.validation.Validator$1.onPostExecute(Validator.java:195)
at com.app.androidnewsapp.utils.validation.Validator$1.onPostExecute(Validator.java:183)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.access$500(AsyncTask.java:180)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:168)
at android.app.ActivityThread.main(ActivityThread.java:5885)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
Caused by: android.view.InflateException: Binary XML file line #17: Error inflating class TextView
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:782)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.widget.Editor.showError(Editor.java:430)
at android.widget.Editor.setError(Editor.java:466)
at android.widget.TextView.setError(TextView.java:4960)
at android.widget.TextView.setError(TextView.java:4945)
at com.app.androidnewsapp.activities.ActivityForgotPassword.onValidationFailed(ActivityForgotPassword.java:132)
at com.app.androidnewsapp.utils.validation.Validator$1.onPostExecute(Validator.java:195)
at com.app.androidnewsapp.utils.validation.Validator$1.onPostExecute(Validator.java:183)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.access$500(AsyncTask.java:180)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:168)
at android.app.ActivityThread.main(ActivityThread.java:5885)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
Caused by: java.lang.UnsupportedOperationException: Failed to resolve attribute at index 24: TypedValue{t=0x3/d=0x4a3 "res/color/secondary_text_material_light.xml" a=1 r=0x106011a}
at android.content.res.TypedArray.getColor(TypedArray.java:447)
at android.widget.TextView.<init>(TextView.java:753)
Code:
#Required(order = 1)
#Email(order = 2, message = "Please Check and Enter a valid Email Address")
EditText edtEmail;
String strEmail, strMessage;
private Validator validator;
Button btn_forgot;
ProgressBar progressBar;
LinearLayout layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_forgot);
if (Config.ENABLE_RTL_MODE) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.BLACK);
}
edtEmail = findViewById(R.id.etUserName);
btn_forgot = findViewById(R.id.btnForgot);
progressBar = findViewById(R.id.progressBar);
layout = findViewById(R.id.view);
btn_forgot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validator.validateAsync();
}
});
validator = new Validator(this);
validator.setValidationListener(this);
setupToolbar();
}
public void setupToolbar() {
final Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setHomeButtonEnabled(false);
getSupportActionBar().setTitle("");
}
AppBarLayout appBarLayout = findViewById(R.id.appBarLayout);
if (appBarLayout.getLayoutParams() != null) {
CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
AppBarLayout.Behavior appBarLayoutBehaviour = new AppBarLayout.Behavior();
appBarLayoutBehaviour.setDragCallback(new AppBarLayout.Behavior.DragCallback() {
#Override
public boolean canDrag(#NonNull AppBarLayout appBarLayout) {
return false;
}
});
layoutParams.setBehavior(appBarLayoutBehaviour);
}
}
#Override
public void onValidationSucceeded() {
strEmail = edtEmail.getText().toString();
if (NetworkCheck.isNetworkAvailable(ActivityForgotPassword.this)) {
new MyTaskForgot().execute(Constant.FORGET_PASSWORD_URL + strEmail);
} else {
Toast.makeText(getApplicationContext(), getResources().getString(R.string.msg_no_network), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onValidationFailed(View failedView, Rule<?> failedRule) {
String message = failedRule.getFailureMessage();
if (failedView instanceof EditText) {
failedView.requestFocus();
((EditText) failedView).setError(message);
} else {
Toast.makeText(this, "Record Not Saved", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed() {
//Log.d(TAG, "onBackPressed: Si entra +++++++++");
// moveTaskToBack(true);
startActivity(new Intent(getApplicationContext(), ActivityUserLogin.class));
finish();
}
private class MyTaskForgot extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
layout.setVisibility(View.INVISIBLE);
}
#Override
protected String doInBackground(String... params) {
return NetworkCheck.getJSONString(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (null == result || result.length() == 0) {
Toast.makeText(getApplicationContext(), getResources().getString(R.string.msg_no_network), Toast.LENGTH_SHORT).show();
} else {
try {
JSONObject mainJson = new JSONObject(result);
JSONArray jsonArray = mainJson.getJSONArray(Constant.CATEGORY_ARRAY_NAME);
JSONObject objJson = null;
for (int i = 0; i < jsonArray.length(); i++) {
objJson = jsonArray.getJSONObject(i);
strMessage = objJson.getString(Constant.MSG);
Constant.GET_SUCCESS_MSG = objJson.getInt(Constant.SUCCESS);
}
} catch (JSONException e) {
e.printStackTrace();
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
progressBar.setVisibility(View.GONE);
setResult();
}
}, Constant.DELAY_PROGRESS_DIALOG);
}
}
}
public void setResult() {
if (Constant.GET_SUCCESS_MSG == 0) {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle(R.string.whops);
dialog.setMessage(R.string.forgot_failed_message);
dialog.setPositiveButton(R.string.dialog_ok, null);
dialog.setCancelable(false);
dialog.show();
layout.setVisibility(View.VISIBLE);
edtEmail.setText("");
edtEmail.requestFocus();
} else {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle(R.string.dialog_success);
dialog.setMessage(R.string.forgot_success_message);
dialog.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(ActivityForgotPassword.this, ActivityUserLogin.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
});
dialog.setCancelable(false);
dialog.show();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
default:
return super.onOptionsItemSelected(menuItem);
}
return true;
}
XML:
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusableInTouchMode="true">
<android.support.design.widget.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsingToolbarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:background="#color/colorBlackary"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed"
app:titleEnabled="false">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="5dp"
android:padding="10dp"
android:text="#string/title_forgot_password"
android:textColor="#color/colorRed"
android:textSize="15sp" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_collapseMode="pin"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:foreground="?android:attr/selectableItemBackground"
app:behavior_overlapTop="64dp"
app:cardCornerRadius="3dp"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
card_view:cardElevation="6sp"
card_view:cardPreventCornerOverlap="false"
card_view:cardUseCompatPadding="true">
<RelativeLayout
android:id="#+id/lyt_form"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<ImageView
android:layout_width="match_parent"
android:layout_height="470dp"
android:scaleType="fitXY"
android:src="#drawable/fondopeleadorkary" />
<LinearLayout
android:id="#+id/view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="vertical"
android:padding="20dp">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/TextLabel">
<EditText
android:id="#+id/etUserName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginTop="20dp"
android:drawablePadding="15dp"
android:hint="#string/edt_email"
android:textColor="#color/colorWhite"
android:inputType="textEmailAddress" />
</android.support.design.widget.TextInputLayout>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:textColor="#color/colorWhite"
android:text="#string/forgot_message" />
<com.balysv.materialripple.MaterialRippleLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginTop="20dp"
app:mrl_rippleAlpha="0.2"
app:mrl_rippleColor="#color/colorRipple"
app:mrl_rippleHover="true"
app:mrl_rippleOverlay="true">
<Button
android:id="#+id/btnForgot"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#color/colorRed"
android:text="#string/btn_send"
android:textColor="#color/colorWhite"
android:textStyle="bold" />
</com.balysv.materialripple.MaterialRippleLayout>
</LinearLayout>
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:visibility="gone" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</android.support.design.widget.CoordinatorLayout>
Try this
#Override
public void onValidationFailed(View failedView, Rule<?> failedRule) {
String message = failedRule.getFailureMessage();
if (failedView instanceof EditText) {
failedView.requestFocus();
if(!TextUtils.isEmpty(message){
((EditText) failedView).setError(message);
}
} else {
Toast.makeText(this, "Record Not Saved", Toast.LENGTH_SHORT).show();
}
I found the problem :
android:theme="#style/TextLabel"
Had to create a theme first and than a style and use it like :
<style name="TextLabel" parent="BellicTheme">
Thanks everyone
I want to add a button in Zxing Scanner Camera View, tried many procedures and seen many answers related to add button in Zxing library and refered this " How to add buttons in Zxing Scanner Camera View " , but it's not working anyone guide me, Thanks in advance, My code is
MainActivity.Java
public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private static final int REQUEST_CAMERA = 1;
final static String serverUrl = "";
private ZXingScannerView scannerView;
String res;
ImageButton img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
Log.e("OnCreate", "OnCreated");
//ZXingScannerView zxing=(ZXingScannerView)findViewById(R.id.zxscan);
scannerView = (ZXingScannerView) findViewById(R.id.zxscan);
img=(ImageButton)findViewById(R.id.img1);
//scannerView.setResultHandler(this);
//scannerView.startCamera();
//zxing.addView(scannerView);
//setContentView(scannerView);
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.M) {
if (checkPermission()) {
Log.e("M", "Permission");
Toast.makeText(getApplicationContext(), "Permission already granted", Toast.LENGTH_LONG).show();
} else {
Log.e("R", "Permission");
requestPermission();
}
}
}
private boolean checkPermission() {
return (ContextCompat.checkSelfPermission(getApplicationContext(), CAMERA) == PackageManager.PERMISSION_GRANTED);
}
private void requestPermission() {
ActivityCompat.requestPermissions(this, new String[]{CAMERA}, REQUEST_CAMERA);
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_CAMERA:
if (grantResults.length > 0) {
Log.e("Successfull", "Success");
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (cameraAccepted) {
Log.e("accpt", "Accpt");
Toast.makeText(getApplicationContext(), "Permission Granted, Now you can access camera", Toast.LENGTH_LONG).show();
} else {
Log.e("ntaccpt", "Not Acpt");
Toast.makeText(getApplicationContext(), "Permission Denied, You cannot access and camera", Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(CAMERA)) {
showMessageOKCancel("You need to allow access to both the permissions",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{CAMERA},
REQUEST_CAMERA);
}
}
});
return;
}
}
}
}
break;
}
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new android.support.v7.app.AlertDialog.Builder(MainActivity.this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
#Override
public void onResume() {
super.onResume();
int capi = android.os.Build.VERSION.SDK_INT;
if (capi >= android.os.Build.VERSION_CODES.M) {
if (checkPermission()) {
if (scannerView == null) {
scannerView = new ZXingScannerView(this);
setContentView(scannerView);
}
scannerView.setResultHandler(this);
scannerView.startCamera();
} else {
requestPermission();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
scannerView.stopCamera();
scannerView = null;
}
#Override
public void handleResult(final Result result) {
res = result.getText();
Log.d("Scanner Result", result.getText());
Log.d("Scanner Result", result.getBarcodeFormat().toString());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Scan Result");
builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
scannerView.resumeCameraPreview(MainActivity.this);
}
});
builder.setNeutralButton("Send", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
GetText();
scannerView.resumeCameraPreview(MainActivity.this);
}
});
builder.setMessage(result.getText());
AlertDialog alert = builder.create();
alert.show();
}
public void GetText() //throws UnsupportedEncodingException
{
String data = res;
String text = "";
BufferedReader reader = null;
Log.e("Datafirst", data);
String requesturi = serverUrl + data;
// Send data
try {
URL url = new URL(requesturi);
Log.e("DataSecond", requesturi);
if (Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
Log.e("Data Third", data);
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
Toast.makeText(MainActivity.this, "Readed Successfully", Toast.LENGTH_SHORT).show();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
Toast.makeText(MainActivity.this, "Readed Successfully", Toast.LENGTH_SHORT).show();
}
text = sb.toString();
} catch (Exception ex) {
Log.e("Exceptionio", "Error", ex);
ex.printStackTrace();
} finally {
try {
reader.close();
Log.e("Closed", "Closed");
} catch (Exception ex) {
Log.e("Except2", "Error", ex);
ex.printStackTrace();
}
}
Log.e("setText", data);
}
}
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<me.dm7.barcodescanner.zxing.ZXingScannerView
android:id="#+id/zxscan"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageButton
android:id="#+id/img1"
android:layout_marginBottom="15dp"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:src="#drawable/imgbut"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Try my code, It will look like this
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:orientation="vertical"
tools:context="com.package.name.TakeSingleScanActivity">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbarAdjustScan"
android:layout_width="match_parent"
android:layout_height="56dp"
android:background="#color/colorPrimary"
android:elevation="6dp"
android:minHeight="56dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/titleToolbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="15dp"
android:ellipsize="end"
android:layout_weight="1"
android:maxLines="1"
android:textColor="#color/white"
android:textSize="18dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
android:padding="10dp"
android:id="#+id/searchAdjustBtn"
android:layout_marginLeft="15dp"
android:ellipsize="end"
android:maxLines="1"
android:text="SEARCH "
android:textColor="#color/white"
android:textSize="13dp" />
</LinearLayout>
</android.support.v7.widget.Toolbar>
<TextView
android:id="#+id/textv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimaryDark"
android:gravity="center_horizontal"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:text="Point at any barcode to scan"
android:textColor="#color/white"
android:textSize="14sp"
android:textStyle="normal" />
<RelativeLayout
android:layout_marginBottom="120dp"
android:layout_below="#+id/textv"
android:id="#+id/relative_scan_take_single"
android:layout_width="match_parent"
android:layout_height="match_parent">
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:background="#color/colorPrimaryDark"
android:layout_height="120dp"
android:orientation="horizontal">
<Button
android:id="#+id/doneBtn"
style="#style/Widget.AppCompat.Button.Colored"
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_gravity="bottom"
android:text="Done"
android:textAllCaps="true"
android:textColor="#color/white"
android:textSize="22dp" />
</LinearLayout>
</RelativeLayout>
Java code for Scanner :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_take_single_scan);
init();
}
private void init() {
//Scanner
mScannerView = new ZXingScannerView(this);
RelativeLayout rl = (RelativeLayout) findViewById(R.id.relative_scan_take_single);
rl.addView(mScannerView);
mScannerView.setResultHandler(this);
mScannerView.startCamera();
mScannerView.setSoundEffectsEnabled(true);
mScannerView.setAutoFocus(true);
}
#Override
public void onResume() {
super.onResume();
mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
mScannerView.startCamera(); // Start camera on resume
}
#Override
public void onPause() {
super.onPause();
mScannerView.stopCamera(); // Stop camera on pause
}
#Override
public void handleResult(Result rawResult) {
// Do something with the result here
Log.e(TAG, rawResult.getText()); // Prints scan results
Log.e(TAG, rawResult.getBarcodeFormat().toString());
Log.e("SCAN_RESULT", "" + rawResult.getText());
//dataSingle.put("0",rawResult.getText());
}