Android studio Barcode read - java

I'm building an app in android studio to read barcodes and store them into SQL Database. But I want the device to read only certain barcodes and return a false Toast message if the wrong barcode is read. The device I'm using is Symbol TC70. Basically the barcodes that I want the app to read are the SSCC barcodes and if they start with "K02" that would be the wrong barcode, the one that needs to be read starts with "K00" and has 18 digits. I've tried multiple code lines with no success. This is the main code that i started with.
private String getSerialnumber() {
String serialNumber;
serialNumber = "";
if (Build.VERSION.SDK_INT >= 26) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
serialNumber = android.os.Build.getSerial();
} else {
serialNumber = "Unknown barcode!";
}
} else {
serialNumber = android.os.Build.SERIAL;
}
return serialNumber;
}

did you try check the return serial number as string like these?
private String getSerialnumber() {
String serialNumber;
serialNumber = "";
if (Build.VERSION.SDK_INT >= 26) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
serialNumber = android.os.Build.getSerial();
if(!serialNumber.substring(0,4).quals('SSCC'))
serialNumber = "wrong barcode";
} else {
serialNumber = "Unknown barcode!";
}
} else {
serialNumber = android.os.Build.SERIAL;
}
return serialNumber;
}

Related

How to check whether the OTP sent is expired or not and verify OTP for forgot/ reset password in Spring Boot?

I am developing an API for reset/ forgot password. I have created an API for send otp to registered user only. In this, I am storing generated OTP in database too.
Below is my SenOTP model:
public class SendOTP {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
Long sendotpid;
private int otp;
private String phone;
private static final long OTP_VALID_DURATION = 5 * 60 * 1000; // 5 minutes
#Column(name="otp_Requested_Time")
private Date otpRequestedTime;
public boolean isOTPRequired() {
if(this.getOtp() == 0) {
return false;
}
long currentTimeInMillis = System.currentTimeMillis();
long otpRequestedTimeMillis = this.otpRequestedTime.getTime();
if(otpRequestedTimeMillis + OTP_VALID_DURATION < currentTimeInMillis) {
// otp expires
return false;
}
return true;
}
}
Below is send otp to regsitered phone number API:
public int getOTP() {
Random r = new Random();
int min = 1000;
int max = 9999;
int uid = r.nextInt(max-min) + min;
return uid;
}
public ResponseEntity<?> sendotptoregisteredphone(HttpServletRequest request, #RequestParam("phone") String phone) {
CustomResponse = ResponseFactory.getResponse(request);
phone = phone.replace(" 1", "").replace("NA", "").replace(" 1NA", "").replace(",", "").replace("-", "").replace("(", "").replace(")", "").replace(" ", "");
User registeredUser = userDao.findByPhoneAndPhoneverify(phone,1);
if(registeredUser != null) {
if(phone.equals(registeredUser.getPhone())) {
int otp = getOTP();
SendOTP s = new SendOTP();
s.setOtp(otp);
s.setPhone(phone);
s.setOtpRequestedTime(new Date());
SendOTP sotp = sendOtpDao.save(s);
// Here is my Twilio implementation to send message to entered phone number
CustomResponse.setResponse(sotp);
CustomResponse.setStatus(CustomStatus.OK);
CustomResponse.setStatusCode(CustomStatus.OK_CODE);
CustomResponse.setResponseMessage(CustomStatus.SuccessMsg);
}
}else {
CustomResponse.setResponse("Sorry ! Phone number is not registered with us.");
CustomResponse.setStatus(CustomStatus.Error);
CustomResponse.setStatusCode(CustomStatus.Error_CODE);
}
return new ResponseEntity<ResponseDao>(CustomResponse, HttpStatus.OK);
}
Below API is to verify entered OTP:
public ResponseEntity<?> verifyotp(HttpServletRequest request, #RequestParam("otp") String otp) {
CustomResponse = ResponseFactory.getResponse(request);
int flag = checkapikey(apikey);
SendOTP otpByUser;
try {
if(otp != null || otp != "" || otp.equalsIgnoreCase("NA")) {
int otpValue = Integer.parseInt(otp);
otpByUser = sendOtpDao.findByOtp(otpValue);
// What next, I am bit confuse here.
}
} catch (Exception e) {
e.printStackTrace();
CustomResponse.setResponse("Error occurred! please try again");
CustomResponse.setStatus(CustomStatus.Error);
CustomResponse.setStatusCode(CustomStatus.Error_CODE);
}
return new ResponseEntity<ResponseDao>(CustomResponse, HttpStatus.OK);
}
Now, next I want to verify or validate OTP that user will enter and check whether the OTP is expired or not. If OTP is not expired then forgot/reset password API should work.
Please suggest me any solution or answer.

How to open new Activity for Vcard and how to open Google Maps app?

