I'm currently working on Xamarin using Visual Studio to try and build and create an app that reads a bar code and saves the integer it gets from it in a .txt file. I have managed to make the code both read the bar code and save it however i was wondering if there is a way i could save it in a more accessible file, as right now its saving in internal storage and the only way i can reach it is through adb console.
Is there a way for me to perhaps save the integers on a .txt file on my laptop? I'm currently testing it on my physical phone and its connected to my laptop via a USB cable.
Here is my code:
using Android.App;
using Android.Widget;
using Android.OS;
using System;
using Android.Content;
using ZXing.Mobile;
using System.IO;
namespace Scanner
{
[Activity(Label = "Scanner", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
Button buttonScan = FindViewById<Button>(Resource.Id.buttonScan);
TextView scanText = FindViewById<TextView>(Resource.Id.scanText);
var documents = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var BarcodesFile = Path.Combine(documents, "Barcodes.txt");
buttonScan.Click += async (sender, e) =>
{
MobileBarcodeScanner.Initialize(Application);
var scanner = new ZXing.Mobile.MobileBarcodeScanner();
var result = await scanner.Scan();
if (result != null)
File.AppendAllText(BarcodesFile, "Scanned Barcode: " + result.Text);
scanText.Text = File.ReadAllText(BarcodesFile);
};
}
}
}
So if api is an idea. I have not used any api yet for those requirements but when I think about txt I immediately thought about pastebin.
https://pastebin.com/api enter code here
That might be usefull to check out. Goodluck!;)
Related
I'm trying to play the video stream "https://s2.moidom-stream.ru/s/public/0000000087.m3u8" using LibVlc, but I only get a black screen. Other threads work fine, but I need this particular thread.
code used:
using Android.App;
using Android.OS;
using Android.Widget;
using LibVLCSharp.Shared;
using System;
using System.Linq;
using WebCamTst.Helpers;
namespace WebCamTst
{
[Activity(Label = "PanelActivity")]
public class PanelActivity : Activity
{
LibVLCSharp.Platforms.Android.VideoView videoView;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.videopanel);
videoView = FindViewById<LibVLCSharp.Platforms.Android.VideoView>(Resource.Id.videoView1);
}
protected override void OnResume()
{
base.OnResume();
PlayVideo("https://s2.moidom-stream.ru/s/public/0000000087.m3u8");
}
private void PlayVideo(string url)
{
Core.Initialize();
using (var libVLC = new LibVLC())
using (var mPlayer = new MediaPlayer(libVLC) { EnableHardwareDecoding = true })
{
videoView.MediaPlayer = mPlayer;
var _media = new Media(libVLC, url, FromType.FromLocation);
_media.Parse(MediaParseOptions.ParseNetwork);
mPlayer.Play(_media);
}
}
}
}
but it doesn't work.
Please help!
Please start with one of the official android samples.
It doesn't work because Play() is not a synchronous method. It actually starts the libvlc thread in the background.
This means that your libvlc and your player are disposed too early and your video is stopped immediately.
Other remarks:
You can Dispose() your media immediately after having passed into the media player.
Your call to Parse is useless because it's also asynchronous and isn't required (Play calls it anyway)
In addition to cube45's answer, m3u8 are played differently than regular media...
var libVLC = new LibVLC();
var media = new Media(libVLC, "https://s2.moidom-stream.ru/s/public/0000000087.m3u8", FromType.FromLocation);
await media.Parse(MediaParseOptions.ParseNetwork);
var mp = new MediaPlayer(media.SubItems.First());
mp.Play();
recently i tried to learn android programming with Xamarin in Visual studio 2017
i wrote a simple app that makes call but when i tap Call Button its give this execption error a couple of days ago its worked fine but now i got this error
i did make permission for CALL_PHONE in manifest file
forgive me for my bad english
if anyone knows how to fix this issue let me know ill be greatfull
here is my Code .cs
using Android.App;
using Android.Widget;
using Android.OS;
using Android.Content;
namespace Dialer.app
{
[Activity(Label = "Dialer.app", MainLauncher = true)]
public class MainActivity : Activity
{
Button btnCall;
ListView txtViewNumbers;
EditText txtUnumber;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
btnCall = FindViewById<Button>(Resource.Id.button1);
txtViewNumbers = FindViewById<ListView>(Resource.Id.listView1);
txtUnumber = FindViewById<EditText>(Resource.Id.editText1);
string phone = txtUnumber.Text;
btnCall.Click += delegate
{
var callDialog = new AlertDialog.Builder(this);
callDialog.SetMessage("Dial This Number? " + phone);
callDialog.SetPositiveButton("ok", delegate
{
var callIntent = new Intent(Intent.ActionCall);
callIntent.SetData(Android.Net.Uri.Parse(phone));
StartActivity(callIntent); //i get error in this line
});
callDialog.SetNeutralButton("Cancel", delegate { });
callDialog.Show();
};
}
}
}
No Activity found to handle Intent { act=android.intent.action.CALL .....
You are missing the tel: prefix on the phone number:
var callIntent = new Intent(Intent.ActionCall);
callIntent.SetData(Android.Net.Uri.Parse("tel:" + phone));
StartActivity(callIntent);
But, in the latest API levela CALL_PHONE is a revoked permission:
Permission Denial: starting Intent { act=android.intent.action.CALL dat=tel:xxx-xxx-xxxx
Instead of being allowed to directly dial a number, you need the user to accept the number via the system dialer, this is done via ACTION_DIAL:
var callIntent = new Intent(Intent.ActionDial);
callIntent.SetData(Android.Net.Uri.Parse("tel:" + "555-555-1212"));
StartActivity(callIntent);
I'm in the process of learning SQLite and wanted to make my own very simple proof of concept app where I simply store and retrieve a value from a database. I use the NuGet package SQLite-net by Krueger.
My problem is everything seems to work except it doesn't retrieve the value, it crashes at "string a = db.GetAsync(0).Result.storedvalue.ToString();", only saying multiple errors ocurred. Is there something wrong with this line, or perhaps is there something wrong with how I store values in the first place?
Here is the complete C# code for the app:
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using SQLite;
using System.IO;
using System.Reflection;
namespace SimpleDatabaseTest
{
[Activity(Label = "SimpleDatabaseTest", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity
{
SQLiteConnection db;
int i;
int k;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
// create database
db = new SQLiteConnection(Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal),"test.sqlite"));
db.CreateTable<somevalues>();
// set up enter_value and show_value
EditText enter_value = FindViewById<EditText>(Resource.Id.enter_value);
TextView show_value = FindViewById<TextView>(Resource.Id.show_value);
// store value button
Button store_value = FindViewById<Button>(Resource.Id.store_value);
store_value.Click += delegate
{
somevalues newTable = new somevalues();
i = int.Parse(enter_value.Text);
newTable.storedvalue = i;
k = newTable.id;
db.Insert(newTable);
Toast toast = Toast.MakeText(ApplicationContext, k.ToString(), ToastLength.Long); //enter_value.Text
toast.Show();
};
// retrieve value button
Button retrieve_value = FindViewById<Button>(Resource.Id.retrieve_value);
retrieve_value.Click += delegate
{
somevalues some = db.Get<somevalues>("id");
//string a = some.storedvalue.ToString();
//Toast toast = Toast.MakeText(ApplicationContext, a, ToastLength.Long);
//toast.Show();
//show_value.Text = a;
};
}
}
}
I'm trying to create a simple test app to take photos in Android, using Xamarin. When I get this app working (or so I hope), i'll use the code in a real app that I'm working on. I'm using the following recipe from Xamarin as my basis:
http://docs.xamarin.com/recipes/android/other_ux/camera_intent/take_a_picture_and_save_using_camera_app/
The major difference is that I need to store images locally, and not on the SD card. I'm able to successfully take a picture (with the Android simulator). I can see the file in the file structure using ADB and can successfully copy and open the file on my PC. However, I'm unsuccessfull in accessing the file in the app, probably due to user rights.
Please note that I was successfull in creating my own .txt files, and reading them back using either System.IO and Java.IO.
Please review the following code. My app crashes when using "System.IO.File.ReadAllText" and gives me "Access to the path "/data/data/CameraAppDemo.CameraAppDemo/files/photo.jpg" is denied.". And whatever I try (absolute, relative paths, uri's), objBitmap is always null.
ADB says that "photo.jpg" has -rwxrwx--- rights, and though I'm not entirely sure, I think that should be more than sufficient
On the other hand, maybe the intent still has a lock on "photo.jpg"? Or something else is going on...
And one final note, I'm using System.IO.File.ReadAllText just for testing purposes. I experimented with stream readers as well, but with the same result. Also, though I believe this step is unnecessary, I enabled "WriteExternalStore" in the Manifest
namespace CameraAppDemo
{
using System;
using System.Collections.Generic;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Graphics;
using Android.OS;
using Android.Provider;
using Android.Widget;
using Java.IO;
using Environment = Android.OS.Environment;
using Uri = Android.Net.Uri;
[Activity(Label = "Camera App Demo", MainLauncher = true)]
public class MainActivity : Activity
{
private File _file;
private string _basePath;
private ImageView _imageView;
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
var objBitmap = BitmapFactory.DecodeFile(_file.AbsolutePath) ;
Console.WriteLine ("objBitmap = null : " + (objBitmap == null).ToString ());
var strOutput = System.IO.File.ReadAllText (FileManager.BasePath + "/photo.jpg");
Console.WriteLine (strOutput);
}
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
FileManager.SetupFolderStructure();
if (IsThereAnAppToTakePictures())
{
Button button = FindViewById<Button>(Resource.Id.myButton);
_imageView = FindViewById<ImageView>(Resource.Id.imageView1);
button.Click += TakeAPicture;
}
}
private bool IsThereAnAppToTakePictures()
{
Intent intent = new Intent(MediaStore.ActionImageCapture);
IList<ResolveInfo> availableActivities = PackageManager.QueryIntentActivities(intent, PackageInfoFlags.MatchDefaultOnly);
return availableActivities != null && availableActivities.Count > 0;
}
private void TakeAPicture(object sender, EventArgs eventArgs)
{
System.IO.Directory.Delete (FileManager.BasePath, true);
_basePath = FileManager.BasePath;
_file = new Java.IO.File (_basePath, "photo.jpg");
Intent intent = new Intent(MediaStore.ActionImageCapture);
intent.PutExtra(MediaStore.ExtraOutput, Uri.FromFile(_file));
StartActivityForResult(intent, 0);
}
}
}
//Part of the FileManager class:
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Android.Graphics;
namespace CameraAppDemo
{
public class FileManager
{
public static string BasePath {
get {
var libraryPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
if (Directory.Exists (libraryPath) == false) {
Directory.CreateDirectory (libraryPath);
}
return libraryPath;
}
}
}
}
==== Edit ====
It seems that I'm simply not able to read the file. As an ex-webdeveloper, I'm fairly new to programming for mobile, let alone the combo of C# and Java and I'm still learning a lot.
Anyway, I added the following lines:
Console.WriteLine("Setting file :" + _file.SetReadable (true));
Console.WriteLine("Can read :" + _file.CanRead());
Both cases return False. I can't read the file, and I am unable to give read access.
So, any ideas? Is this by design? Can I tell the Intent for taking images to give me read access, or is there another workaround?
If everything fails, I'm hoping to workaround the problem by saving to the SD card first and then copying the file to the local filesystem. But that's something I rather would not do; I can't guarantee that the end users have an SD card, and the pictures should not be deleted by accident.
Im trying to get my notefunction to post the current city you are in by using your gps coordinates when saving a note. Right now it's only showing "unknown location". Im kinda lost right now and i have worked so long with this code to try and get it to work so please could anyone tell me what i have done wrong?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Device.Location;
using System.Text;
using System.IO.IsolatedStorage;
using System.IO;
using Secret.myTerraService;
namespace Secret
{
public partial class AddNotePage : PhoneApplicationPage
{
private IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
private string location = "";
#region Hämtar din geografiska position
public AddNotePage()
{
InitializeComponent();
GeoCoordinateWatcher watcher;
watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default)
{
MovementThreshold = 20
};
watcher.PositionChanged += this.watcher_PositionChanged;
watcher.StatusChanged += this.watcher_StatusChanged;
watcher.Start();
}
private void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
{
switch (e.Status)
{
case GeoPositionStatus.Disabled:
// location is unsupported on this device
break;
case GeoPositionStatus.NoData:
// data unavailable
break;
}
}
private void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
var epl = e.Position.Location;
// Access the position information thusly:
epl.Latitude.ToString("0.000");
epl.Longitude.ToString("0.000");
epl.Altitude.ToString();
epl.HorizontalAccuracy.ToString();
epl.VerticalAccuracy.ToString();
epl.Course.ToString();
epl.Speed.ToString();
e.Position.Timestamp.LocalDateTime.ToString();
}
void client_ConvertLonLatPtToNearestPlaceCompleted(object sender, myTerraService.ConvertLonLatPtToNearestPlaceCompletedEventArgs e)
{
location = e.Result;
//throw new NotImplementedException();
}
#endregion
#region Knappfunktioner
private void AppBar_Cancel_Click(object sender, EventArgs e)
{
navigateBack();
}
private void AppBar_Save_Click(object sender, EventArgs e)
{ // spara en ny anteckning
if (location.Trim().Length == 0)
{
location = "Okänd Plats";
}
// skapa namnet på filen
StringBuilder sb = new StringBuilder();
sb.Append(DateTime.Now.Year);
sb.Append("_");
sb.Append(String.Format("{0:00}", DateTime.Now.Month));
sb.Append("_");
sb.Append(String.Format("{0:00}", DateTime.Now.Day));
sb.Append("_");
sb.Append(String.Format("{0:00}", DateTime.Now.Hour));
sb.Append("_");
sb.Append(String.Format("{0:00}", DateTime.Now.Minute));
sb.Append("_");
sb.Append(String.Format("{0:00}", DateTime.Now.Second));
sb.Append("_");
location = location.Replace(" ", "-");
location = location.Replace(", ", "_");
sb.Append(location);
sb.Append(".txt");
//spara filen i Isolated Storage
var appStorage = IsolatedStorageFile.GetUserStoreForApplication();
try
{
using (var fileStream = appStorage.OpenFile(sb.ToString(), System.IO.FileMode.Create))
{
using (StreamWriter sw = new StreamWriter(fileStream))
{
sw.WriteLine(editTextBox.Text);
}
}
}
catch
{
// åtgärda vid senare tillfälle..
}
//Klart Navigera tillbaka till NoteMainPage
navigateBack();
}
When testing this, I can see a few points where your code could break. You should debug with breakpoints to actually confirm that your app is getting GPS location data. If not, use the Windows Phone emulator and run a GPS simulation (and then confirm again).
Next, once you know that your GPS data is coming in and formatted correctly for your Terra Web Service, confirm that the data is actually being sent to the Terra Web Service and that data is being returned from the web service call. If your Terra Web Service is returning "Unknown Location" still, try again but this time plot the GPS location near a major city to increase the odds of the web service knowing what city you are close to. If you are still returning "Unknown Location" then you can be fairly certain that the issue resides with the web service provider.
In my experience with the Windows Phone location services (I've only used dev phones with WiFi access (i.e. no sim)), location data sometimes takes a few seconds or minutes to pickup. If you're testing this on a physical dev phone in a basement or an area with limited access for the GPS to find you, odds are the data isn't being generated. Also, because the Windows Phone location data isn't necessarily instant, you can't always call it on the fly and expect it to have location data ready. In my experience I have had the user opt in to location services (per the Windows Phone Marketplace submission requirements) and then have a background agent pull location data while the user is using the app. That way location data is likely to be ready by the time user would need it (like your example when the user saves the note).
Here's a working example I made for you in C# that will work for your Windows Phone app. The sample is a console app for the sake of simplicity and time. If you can't figure it out still, I'll code it up for Windows Phone. With this though you really have everything you need to make it work, just plug in the lat and long variables. Download Working Source Code (Visual Studio 2010)
C# Source code snippet
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TerraServiceExample.com.msrmaps; // add the service using statement
// http://msrmaps.com/terraservice2.asmx
namespace TerraServiceExample
{
class Program
{
/// <summary> The main entry point for the application. </summary>
static void Main(string[] args)
{
// Create the GPS point from your location services data
LonLatPt location = new LonLatPt();
// Modify Lat and Lon based on your needs
// This example uses the GPS Coordinates for "Eau Claire, Wisconsin, United States"
location.Lat = 44.811349;
location.Lon = -91.498494;
// Create a new TerraService object
TerraService ts = new TerraService();
// Output the nearest location from the TerraService
Console.WriteLine(ts.ConvertLonLatPtToNearestPlace(location));
// For console app to stay open/close easily
Console.WriteLine("Press any key to close window...");
Console.ReadKey();
// Lastly, appreciate the Microsoft folks that made this available for free
// They are all interesting individuals but you should read about Jim Gray via Wikipedia to
// understand some history behind this cool web service.
}
}
}