how to Creating pdf file - xamarin.android

I used a library itextsharp .
I used the following code to create PDF File and print it , but the next error occurs, what code is missing ?.
Severity Code Description Project File Line Suppression State Suppression State Error Can not resolve reference: System.Drawing, referenced by itextsharp. Please add a NuGet package or assembly reference for System.Drawing, or remove the reference to itextsharp. print_pdf
full code
using Android.App;
using Android.OS;
using Android.Support.V7.App;
using Android.Runtime;
using Android.Widget;
using System.IO;
using Android.Content;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace print_pdf
{
[Activity(Label = "#string/app_name", Theme = "#style/AppTheme", MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
var directory = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory, "pdf").ToString();
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
var path = Path.Combine(directory, "myTestFile.pdf");
if (File.Exists(path))
{
File.Delete(path);
}
var fs = new FileStream(path, FileMode.Create);
Document document = new Document(PageSize.A4, 25, 25, 30, 30);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.Open();
document.Add(new Paragraph("Hello World"));
document.Close();
writer.Close();
fs.Close();
Java.IO.File file = new Java.IO.File(path);
Intent intent = new Intent(Intent.ActionView);
intent.SetDataAndType(Android.Net.Uri.FromFile(file), "application/pdf");
StartActivity(intent);
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}

Try to add the add System.Drawing.dll as references
Right click on References --> Add Referencesc --> Assembly --> Browse... --> C:\Windows\Microsoft.NET\Framework\v4.0.30319 --> select System.Drawing.dll.

Related

Show ProgressBar programattically while user logging on

I found this class at Centering ProgressBar Programmatically in Android which would display a progressbar programmatically, problem is it's an Xamarin Android Studio example and I'm trying to convert it to Xamarin for Visual Studio 2017. This is the code that I have successfully converted with those lines that I can't seem to find a Xamarin VS 2017 equivalent for.
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace OML_Android
{
class ProgressBarHandler
{
private ProgressBar mProgressBar;
private Context mContext;
public ProgressBarHandler(Context context)
{
mContext = context;
ViewGroup layout = (ViewGroup)((Activity)context).FindViewById(Android.Resource.Id.Content).RootView;
mProgressBar = new ProgressBar(context, null, Android.Resource.Attribute.ProgressBarStyleLarge);
// there is no setIndeterminate method for progressbar
mProgressBar.setIndeterminate(true);
// I cannot find an equivilent for LayoutParams
RelativeLayout.LayoutParams params = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MatchParent, RelativeLayout.LayoutParams.MatchParent);
RelativeLayout rl = new RelativeLayout(context);
// No equivalent for Gravity.CENTER
rl.SetGravity(Gravity.CENTER);
rl.AddView(mProgressBar);
layout.AddView(rl, params);
hide();
}
public void show()
{
mProgressBar.Visibility = Android.Views.ViewStates.Visible;
}
public void hide()
{
mProgressBar.Visibility = Android.Views.ViewStates.Invisible;
}
}
}
Once I have this converted and working I want it to overlay my logon view until the view finishes processing.
I help you transform Java code to C#, there is running GIF.
There is code.
class ProgressBarHandler
{
private ProgressBar mProgressBar;
private Context mContext;
public ProgressBarHandler(Context context)
{
mContext = context;
ViewGroup layout = (ViewGroup)((Activity)context).FindViewById(Android.Resource.Id.Content).RootView;
mProgressBar = new ProgressBar(context, null, Android.Resource.Attribute.ProgressBarStyleLarge);
// there is no setIndeterminate method for progressbar
// mProgressBar.SetIndeterminate(true);
mProgressBar.Indeterminate = true;
// I cannot find an equivilent for LayoutParams
RelativeLayout.LayoutParams layoutparams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MatchParent, RelativeLayout.LayoutParams.MatchParent);
RelativeLayout rl = new RelativeLayout(context);
// No equivalent for Gravity.CENTER
rl.SetGravity(GravityFlags.Center );
rl.AddView(mProgressBar);
layout.AddView(rl, layoutparams);
hide();
}
public void show()
{
mProgressBar.Visibility = Android.Views.ViewStates.Visible;
}
public void hide()
{
mProgressBar.Visibility = Android.Views.ViewStates.Invisible;
}
}
You can use it directly like following code in Activity.
var progress= new ProgressBarHandler(this);
progress.show();

Object reference not set to an instance of an object - Select statement Sqlite Xamarin iOS