I am making a qr code scanner app and I can't complete two things. The first one is to pass information about Vcard to a new Activity. Here is the code I wrote:
#Override
public void handleResult(Result rawResult) {
processRawResult(rawResult.getText());
}
private void processRawResult(String text){
if (text.startsWith("BEGIN:")) {
String[] tokens = text.split("\n");
QRVcardModel qrVcardModel = new QRVcardModel();
for (int i = 0; i < tokens.length; i++) {
if (tokens[i].startsWith("BEGIN:")) {
qrVcardModel.setType(tokens[i].substring("BEGIN:".length()));
} else if (tokens[i].startsWith("N:")) {
qrVcardModel.setName(tokens[i].substring("N:".length()));
} else if (tokens[i].startsWith("ORG:")) {
qrVcardModel.setOrg(tokens[i].substring("ORG:".length()));
} else if (tokens[i].startsWith("TEL:")) {
qrVcardModel.setTel(tokens[i].substring("TEL:".length()));
} else if (tokens[i].startsWith("URl:")) {
qrVcardModel.setUrl(tokens[i].substring("URL:".length()));
} else if (tokens[i].startsWith("EMAIL:")) {
qrVcardModel.setEmail(tokens[i].substring("EMAIL:".length()));
} else if (tokens[i].startsWith("ADR:")) {
qrVcardModel.setAddress(tokens[i].substring("ADR:".length()));
} else if (tokens[i].startsWith("NOTE:")) {
qrVcardModel.setNote(tokens[i].substring("NOTE:".length()));
} else if (tokens[i].startsWith("SUMMARY:")) {
qrVcardModel.setSummary(tokens[i].substring("SUMMARY:".length()));
} else if (tokens[i].startsWith("DTSTART:")) {
qrVcardModel.setDtstart(tokens[i].substring("DTSTART:".length()));
} else if (tokens[i].startsWith("DTEND:")) {
qrVcardModel.setDtend(tokens[i].substring("DTEND:".length()));
}
}
Intent intentVcard = new Intent(MainActivity.this, VcardActivity.class);
startActivity(intentVcard);
}
The second problem I face is that I can't open Google Maps app when I scan the Geoqrcode. Here is the code:
else if (text.startsWith("geo:"))
{
QRGeoModel qrGeoModel = new QRGeoModel();
String delims = "[ , ?q= ]+";
String tokens[] = text.split(delims);
for (int i=0;i<tokens.length;i++)
{
if (tokens[i].startsWith(" geo:"))
{
qrGeoModel.setLat(tokens[i].substring("geo:".length()));
}
}
qrGeoModel.setLat(tokens[0].substring("geo:".length()));
qrGeoModel.setLng(tokens[1]);
qrGeoModel.setGeo_place(tokens[2]);
Uri gmmIntentUri = Uri.parse("qrGeoModel.getLat(),qrGeoModel.getLng()");
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
startActivity(mapIntent);
}
Do you know how can I do that two?
You can pass values in Intent like this :
intentVcard.putExtra("value_name" , value);
value can be String, int, boolean, long and more (you can check in your ide what you can pass).
On the recieving activity you can get the value like this :
getIntent.getStrinExtra("value_name");
Be sure to replace it by your value name, for String it is like this, however for boolean it will be :
getIntent.getBooleanExtra("value_name" , defualt_value);
About the Google Maps problem, look at this line
Uri gmmIntentUri = Uri.parse("qrGeoModel.getLat(),qrGeoModel.getLng()");
you don't need " there, that way you will pass it all as a string and not the actual value of qrGeoModel.getLat(), insted write this line like that :
Uri gmmIntentUri = Uri.parse(qrGeoModel.getLat() + "," + qrGeoModel.getLng());

RecyclerView is empty on "some" devices, but works perfectly on my own device

I have an app that uses json data to populate a recyclerview. It works perfectly on my own device. However, it doesn't work on some devices which even have the same android version with mine.
I found the source of the problem by printing the size of the ArrayList at some stages of the data handling and I am sure nothing is due to network.
The exact problem is that the ArrayList.size() returns 0 on some devices but it doesn't happen on my own device which shows "231" for the size.
The list is defined in the class and initialized in the void.
List<Match> liste;
private void refreshList() {
String ret = new TinyDB(getApplicationContext()).getString("list");
try {
JSONArray bulten = new JSONArray(ret.substring(ret.indexOf("[")));
if(ret==""){Toast.makeText(getApplicationContext(),"Something is wrong.",Toast.LENGTH_LONG).show();}
liste = new ArrayList<>();
for (int i = 0; i < bulten.length(); i++) {
String isim,kod,ust,alt,bet;
bet = bulten.optJSONObject(i).getString("BetTypeId");
isim = bulten.optJSONObject(i).getString("BetName");
kod = bulten.optJSONObject(i).getString("Code");
if(bulten.optJSONObject(i).optJSONArray("Odds25").optJSONObject(0) != null){
ust = bulten.optJSONObject(i).optJSONArray("Odds25").optJSONObject(0).getString("Value");
alt = bulten.optJSONObject(i).optJSONArray("Odds25").optJSONObject(1).getString("Value");}
else{
ust = "0.00";
alt= "0.00";
}
if(bet == "3"){
liste.add(new Match(isim,kod,ust,alt));}
}
Toast.makeText(getApplicationContext(),""+liste.size(),Toast.LENGTH_SHORT)
.show(); // The part I show the size of the arraylist is here.
Collections.sort(liste, new Match.CompId());
RecyclerView.Adapter adapter1 = new RVAdapter(liste);
rv.setAdapter(adapter1);
} catch (JSONException e) {
e.printStackTrace();
}catch (StringIndexOutOfBoundsException e){}
}
Here is the Match class:
public class Match {
String isim;
String kod;
String ust;
String alt;
Match(String isim, String kod, String ust, String alt) {
this.isim = isim;
this.kod = kod;
this.ust = ust;
this.alt = alt;
}
public static class CompId implements Comparator<Match> {
#Override
public int compare(Match arg0, Match arg1) {
return Integer.parseInt(arg0.kod) - Integer.parseInt(arg1.kod);
}
}
}
I don't know why this happened but in the line
if(bet == "3"){
liste.add(new Match(isim,kod,ust,alt));}
}
I was checking if the variable bet is equal to three. It seems that in some devices the string "3" is not read as "3". I changed this line to bet.contains("3")
and it is working right now on those devices.

