I'm using ZXing in an Android app being developed in Xamarin to scan a QR code and start playing the corresponding audio file automatically.
My problem is that when I get a result from scanning, it takes some time for the audio player activity to load so it gets called twice or more due to subsequent successful scannings.
Is there a way to stop continuous scanning as soon as I get a correct result?
Here's the code:
//Start scanning
scanner.ScanContinuously(opt, HandleScanResult);
}
private void HandleScanResult(ZXing.Result result)
{
string msg = "";
if (result != null && !string.IsNullOrEmpty(result.Text))
{
msg = result.Text;
var playerActivity = new Intent(myContext, typeof(AudioActivity));
//-------------------------------------------------------------
// Prerequisite: load all tracks onto "Assets/tracks" folder
// You can put here qr code - track assignments here below
// msg: decoded qr code
// playerActivity.Putextra second parameter is a relative path
// under "Assets" directory
//--------------------------------------------------------------
//Iterate through tracks stored in assets and load their titles into an array
System.String[] trackArray = Application.Context.Assets.List("tracks");
bool trackFound = false;
foreach (string track in trackArray)
{
if (track.Equals(msg + ".mp3"))
{
playerActivity.PutExtra("Track", "tracks/" + msg + ".mp3");
for (int i = 0; i < PostList.postList.Count; i++)
{
if (PostList.postList.ElementAt(i).code.Equals(msg))
playerActivity.PutExtra("TrackTitle", PostList.postList.ElementAt(i).title);
}
myContext.StartActivity(playerActivity);
trackFound = true;
}
}
Thank you!
Old question but i'll post it anyway for anyone still looking for this information.
You need your scanner to be a class variable. This is my code:
public MobileBarcodeScanner scanner = new MobileBarcodeScanner();
private void ArrivalsClick(object sender, EventArgs e)
{
try
{
if (Arrivals.IsEnabled)
{
MobileBarcodeScanningOptions optionsCustom = new MobileBarcodeScanningOptions();
scanner.TopText = "Scan Barcode";
optionsCustom.DelayBetweenContinuousScans = 3000;
scanner.ScanContinuously(optionsCustom, ArrivalResult);
}
}
catch (Exception)
{
throw;
}
}
private async void ArrivalResult(ZXing.Result result)
{
if (result != null && result.Text != "")
{
// Making a call to a REST API
if (resp.StatusCode == System.Net.HttpStatusCode.OK)
{
int? res = JsonConvert.DeserializeObject<int>(resp.Content);
if (res == 0)
{
scanner.Cancel(); // <----- Stops scanner (Something went wrong)
Device.BeginInvokeOnMainThread(async () =>
{
await DisplayAlert("..", "..", "ΟΚ");
});
}
else
{
Plugin.SimpleAudioPlayer.ISimpleAudioPlayer player = Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.Current;
player.Load("beep.wav");
player.Play(); // Scan successful
}
}
else
{
scanner.Cancel();
Device.BeginInvokeOnMainThread(async () =>
{
await DisplayAlert("..", "..", "ΟΚ");
});
}
}
}
I am using C++ Builder XE8. As the TOpenDialog doesn't work on Android, I am trying to make such thing myself. My logic is very simple. It'll start to check file and folders from "/storage" and show all items on TListView. If I touch a folder (name) it'll open that folder and if I touch a file, it should show the name on a label. So I assigned a function to TListView's OnItemClick event.
Here is code. fpath is String, Label1 is showing current folder and Label2 is showing selected file.
void __fastcall TForm1::lviewitemclck(TObject * const Sender, TListViewItem * const AItem)
{
if (AItem->Text == "<< BACK") {
if (!fpath.LastDelimiter("/") == 0) {
fpath = fpath.SubString(0, fpath.LastDelimiter("/"));
Label1->Text = fpath;
Form1->showfiles(fpath);
}
}
else if ( DirectoryExists(fpath+ AItem->Text)) {
fpath = fpath+ AItem->Text;
Label1->Text = fpath;
Form1->showfiles(fpath);
}
else if (FileExists(fpath+ AItem->Text)) {
Label2->Text ="File: "+ fpath+ AItem->Text;
}
}
Below is the code of function to scan for files & folders and show them. stringlist is TStringList.
void __fastcall TForm1::showfiles (String path)
{
TSearchRec sr; // for scaning files and folders
TSearchRec fr; // to check whether the folder is accessible or not.
if (FindFirst(path+"/*", faAnyFile, sr) == 0)
{
stringlist->Clear();
stringlist->Add("<< BACK"); // being used to replace the ".."
do{
if(sr.Name != "." && sr.Name != ".."){
if (DirectoryExists(path+"/"+sr.Name)) {
if (FindFirst(path+"/"+sr.Name+"/*", faAnyFile, fr) == 0) { // to check if the folder is accessible
stringlist->Add("/"+ sr.Name);
}
FindClose(fr);
}
else{
stringlist->Add("/"+ sr.Name);
}
}
} while (FindNext(sr) == 0);
}
FindClose(sr);
stringlist->Sort();
Form1->Item->Free();
Form1->ListView1->BeginUpdate();
Form1->ListView1->ClearItems();
for( int i =0;i< stringlist->Count; i++){
Form1->Item = Form1->ListView1->Items->Add();
Form1->Item->Text = stringlist->Strings[i];
}
Form1->ListView1->EndUpdate();
}
Here the problem is, if I use ListView1->ClearItems() in TForm1::showfiles it shows me an error saying "Access violation at address (random no), accessing address 00000009". And if I dont use ClearItems() it just add more lines with already existed lines. I am a beginer, so I dont know where I am doing wrong.
You should use:
ListView1->Items->Clear
The best way I have found so far is to dynamically create TListView and delete it each time you want to add new items( or calling showfiles function). I have written a small function (named it refresh) to release already created TListView and call another function(named it create_lview ) which can create an instance again then it calls the showfiles method.
void __fastcall TForm1::refresh()
{
if (!lview1->Released()) {
try{
lview1->Release();
Form1->create_lview();
Form1->showfiles(fpath);
}
catch(...){
Label2->Text = "error in cleaning";
}
}
}
Here is the code to create the TListView whenever you want.
void __fastcall TForm1::create_lview()
{
lview1 = new TListView(Form1);
lview1->Parent = Form1;
lview1->Height = 600;
lview1->Width = 400;
lview1->Position->X = 0;
lview1->Position->Y = 0;
lview1->Visible = true;
lview1->Enabled = true;
lview1->OnItemClick = lviewitemclck;
lview1->CanSwipeDelete = false;
}
Please comment if you find any mistake or you can do it more efficiently.
I have tried another way to avoid the error by replacing the Clear method with updating the Item Text, then deletes the unused last row of the ListView within the ListView1Change event.
void __fastcall TForm1::ListView1Change(TObject *Sender)
{
//Delete last item
while (ListView1->Items->Count>stringlist->Count){
ListView1->Items->Delete(ListView1->Items->Count-1);
}
}
void __fastcall TForm1::showfiles (String path)
{
TSearchRec sr; // for scaning files and folders
TSearchRec fr; // to check whether the folder is accessible or not.
//path+PathDelim+
if (FindFirst(path+PathDelim+'*', faAnyFile, sr) == 0)
{
stringlist->Clear();
stringlist->Add("<<--BACK"); // being used to replace the ".."
do{
if(sr.Name != "." && sr.Name != ".."){
if (DirectoryExists(path+PathDelim+sr.Name)) {
if (FindFirst(path+PathDelim+sr.Name+PathDelim+"*", faAnyFile, fr) == 0) { // to check if the folder is accessible
stringlist->Add(sr.Name);
}
FindClose(fr);
}
else{
stringlist->Add(sr.Name);
}
}
} while (FindNext(sr) == 0);
}
FindClose(sr);
stringlist->Sort();
for( int i =0;i< ListView1->Items->Count; i++){
ListView1->Items->Item[i]->Text="";
}
ListView1->BeginUpdate();
try {
for( int i =0;i< stringlist->Count; i++)
{
if (ListView1->Items->Count-1<i)
{
TListViewItem* Item=ListView1->Items->Add();
Item->Text=stringlist->Strings[i];
} else
{
TListViewItem* Item=ListView1->Items->Item[i];
Item->Text=stringlist->Strings[i];
}
}
}
catch (...) {
}
ListView1->EndUpdate();
/* */
}
i use different savegames in my app. "coins" , "levels" , ...
It works fine but if a conflict detected then its wrong result.
/**
* Conflict resolution for when Snapshots are opened. Must be run in an AsyncTask or in a
* background thread,
*/
Snapshots.OpenSnapshotResult processSnapshotOpenResult(Snapshots.OpenSnapshotResult result, int retryCount) {
retryCount++;
int status = result.getStatus().getStatusCode();
Log.i(TAG, "Load Result for saveGame<" + savedGame.getName() + "> status: " + status);
if (status == GamesStatusCodes.STATUS_OK) {
return result;
} else if (status == GamesStatusCodes.STATUS_SNAPSHOT_CONTENTS_UNAVAILABLE) {
return result;
} else if (status == GamesStatusCodes.STATUS_SNAPSHOT_CONFLICT) {
saveResolveConflictGameData = true;
Log.i(TAG, "Konflikt aufgetreten");
Snapshots.OpenSnapshotResult resolveResult = null;
Snapshot snapshot = result.getSnapshot();
Snapshot conflictSnapshot = result.getConflictingSnapshot();
Snapshot mResolvedSnapshot = null;
mResolvedSnapshot = snapshot;
SnapshotMetadata s1Meta = snapshot.getMetadata();
SnapshotMetadata cMeta = conflictSnapshot.getMetadata();
// resolveConflict and get new merged Parser Object
//
Parser conflictParserTemp = savedGame.resolveConflict(snapshot, conflictSnapshot);
if ( conflictParserTemp == null) {
Log.e(TAG, "savedGame.resolveConflict(snapshot,conflictSnapshot) Error");
return result;
}
//
// wurde schon ein conflict behandelt ?
//
if ( conflictParser != null ) {
// merge previous Conflict with this conflict
conflictParser.merge(conflictParserTemp);
} else {
// set first conflict Parser
conflictParser = conflictParserTemp;
}
Log.i(TAG, String.format("Games.Snapshots.resolveConflict() Step %d", retryCount));
resolveResult =
Games.Snapshots.resolveConflict(
activity.mGoogleApiClient, result.getConflictId(), mResolvedSnapshot).await();
if (retryCount < MAX_SNAPSHOT_RESOLVE_RETRIES) {
// Recursively attempt again
return processSnapshotOpenResult(resolveResult, retryCount);
} else {
// Failed, log error and show Toast to the user
String message = "Could not resolve snapshot conflicts";
Log.e(TAG, message);
Toast.makeText(activity.getBaseContext(), message, Toast.LENGTH_LONG).show();
return resolveResult;
}
}
// Fail, return null.
return null;
}
The Error is that if I load savegame "coins" I become all conflicts from other savegames.
I see it here.
SnapshotMetadata s1Meta = snapshot.getMetadata();
SnapshotMetadata cMeta = conflictSnapshot.getMetadata();
The Snapshot for korrekt coins savegame show this:
SnapshotMetadataEntity{Game=GameEntity{ApplicationId=520840013521,
DisplayName=Crush me, PrimaryCategory=Simulation,
SecondaryCategory=null, Description=hallo, DeveloperName=steffen
höhmann, IconImageUri=null, IconImageUrl=null, HiResImageUri=null,
HiResImageUrl=null, FeaturedImageUri=null, FeaturedImageUrl=null,
PlayEnabledGame=true, InstanceInstalled=true,
InstancePackageName=cherry.de.wubbleburst, AchievementTotalCount=0,
LeaderboardCount=0, RealTimeMultiplayerEnabled=false,
TurnBasedMultiplayerEnabled=false, AreSnapshotsEnabled=true,
ThemeColor=00456B, HasGamepadSupport=false},
Owner=PlayerEntity{PlayerId=113260033482974102226,
DisplayName=shoehmi, HasDebugAccess=false, IconImageUri=null,
IconImageUrl=null, HiResImageUri=null, HiResImageUrl=null,
RetrievedTimestamp=1454003980807, Title=Anfänger,
LevelInfo=com.google.android.gms.games.PlayerLevelInfo#1e1b36},
SnapshotId=drive://113260033482974102226/520840013521/coins,
CoverImageUri=null, CoverImageUrl=null, CoverImageAspectRatio=0.0,
Description=null, LastModifiedTimestamp=1454004003382, PlayedTime=-1,
UniqueName=coins, ChangePending=true, ProgressValue=-1}
drive://113260033482974102226/520840013521/coins
and the snapshotData:
timestamp;coins#1453929273252;100#1453929280956;-70#230179;70
but he shows me savegame snaphot from "level" savegame as conflicted Snapshot:
levelId;points#1;3241#2;9634
and the Conflict Snapshot Metadata say it is a "coins" savegame:
SnapshotMetadataEntity{Game=GameEntity{ApplicationId=520840013521,
DisplayName=Crush me, PrimaryCategory=Simulation,
SecondaryCategory=null, Description=hallo, DeveloperName=steffen
höhmann, IconImageUri=null, IconImageUrl=null, HiResImageUri=null,
HiResImageUrl=null, FeaturedImageUri=null, FeaturedImageUrl=null,
PlayEnabledGame=true, InstanceInstalled=true,
InstancePackageName=cherry.de.wubbleburst, AchievementTotalCount=0,
LeaderboardCount=0, RealTimeMultiplayerEnabled=false,
TurnBasedMultiplayerEnabled=false, AreSnapshotsEnabled=true,
ThemeColor=00456B, HasGamepadSupport=false},
Owner=PlayerEntity{PlayerId=113260033482974102226,
DisplayName=shoehmi, HasDebugAccess=false, IconImageUri=null,
IconImageUrl=null, HiResImageUri=null, HiResImageUrl=null,
RetrievedTimestamp=1454003980807, Title=Anfänger,
LevelInfo=com.google.android.gms.games.PlayerLevelInfo#1e1b36},
SnapshotId=drive://113260033482974102226/520840013521/coins,
CoverImageUri=null, CoverImageUrl=null, CoverImageAspectRatio=0.0,
Description=null, LastModifiedTimestamp=1454004003382, PlayedTime=-1,
UniqueName=coins, ChangePending=true, ProgressValue=-1}
drive://113260033482974102226/520840013521/coins
Why only if conflict occured and without conflicts its running correct and
save / load correct??
Please Help me???
sorry for my english ;)
How to rectify the error "The method getErrorCodeName() is undefined for the type MulticastResult" ? I used following code
MulticastResult result = sender.send(message, androidTargets, 1);
if (result.getResults() != null) {
int canonicalRegId = result.getCanonicalIds();
if (canonicalRegId != 0) {
// same device has more than on registration ID: update database
}
} else {
int error = result.getFailure();
System.out.println("Broadcast failure: " + error);
String error_code_name = result.getErrorCodeName(); //Error is Here
if (error_code_name.equals(Constants.ERROR_NOT_REGISTERED)) {
// application has been removed from device - unregister database or remove from database
}
}
Thanks in advance !
You want to do this:
result.getResults().get(0).getErrorCodeName();
or something like:
for(Result r : result.getResults()){
if (Constants.ERROR_NOT_REGISTERED.equals(r)) {
// application has been removed from device - unregister database or remove from database
}
}
API docs:
http://developer.android.com/reference/com/google/android/gcm/server/MulticastResult.html
http://developer.android.com/reference/com/google/android/gcm/server/Result.html
I am using selenium to test an android web app. My test is running fine initially but hangs at particular point. It selects the first text field on the web page and writes the values while in zoom-in mode but it hangs at this point and does not select the second text field. Where am I going wrong?
My code is as follows:
public void testRegister() throws Exception
{
driver.get("file:///android_asset/www/aboutus.html");
driver.findElement(By.xpath("html/body/div/div/ul/li[2]")).click();
List<WebElement> w1=driver.findElements(By.tagName("input"));
System.out.println(w1.size());
for(int i=0;i<w1.size();i++)
{
System.out.println("************");
System.out.println(i + w1.get(i).getAttribute("id") +"*****" + w1.get(i).getAttribute("name"));
}
for(WebElement option:w1)
{
String str=option.getAttribute("id");
if(str.equals("name"))
{
option.click();
option.sendKeys("Vaishali");
}
else if(str.equals("dateofbirth"))
{
option.click();
option.sendKeys("28-09-1991");
}
else if(str.equals("club"))
{
option.click();
option.sendKeys("Manchester United");
}
else if(str.equals("username"))
{
option.click();
option.sendKeys("vishchan");
}
else if(str.equals("password"))
{
option.click();
option.sendKeys("vishchan");
}
else if(str.equals("sendbutton"))
{
option.click();
}
}
the id can be '' and it'l return null value
in the list of elements can be hidden element with the same id
for more reasons please post stack trace.
Best Regards Taras