I am fetching the values from sqlite database in my iOS application. I have written a Select statement like stringquery = "Select * from tablename" and executing it using
database.Query < table > (stringquery);
and assigning the values to the properties in a class. The class has properties with the same name that the columns has in the table in sqlite database.
as the above statement executes i am getting error Object reference not set to an instance of an object
Please suggest the solution this issue.
Thanks
It sounds like you are initializing the SQLite Database incorrectly. I've added code below that shows how to implement a SQLite Database in Xamarin.Forms.
This Xamarin.Forms app, contains a fully implemented SQLite Database:
https://github.com/brminnick/InvestmentDataSampleApp
ISQLite.cs
Create this file in the Xamarin.Forms PCL. It allows us to access the iOS and Android File Systems to create our Database Connection
using SQLite;
namespace SampleApp
{
public interface ISQLite
{
SQLiteAsyncConnection GetConnection();
}
}
SQLite_Android.cs
Create this file in the Android project. It returns the Android file path for our SQLite Database Connection.
using System.IO;
using SampleApp.Droid;
using SQLite;
using Xamarin.Forms;
[assembly: Dependency(typeof(SQLite_Android))]
namespace SampleApp.Droid
{
public class SQLite_Android : ISQLite
{
#region ISQLite implementation
public SQLiteAsyncConnection GetConnection()
{
var sqliteFilename = "DatabaseFileName.db3";
string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); // Documents folder
var path = Path.Combine(documentsPath, sqliteFilename);
var conn = new SQLiteAsyncConnection(path, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create | SQLiteOpenFlags.SharedCache);
// Return the database connection
return conn;
}
#endregion
}
}
SQLite_iOS.cs
Create this file in the iOS project. It returns the iOS file path for our SQLite Database Connection.
using System;
using System.IO;
using SQLite;
using Xamarin.Forms;
using SampleApp.iOS;
[assembly: Dependency(typeof(SQLite_iOS))]
namespace SampleApp.iOS
{
public class SQLite_iOS : ISQLite
{
#region ISQLite implementation
public SQLiteAsyncConnection GetConnection()
{
var sqliteFilename = "DatabaseFileName.db3";
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); // Documents folder
string libraryPath = Path.Combine(documentsPath, "..", "Library"); // Library folder
var path = Path.Combine(libraryPath, sqliteFilename);
var conn = new SQLiteAsyncConnection(path, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create | SQLiteOpenFlags.SharedCache);
// Return the database connection
return conn;
}
#endregion
}
}
SampleModelDatabase.cs
Create this file in your Xamarin.Forms PCL
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using SQLite;
using Xamarin.Forms;
namespace SampleApp
{
public static class SampleModelDatabase
{
#region Constant Fields
static readonly SQLiteAsyncConnection _database = DependencyService.Get<ISQLite>().GetConnection();
#endregion
#region Fields
static bool _isInitialized;
#endregion
#region Methods
public static async Task<IList<SampleModel>> GetAllItemsAsync()
{
if (!_isInitialized)
await Initialize();
return await _database.Table<SampleModel>().ToListAsync();
}
public static async Task<int> SaveItemAsync(SampleModel model)
{
if (!_isInitialized)
await Initialize();
return await _database.InsertOrReplaceAsync(model);
}
public static async Task<int> DeleteItemAsync(SampleModel model)
{
if (!_isInitialized)
await Initialize();
return await _database.DeleteAsync(model);
}
public static async Task<int> GetNumberOfRowsAsync()
{
if (!_isInitialized)
await Initialize();
return await _database.Table<SampleModel>().CountAsync();
}
static async Task Initialize()
{
await _database.CreateTableAsync<SampleModel>();
_isInitialized = true;
}
#endregion
}
}
I encountered the same problem as you. I found out that the point is database connection, a process that takes time, hasn't completely finished at the moment I started my query. so the solution will be something like:
await Connectdb();
// now do your query
var treatment = _database.Query<ClassName>("SELECT * FROM [TableName] WHERE ...");
where the Connectdb() is a function that does:
DependencyService.Get<IDatabaseConnection>().DbConnection();

Set ringtones as default ringtone or for some phone number

i want to create an app to use ringtones to set as default ringtone or set that ringtone for specific phone number. Can you help me with the code.
I saw many posts but anyone showed what i should actually have to do. So i decided to create this complete answer , you can start by using this sample code...
Here is my MainActivity.java which i used
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
b2 = (Button) findViewById(R.id.button2);
b2.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
Intent intent1 = new Intent();
intent1.setAction(Intent.ACTION_GET_CONTENT);
intent1.setType("audio/*");
startActivityForResult(Intent.createChooser(intent1, "Choose Sound File"), 6);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode ==RESULT_OK&&requestCode==6){
Uri i = data.getData(); //getDATA
String s = = i.getPath(); //getPath
File k = new File(s); //set File from path
if(s!=null){ //(file.exists
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "ring");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.MediaColumns.SIZE, k.length());
values.put(MediaStore.Audio.Media.ARTIST, R.string.app_name);
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, true);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
Uri uri = MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath());
getContentResolver().delete(uri, MediaStore.MediaColumns.DATA + "=\"" + k.getAbsolutePath() + "\"", null);
Uri newUri = getContentResolver().insert(uri, values);
try {
RingtoneManager.setActualDefaultRingtoneUri(MainActivity.this, RingtoneManager.TYPE_RINGTONE, newUri);
} catch (Throwable t) {
}
}
}
}
}
Lastly its really important to add those permisions in your AndroidManifest.xml for example if you dont add the permision to write external storage your app will crash like mine.. xD
What you need:
<uses-permission android:name="android.permission.WRITE_SETTINGS" ></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION" ></uses-permission>
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" ></uses-permission>
You can try my app on Google Play : BackAtel Audio Manager
Hope that helps....