I am getting string errors

After changing my string from this:
String osver = System.getProperty("os.name");
if (osver.contains("Mac")){
String app = wd + "/relap5.x\"";
} else if (osver.contains("Windows")){
String app = "relap5.exe";
} else if (osver.contains("linux")) {
String app = "/relap5.x";
}
To this:
String[] osver = {System.getProperty("os.name")};
if (osver.contains("Mac")){
String[] app = {wd + "/relap5.x\""};
} else if (osver.contains("Windows")){
String[] app = {"relap5.exe"};
} else if (osver.contains("linux")) {
String[] app = {"/relap5.x"};
}
I am getting errors.
Cannot find symbol
symbol: method contains(String)
Location variable osver of type string[]
You cannot do contains over an array.
You could alternatively do this:
List<String> osver = Arrays.asList(System.getProperty("os.name"));
if (osver.contains("Mac")) {
String[] app = { wd + "/relap5.x\"" };
} else if (osver.contains("Windows")) {
String[] app = { "relap5.exe" };
} else if (osver.contains("linux")) {
String[] app = { "/relap5.x" };
}
This is because Array does not contain method contains. Do you mean the following:
String osver = System.getProperty("os.name");
String app;
if (osver.equals("Mac")){
app = "wd" + "/relap5.x\"";
} else if (osver.equals("Windows")){
app = "relap5.exe";
} else if (osver.equals("linux")) {
app = "/relap5.x";
}
System.out.println(app);
The above code will check for equality but if you want to check for containment then use:
String osver = System.getProperty("os.name");
String app;
if (osver.contains("Mac")){
app = "wd" + "/relap5.x\"";
} else if (osver.contains("Windows")){
app = "relap5.exe";
} else if (osver.contains("linux")) {
app = "/relap5.x";
}
System.out.println(app);

Get Primary gmail id among all gmails in my mobile

we have one requirement, to display primary Gmail account in edittext. But i am getting all email(Gmail) accounts which are logged in my mobile.
I am using below code.
Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
Account[] accounts = AccountManager.get(MainActivity.this).getAccountsByType("com.google");
if(accounts.length>1){
for (Account account : accounts) {
if (emailPattern.matcher(account.name).matches()) {
String possibleEmail = account.name;
Log.d("email::","email::"+possibleEmail+"----"+account.type);
}
}
}else{
Log.d("email::","email::no mails found");
}
Please help me to find out the primary email id.
Thanks
Try This:-
private String getEmailID() {
AccountManager manager = (AccountManager) getSystemService(ACCOUNT_SERVICE);
Account[] list = manager.getAccounts();
for (Account account : list) {
if (account.type.equalsIgnoreCase("com.google")) {
gmail = account.name;
break;
}
}
mStr_email = gmail;
Log.d(KEY_TAG, "EMAIL" + mStr_email);
return mStr_email;
}
Code to Check whether Internet Connection is On:-
InternetConnection ic = new InternetConnection(getApplicationContext());
isInternetPresent = ic.isConnectingToInternet();
if (!isInternetPresent) {
Utilities.showToast(SplashActivity.this,
"Switch on Internet Connection");
startActivity(new Intent(Settings.ACTION_SETTINGS));
} else {
Log.d(KEY_TAG, "Check attendane ");
}

Categories

Resources