How to add button in Zxing Scanner Camera View? - java

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());
}

Related

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

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

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>

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

Android crashing on empty EText

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

Add 2 Button ListView with Custom Adapter

i'm having problems trying to add 2 buttons into my listview, i'm uploading a picture with what i have and what i want
So, i just want to add those 2 buttons there, but i've been trying to do it using custom adapters but i still can't do it, if anyone could help me i would really appreciate it.
My files so far:
activity_vendor_main.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_vendedor_main"
android:orientation="vertical"
android:layout_width="match_parent"
android:background="#color/colorPrimary"
android:layout_height="match_parent"
android:weightSum="1">
<ImageView
android:src="#drawable/logo"
android:layout_width="209dp"
android:layout_height="106dp"
android:layout_marginBottom="20dp"
android:layout_gravity="center_horizontal" />
/>
<ImageView
android:src="#drawable/orderid1"
android:layout_width="134dp"
android:layout_height="34dp"
android:layout_gravity="center_horizontal"
/>
<SearchView
android:layout_width="match_parent"
android:layout_height="30dp"
android:id="#+id/seacrhBar"
android:textColor="#color/colorVendor"
android:layout_marginTop="25dp"
android:background="#drawable/vendor_bars_background"/>
<android.support.v7.widget.AppCompatButton
android:text="AGREGAR ORDEN"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="5dp"
android:layout_marginBottom="8dp"
android:textStyle="bold"
android:textColor="#color/colorVendor"
android:background="#drawable/single_button"
android:id="#+id/add_order1"
android:onClick="EVENTO" />
<ListView
android:layout_width="wrap_content"
android:layout_height="190dp"
android:id="#+id/tablaPedidos"
android:choiceMode="singleChoice"
android:layout_above="#+id/editText2"
android:background="#drawable/vendor_bars_background"
android:layout_weight="0.13" />
<android.support.v7.widget.AppCompatButton
android:text="CERRAR SESIÓN"
android:layout_width="120sp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:layout_marginBottom="135dp"
android:textStyle="bold"
android:textColor="#color/colorVendor"
android:background="#drawable/button_login_form"
android:id="#+id/signOut2_order_form"
android:onClick="logout" />
</LinearLayout>
MainActivity.java
public class LoginActivity extends AppCompatActivity {
GlobalClass appContext;
#BindView(R.id.input_username)
EditText _usernameText;
#BindView(R.id.input_password)
EditText _passwordText;
#BindView(R.id.btn_login)
Button _loginButton;
ProgressDialog progressDialog;
//Invocación de servicio para acceso al API
UsersHandler client = ServiceGenerator.createService(UsersHandler.class);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
ButterKnife.bind(this);
appContext = (GlobalClass)getApplicationContext();
_loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public void onBackPressed() {
moveTaskToBack(false);
}
public void onLoginSuccess() {
_loginButton.setEnabled(true);
finish();
}
public void onLoginFailed(String message) {
Toast.makeText(getBaseContext(), message, Toast.LENGTH_LONG).show();
_loginButton.setEnabled(true);
}
public void login() {
if (!validate()) {
// onLoginFailed("Login failed");
return;
}
_loginButton.setEnabled(false);
progressDialog = new ProgressDialog(LoginActivity.this,R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Autenticando...");
progressDialog.show();
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
onLoginSuccess();
//progressDialog.dismiss();
}
}, 3000);
progressDialog.dismiss();
String userType = appContext.getSessionUserType();
loadUserView(userType);
}
public boolean validate() {
boolean valid = true;
String username = _usernameText.getText().toString().trim();
String password = _passwordText.getText().toString();
//if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(username).matches()) {
if (username.isEmpty()) {
_usernameText.setError("Ingrese un usuario válido.");
valid = false;
} else {
_usernameText.setError(null);
}
if (password.isEmpty() || password.length() < 4) {
_passwordText.setError("No menos de 4 caracteres alfanuméricos");
valid = false;
} else {
_passwordText.setError(null);
}
if (valid) {
valid = validateApi(1, username, password);
}
return valid;
}
public boolean validateApi(int i, String username, String password) {
appContext.setSessionToken("1");
appContext.setSessionUserType(Constants.COURIER);
if (username.equals("v"))
appContext.setSessionUserType(Constants.VENDOR);
appContext.setSessionUsername("tester");
appContext.setSessionCompany("test");
appContext.saveSessionAttributes();
return true;
}
public boolean validateApi(String username, String password) {
boolean valid = false;
//Creación de request
UserLoginRequest requestObj = new UserLoginRequest(username, password);
//Declaración de request
Call<ResponseBody> call = client.userLogin(requestObj);
JSONObject json = null;
try {
ResponseBody responseBody = call.execute().body();
json = UtilsController.getJsonResponse(responseBody);
boolean success = UtilsController.isJsonValid(json);
String error = UtilsController.extractMessage(json);
if (success) {
User response = (User) UtilsController.extractDataJson(json, User.class);
appContext.setSessionToken(response.getToken());
appContext.setSessionUserType(response.getUserType());
appContext.setSessionUsername(response.getUsername());
appContext.setSessionCompany(response.getCompanyName());
appContext.saveSessionAttributes();
valid = true;
} else {
onLoginFailed(error);
return false;
}
} catch (IOException e) {
//Error en lectura de respuesta de servidor
onLoginFailed("Error interno. Intente más tarde");
} catch (JSONException e) {
//Error en campos de respuesta
onLoginFailed("Error interno. Intente más tarde");
} catch (Exception e) {
//Error general
if (json == null) {
onLoginFailed("Error interno. Intente más tarde");
}
onLoginFailed("Login failed");
}
return valid;
}
public void loadUserView(String userType) {
if (userType != null && Constants.VENDOR.equals(userType)) {
Intent userView = new Intent(this, VendorMain.class);
startActivity(userView);
} else if (Constants.COURIER.equals(userType)) {
Intent userView = new Intent(this, CourierMain.class);
startActivity(userView);
}
}
}
row_item.xml (Picture Below)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true">
</LinearLayout>
<Button
android:text="EDITAR"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/cancel_btn" />
<Button
android:text="Cancelar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/edit_btn"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/cancel_btn"
android:layout_toStartOf="#+id/cancel_btn"
android:layout_marginRight="7dp"
android:layout_marginEnd="7dp" />
<TextView
android:id="#+id/orden_title_text"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ORDEN #"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#android:color/black"
android:layout_alignBaseline="#+id/edit_btn"
android:layout_alignBottom="#+id/edit_btn"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:id="#+id/textbox1"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_marginLeft="7dp"
android:text=" "
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#android:color/black"
android:layout_alignBaseline="#+id/orden_title_text"
android:layout_alignBottom="#+id/orden_title_text"
android:layout_toRightOf="#+id/orden_title_text"
android:layout_marginStart="7dp" />
</RelativeLayout>
row_item.xml "What i have so far"
If another files is needed in order to help me, let me know and i'll upload it.
Thanks you so much guys.
create a class like
public class TestAdapter extends BaseAdapter {
Context context;
public TestAdapter(Context context)
{
this.context=context;
}
//count of number of items in listview may be depending on the array ua passing....here i am keeping 5 it may be according to you!
int count=5;
#Override
public int getCount() {
return 5;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView= LayoutInflater.from(context).inflate(R.layout.row_item,parent,false);
TextView ordentitle=(TextView)convertView.findViewById(R.id.orden_title_text);
TextView textbox1=(TextView)convertView.findViewById(R.id.textbox1);
ordentitle.setText("Whatever yout text is");
textbox1.setText("whatever your text is");
Button editar=(Button)convertView.findViewById(R.id.edit_btn);
Button cancel=(Button)convertView.findViewById(R.id.cancel_btn);
editar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//funtionality of edit button
}
});
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//functionality of cancel button
}
});
return convertView;
}
}
and then set this adapter to your listview in activity or fragment like this:
TestAdapter testAdapter=new TestAdapter(YourActivity.this)
yourlistview.setAdapter(testAdapter);
one more pointer :
YOU GAVE EDIT BUTTON id as cancel_btn and CANCEL BUTTON id as edit_btn!
You could create a new class that extends BaseAdapter and in the getView method you do w/e you want with the buttons. In the the activity with the listView you use the setAdapter.

Categories