How to Get GPS base on Wifi using Xamarin

This code base on the link below:
http://docs.xamarin.com/guides/android/platform_features/maps_and_location/part_3_-_location_services
I could not get any Lat/Lon ( Gps/Wifi)
The code is below :
I have added:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
&lt:uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Android.Locations
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
//-- add these
using Android.Locations;
using System.Collections.Generic;
using System.Threading;
using System.Text;
using System.Linq;
using System.Xml;
namespace GPSWifi
{
[Activity (Label = "GPSWifi", MainLauncher = true)]
public class Activity1 : Activity
{
int count = 1;
private LocationManager _locMgr;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
InitializeLocationManager();
}
private void InitializeLocationManager()
{
_locMgr = (LocationManager) GetSystemService(LocationService);
var locationCriteria = new Criteria();
locationCriteria.Accuracy = Accuracy.NoRequirement;
locationCriteria.PowerRequirement = Power.NoRequirement;
string locationProvider = _locMgr.GetBestProvider(locationCriteria, true);
_locMgr.RequestLocationUpdates (locationProvider, 2000, 1, this);
}
protected override void OnResume ()
{
base.OnResume ();
_locMgr.RequestLocationUpdates (LocationManager.GpsProvider, 2000, 1, this);
}
protected override void OnPause ()
{
base.OnPause ();
_locMgr.RemoveUpdates (this);
}
public void OnProviderDisabled(string provider) {}
public void OnProviderEnabled(string provider) {}
public void OnLocationChanged (Location location)
{
var locationText = FindViewById<TextView>(Resource.Id.locationTextView);
locationText.Text = String.Format ("Latitude = {0}, Longitude = {1}",
location.Latitude, location.Longitude);
}
}
}
Your help is much appreciated.
-- Error Message :
C:\Program Files
(x86)\MSBuild\Xamarin\Android\Xamarin.Android.Common.targets(2,2):
Error MSB4018: The "Aapt" task failed unexpectedly.
System.InvalidOperationException: Sequence contains no elements
at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
at Xamarin.Android.Tasks.BuildToolsUtils.GetBuildToolsPath(String
androidSdkDirectory)
at Xamarin.Android.Tasks.Aapt.GenerateFullPathToTool()
at Microsoft.Build.Utilities.ToolTask.ComputePathToTool()
at Microsoft.Build.Utilities.ToolTask.Execute()
at Xamarin.Android.Tasks.Aapt.Execute()
at
Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
at
Microsoft.Build.BackEnd.TaskBuilder.d__20.MoveNext()
(MSB4018) (GPSWifi)
This error: The "Aapt" task failed unexpectedly. has just started occurring recently - I think it's to do with the very latest sdk's from Android/Google - I think they've moved a file location.
Check other questions like Xamarin Studio 2 - latest stable update - Error executing task Aapt: The source sequence is empty
Then check with Xamarin support - they'll issue an update to fix this.

Android File Chooser Return path to main class

I want to implement an Android file chooser for OCR.
I have the source code from this site: here
What I want is to create a main Activity using an intent to call the FileChooser
public class MainFileChooser extends Activity {
Button btnBrowse =null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.utama);
btnBrowse = (Button)findViewById(R.id.btnBrowse);
btnBrowse.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setClass(MainFileChooser.this, FileChooser.class);
startActivity(intent);
}
});
}
}
While the button is clicked it will be linked to FileChooser and then while a tile is clicked the activity will be returned toMainFileChooser and also return the file path.
The File Path will be processed for OCR such as converting to gray scale, features extraction and so on.
The Question is how can I return the image path to MainFileChooser activity and for the given path I can create bitmap image (buffered image)?
Like the source code for FileChooser suggested, you can modify onFileClick to return the image path:
private void onFileClick(Option o) {
String path = o.getName();
Intent data = new Intent();
data.putExtra("path", path);
setResult(Activity.RESULT_OK, data);
finish();
}
Then, in MainFileChooser, instead of startActivity, use startActivityForResult:
setActivityForResult(intent, 1234);
You will also need to add onActivityResult to MainFileChooser to get the filename:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && requestCode == 1234) {
String path = data.getStringExtra("path");
Toast.makeText(this, "Path: " + path, Toast.LENGTH_SHORT).show();
}
}

Resources