How to make ProgressBar progress in alertDialog?(Xamarin.Android) - xamarin.android

I have the following code in alertDialog.SetPositiveButton
alertConfirmTransfer.SetPositiveButton("ДА", delegate
{
ProgressBar progressBar = FindViewById<ProgressBar>(Resource.Id.progressBar);
alertConfirmTransfer.Cancel();
MobileSellReference.Service1 service = new
MobileSellReference.Service1();
progressBar.IncrementProgressBy(10);
service.Url = settings.Synchronization.Msellurl;
progressBar.IncrementProgressBy(10);
byte[][] resultFromService = service.ToPPC(basedataZipName, objectId);
progressBar.IncrementProgressBy(10);
byte[] basedataZipFile = resultFromService[0];
byte[] dutybasedataZipFile = resultFromService[3];
byte[] tranbasedataZipFile = resultFromService[2];
byte[] vendbasedataZipFile = resultFromService[1];
progressBar.IncrementProgressBy(10);
string basedataZipFullPath = GlobalVariables.fromserverFolderPath + "/" + basedataZipName;
string dutybasedataZipFullPath = GlobalVariables.fromserverFolderPath + "/" + dutybasedataZipName;
string tranbasedataZipFullPath = GlobalVariables.fromserverFolderPath + "/" + tranbasedataZipName;
string vendbasedataZipFullPath = GlobalVariables.fromserverFolderPath + "/" + vendbasedataZipName;
Helper.DeleteAllFromFolders(GlobalVariables.fromserverFolderPath, GlobalVariables.vendingFolderPath, GlobalVariables.tranFolderPath, GlobalVariables.debtFolderPath);
progressBar.IncrementProgressBy(10);
Helper.EmptyMobileSellDB();
progressBar.IncrementProgressBy(10);
System.IO.File.WriteAllBytes(basedataZipFullPath, basedataZipFile);
progressBar.IncrementProgressBy(10);
System.IO.File.WriteAllBytes(dutybasedataZipFullPath, dutybasedataZipFile);
progressBar.IncrementProgressBy(10);
System.IO.File.WriteAllBytes(tranbasedataZipFullPath, tranbasedataZipFile);
progressBar.IncrementProgressBy(10);
System.IO.File.WriteAllBytes(vendbasedataZipFullPath, vendbasedataZipFile);
progressBar.IncrementProgressBy(10);
}
I want the progress bar to increment in the places I specified . But when I run the app I have only progress bar circulating infinetly. I want to increase by and by. And After reaching 100 to dissapear. I've found too little information how to do that in Xamarin.Android and none of it helped me.

After the line where you findviewbyreference :
ProgressBar progressBar = FindViewById<ProgressBar>(Resource.Id.progressBar);
Set the max progress to 100 and then set the current progress to 0.
progressBar.Max = 100;
progressBar.Progress = 0;
Then incrementing the progress should work.
progressBar.IncrementProgressBy(10);
// Try adding delay after/before you set the progress.
// You can put the below code in a method and call that method after updating the progress bar.
try
{
Thread.Sleep(2000);
}
catch (Exception exception)
{
Android.Util.Log.Error("Error",exception.Message);
}

cs file
MobileSellReference.Service1 service = new MobileSellReference.Service1();
service.Url = settings.Synchronization.Msellurl;
progressBar.IncrementProgressBy(10);
Thread.Sleep(2000);
byte[][] resultFromService = service.ToPPC(basedataZipName, objectId);
progressBar.IncrementProgressBy(50);
Thread.Sleep(2000);
byte[] basedataZipFile = resultFromService[0];
byte[] dutybasedataZipFile = resultFromService[3];
byte[] tranbasedataZipFile = resultFromService[2];
byte[] vendbasedataZipFile = resultFromService[1];
string basedataZipFullPath = GlobalVariables.fromserverFolderPath + "/" + basedataZipName;
string dutybasedataZipFullPath = GlobalVariables.fromserverFolderPath + "/" + dutybasedataZipName;
string tranbasedataZipFullPath = GlobalVariables.fromserverFolderPath + "/" + tranbasedataZipName;
string vendbasedataZipFullPath = GlobalVariables.fromserverFolderPath + "/" + vendbasedataZipName;
Helper.DeleteAllFromFolders(GlobalVariables.fromserverFolderPath, GlobalVariables.vendingFolderPath, GlobalVariables.tranFolderPath, GlobalVariables.debtFolderPath);
progressBar.IncrementProgressBy(5);
Thread.Sleep(2000);
Helper.EmptyMobileSellDB();
progressBar.IncrementProgressBy(5);
Thread.Sleep(2000);
System.IO.File.WriteAllBytes(basedataZipFullPath, basedataZipFile);
progressBar.IncrementProgressBy(10);
Thread.Sleep(2000);
System.IO.File.WriteAllBytes(dutybasedataZipFullPath, dutybasedataZipFile);
progressBar.IncrementProgressBy(10);
Thread.Sleep(2000);
System.IO.File.WriteAllBytes(tranbasedataZipFullPath, tranbasedataZipFile);
progressBar.IncrementProgressBy(10);
Thread.Sleep(2000);
System.IO.File.WriteAllBytes(vendbasedataZipFullPath, vendbasedataZipFile);
The code above is in alert.SetPositiveButton("Yes" ....) method
the axml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:minWidth="25px"
android:minHeight="25px">
<LinearLayout
android:orientation="vertical"
android:gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/linearLayout1">
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/progressBar" />
<Button
android:text="Взема данни"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/btnGetData" />
<Button
android:text="Предава данни"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/btnTransferData" />
<Button
android:text="Пълна синхронизация"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/btnFullSynchronization" />
</LinearLayout>

Related

How to wait for LottieAnimationView to finish then do something

I have the following code in Xamarin.Android, I want to show my main actcivty after the LottieAnimationView finshed.
<com.airbnb.lottie.LottieAnimationView
android:id="#+id/SplashAnimationView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
app:lottie_autoPlay="true"
app:lottie_fileName="LoadingLottie.json"
app:lottie_loop="false"
app:lottie_speed="1.00"/>
There is an AnimationEnd event in it. So you can try the following code:
LottieAnimationView lottieAnimationView = this.FindViewById<LottieAnimationView>(Resource.Id.SplashAnimationView);
lottieAnimationView.Animation.AnimationEnd += (s, e) =>
{
Intent intent = new Intent(this, typeof(MainActivity));
intent.SetFlags(ActivityFlags.NewTask);
StartActivity(intent);
};

textview visibility xamarin android

I have created an imageview and above it I created a textview. my aim is that I want to show my imageview if there's an image and if not I want to remove the imageview and display the textview that says "no image", this is my xml code:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<TextView
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Item Image: "
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView9"
android:textColor="#android:color/holo_blue_dark"/>
<ImageView
android:src="#android:drawable/ic_menu_gallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="25px"
android:minHeight="25px"
android:id="#+id/imageView1"
android:layout_toRightOf="#id/textView9"/>
<TextView
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="No Image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView10"
android:layout_toRightOf="#id/textView9"
/>
</RelativeLayout>
and this is my code:
ImageView imgv = view.FindViewById<ImageView>(Resource.Id.imageView1);
textview10 = view.FindViewById<TextView>(Resource.Id.textView10);
textview10.Visibility = ViewStates.Invisible;
private void Ws_getimg_clrCompleted(object sender, WSitems.getimg_clrCompletedEventArgs e)
{
Byte[] data = e.Result.datab;
if (data != null)
{
MemoryStream mem = new MemoryStream(data);
Android.Graphics.Bitmap originBitmap = BitmapFactory.DecodeStream(mem);
imgv.SetImageBitmap(originBitmap);
}
else
{
imgv.Visibility = ViewStates.Gone;
textview10.Visibility = ViewStates.Visible;
}
}
I get my image from a webservice. the problem is that only the imageview is disappearing when there's no image but the textview isn't becoming visible. why? what should I do? thanks in advance.
You can use FFImageLoading to replace your webservice to load Image on the intnet.
ImageView imageView1 = FindViewById<ImageView>(Resource.Id.imageView1);
TextView textView10 = FindViewById<TextView>(Resource.Id.textView10);
textView10.Visibility = ViewStates.Invisible;
// string urlToImage = "http://www.123raw.com/includes/templates/custom/images/123raw_mainpic_01.jpg";
string urlToImage = "http://www.123raw.com/includes/templates/custom/images/12311raw_mainpic_01.jpg";
var config = new FFImageLoading.Config.Configuration()
{
ExecuteCallbacksOnUIThread = true
};
ImageService.Instance.Initialize(config);
ImageService.Instance.LoadUrl(urlToImage).Error(exception =>
{
imageView1.Visibility = ViewStates.Gone;
textView10.Visibility = ViewStates.Visible;
}).Into(imageView1);
Here is running GIF, if the image cannot be loaded.
this is my code:
Task<Stream> GetStreamFromImageByte(CancellationToken ct)
{
//Since we need to return a Task<Stream> we will use a TaskCompletionSource>
TaskCompletionSource<Stream> tcs = new TaskCompletionSource<Stream>();
if (data != null)
{
tcs.TrySetResult(new MemoryStream(data));
}
return tcs.Task;
}
private void Ws_getimg_clrCompleted(object sender, WSitems.getimg_clrCompletedEventArgs e)
{
data = e.Result.datab;
var config = new FFImageLoading.Config.Configuration()
{
ExecuteCallbacksOnUIThread = true
};
ImageService.Instance.Initialize(config);
ImageService.Instance.LoadStream(GetStreamFromImageByte).Error(exception =>
{
imgv.Visibility = ViewStates.Gone;
textview10.Visibility = ViewStates.Visible;
}).Into(imgv);

How to show ProgressBar and make it progress?(Xamarin.Android)

I call a web service which gets 4 files, and while these files are loading I want to show progress to the user (circular or horizontal it doesn't matter). I've followed the examples on internet but nothing appears on screen.
MobileSellReference.Service1 service = new MobileSellReference.Service1();
service.Url = settings.Synchronization.Msellurl;
ProgressBar progressBar = FindViewById<ProgressBar>(Resource.Id.progressBar);
progressBar.Max = 100;
progressBar.Progress = 0;
byte[][] basedataResult = service.ToPPC(basedataZipName, objectId);
progressBar.IncrementProgressBy(25);
byte[][] dutybasedataResult = service.ToPPC(dutybasedataZipName, objectId);
progressBar.IncrementProgressBy(25);
byte[][] tranbasedataResult = service.ToPPC(tranbasedataZipName, objectId);
progressBar.IncrementProgressBy(25);
byte[][] vendbasedataResult = service.ToPPC(vendbasedataZipName, objectId);
progressBar.IncrementProgressBy(25);
I've found a lot of examples using external progressbar libraries but they all want to change the theme of the Activity. Instead I want some simple ProgressBar built into Xamarin.Android. For example when the first file is downloaded I want 1/4 of the circle to be filled, when 2 files are downloaded 1/2 of the circle to be filled et cetera. Similarly for a horizontal ProgressBar.
Use AsyncTask
.axml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="0" />
<ProgressBar
android:id="#+id/pb"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="?android:attr/progressBarStyleHorizontal" />
</LinearLayout>
MainActivity:
public class MainActivity : Activity
{
ProgressBar pb;
TextView tv;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
pb = FindViewById<ProgressBar>(Resource.Id.pb);
tv = FindViewById<TextView>(Resource.Id.tv);
UpdatePB uptask = new UpdatePB(this,pb,tv);
uptask.Execute(100);
}
public class UpdatePB : AsyncTask<int, int, string>
{
Activity mcontext;
ProgressBar mpb;
TextView mtv;
public UpdatePB(Activity context,ProgressBar pb,TextView tv) {
this.mcontext = context;
this.mpb = pb;
this.mtv = tv;
}
protected override string RunInBackground(params int[] #params)
{
// TODO Auto-generated method stub
for (int i = 1; i <= 4; i++)
{
try
{
Thread.Sleep(3000);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
Android.Util.Log.Error("lv",e.Message);
}
mpb.IncrementProgressBy(25);
PublishProgress(i * 25);
}
return "finish";
}
protected override void OnProgressUpdate(params int[] values)
{
mtv.Text = String.ValueOf(values[0]);
Android.Util.Log.Error("lv==", values[0] + "");
}
protected override void OnPostExecute(string result)
{
mcontext.Title = result;
}
}
}
This might be a helpful link:
https://developer.android.com/reference/android/widget/ProgressBar.html
Code:
<ProgressBar
android:id="#+id/determinateBar"
style="#android:style/Widget.ProgressBar.Horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:progress="25"/>
... and then you just change the progress; 25, 50, 75, 100?
After running into the same problem, I found another solution that got it working. I was reluctant to define a new class (like AsyncTask) to fix this, so looked into async await and threading. I found that after defining an Android.Widget.ProgressBar in an .axml layout file like so:
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:progress="0"
style="?android:attr/progressBarStyleHorizontal" />
I could get it to update if I put the updating tasks in a System.Threading.Tasks.Task.Run and passing in an action that does the updates with RunOnUiThread call like:
btnDoStuff.Click += (sender, e) =>
{
Task.Run(() =>
{
RunOnUiThread(() =>
{
progressBar.Max = 100;
progressBar.Progress = 0;
progressBar.Visibility = ViewStates.Visible;
});
DoSomeWork1(arguments);
RunOnUiThread(() => progressBar.Progress += 25);
DoSomeWork2(arguments);
RunOnUiThread(() => progressBar.Progress += 25);
DoSomeWork3(arguments);
RunOnUiThread(() => progressBar.Progress += 25);
DoSomeWork4(arguments);
RunOnUiThread(() => progressBar.Progress += 25);
});
}
But even then I've had some inconsistent behavior - there may be an element of timing to it as well...

How to remove added attributes from xml-file when adding new node

My xml file look like this:
<?xml version="1.0" encoding="utf-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap>
<loc>abcdefg </loc>
<lastmod>2017-12-10</lastmod>
</sitemap>
</sitemapindex>
After running my program for adding new node it look like this:
<?xml version="1.0" encoding="utf-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap>
<loc>laksdjfs </loc>
<lastmod> 453w43e5</lastmod>
</sitemap>
<sitemap xmlns="">
<loc>abcdefghoh_20170501181500715.xml</loc>
<lastmod>2017-05-01</lastmod>
</sitemap>
</sitemapindex>
The xmlns="" is added to the node - and I don't want to have it there. How can I remove it?
My Asp.Net Core 2.0 program look like this:
public void AddIndexFileToSiteMap(string IndexFileName)
{
string filenavn = GetSiteMapDir();
DateTime time = DateTime.Now;
string lastmoddate = time.Year.ToString("0000") + "-" + time.Month.ToString("00") + "-" + time.Day.ToString("00");
try
{
FileStream fileStream = new FileStream(filenavn, FileMode.Open);
XmlDocument doc = new XmlDocument();
doc.Load(fileStream);
// Create the child nodes. This code demonstrates various ways to add them.
XmlNode newElem = doc.CreateNode(XmlNodeType.Element,"sitemap", "");
newElem.InnerXml = "<loc></loc><lastmod></lastmod>";
newElem["loc"].InnerText = IndexFileName;
newElem["lastmod"].InnerText = lastmoddate;
newElem.Attributes.RemoveAll();
// 2. Add the new element to the end of the item list.
doc.DocumentElement.AppendChild(newElem);
fileStream.Position = 0;
doc.Save(fileStream);
fileStream.Flush();
}
catch
{
}
//doc.Save(fileStream);
}

How to convert (by using ANT) .properties file into constants as a code file?

I want to use ANT build to translate .properties file into text file (code).
Input file my.properties:
FOO=foo bar
BAR=bar bar foo
Desired output file Constants.as:
package foo.bar {
public final class Constants {
public static const FOO:String = "FOO";
public static const BAR:String = "BAR";
}
}
Note: ActionScript can't use properties files like Java, so I need to use this translation as a pre-build task. My properties file is localization and I want the keys as constants.
You could do this by including a filterchain in a concat task.
<concat destfile="Constants.as">
<header filtering="false">
package foo.bar {
public final class Constants {
</header>
<footer filtering="false">
}
}
</footer>
<fileset file="my.properties"/>
<filterchain>
<tokenfilter>
<ignoreblank/>
<trim/>
<replaceregex pattern="(.*)=(.*)" replace=" public static const \1:String = "\2";"/>
</tokenfilter>
</filterchain>
</concat>
I've managed to hack it through scriptdef in JavaScript.
Any ideas how to do it better?
<scriptdef name="localization-regen" language="javascript">
<attribute name="input.file.path"/>
<attribute name="output.file.category"/>
<attribute name="output.file.package"/>
<attribute name="output.file.dir"/>
<attribute name="output.property"/>
<![CDATA[
importPackage(java.io);
inputFilePath = attributes.get("input.file.path");
outputFileCategory = attributes.get("output.file.category");
outputFilePackage = attributes.get("output.file.package");
outputFileDir = attributes.get("output.file.dir");
outputFileClass = "LocalizationKeys" + outputFileCategory.substring(0, 1).toUpperCase() + outputFileCategory.substring(1, outputFileCategory.length());
inputFile = new File(inputFilePath);
inputStream = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile)));
outputLines = "";
for(line = inputStream.readLine(); line != null; line = inputStream.readLine())
{
vars = line.split("=");
c = vars[0];
if(c.substring(0, 1) == "#") continue;
outputLines += "\t\tpublic static const " + c + ":String = \"" + c + "\";\n";
}
output = "";
output = "package " + outputFilePackage + "\n"
+ "{\n"
+ "\tpublic final class " + outputFileClass + "\n"
+ "\t{\n"
+ outputLines
+ "\t}\n"
+ "}";
outputFilePath = outputFileDir + "/" + outputFileClass+ ".as";
out = new BufferedWriter(new FileWriter(outputFilePath));
out.write(output, 0, output.length);
out.flush();
out.close();
]]>
</scriptdef>

Resources