Barcode scanner app parses barcode string to URL

Multi tool use


Barcode scanner app parses barcode string to URL
I'm trying to build an app for learning purposes. It's a simple QR code and Barcode scanner app with a two flows:
I have achieved goal number one with the if statement
public void handleResult(Result result) {
final String myResult = result.getText();
Log.d("QRCodeScanner", result.getText());
Log.d("QRCodeScanner", result.getBarcodeFormat().toString());
if(Patterns.WEB_URL.matcher(result.getText()).matches()) {
// Open URL
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(result.getText()));
startActivity(browserIntent);
}
}
My challenge is now with goal number to which I just can't get to compile. I was thinking using an else statement and parse Uri with something like google.com + the string. The expected result is that if the scanner returns and value which is not a URL pattern open the browser go to google and search with the return value.
I hope I make myself clear. Pretty much a newbie here - trying to learn terminology and way to communicate.
3 Answers
3
please try this
public void handleResult(Result result) {
final String myResult = result.getText();
Log.d("QRCodeScanner", result.getText());
Log.d("QRCodeScanner", result.getBarcodeFormat().toString());
if(Patterns.WEB_URL.matcher(result.getText()).matches()) {
// Open URL
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(result.getText()));
startActivity(browserIntent);
}
else
{
String scannedResult = result.getText().toString();
String url = "https://www.google.com/search?q="+scannedResult;
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(browserIntent);
}
}
Use this to meet your requirement.
String query=result.getText();
if(Patterns.WEB_URL.matcher(query).matches()) {
// Open URL
Intent browserIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse(result.getText()));
startActivity(browserIntent);
}else{
//Open url with google query
String escapedQuery = URLEncoder.encode(query, "UTF-8");
Uri uri = Uri.parse("http://www.google.com/#q=" + escapedQuery);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
Just simply put this code in your else condition
else{
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, result.getText());
startActivity(intent);
}
Let me know if it works
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.