PDA

View Full Version : برنامه اندرویدی با زامارین و استفاده از SQLite



ghasem110deh
شنبه 27 آذر 1395, 18:25 عصر
بنام خدا
سلام به همه :-)
در خدمت دوستان هستیم با آموزش استفاده از زامارین و دیتابیس اسکیوال لایت ...
توجه: فقط از طریق NuGet کامپوننت sqlit.net-pcl رو به پروژه اضافه کنید !

بریم سر اصل مطلب :
خوب طبیعتا مثل برنامه نویسی با اندروید استودیو باید اول لایه های نمایشی (layout) رو ایجاد کرد !

لایه اصلی برنامه که بعد از اجرا به کاربر نمایش داده میشه (لانچر)



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:minWidth="25px"
android:minHeight="25px"
android:background="#3498DB">
<LinearLayout
android:orientation="vertical"
android:minWidth="25px"
android:minHeight="25px"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/linearLayout1"
android:layout_gravity="fill"
android:layout_margin="5dp">
<EditText
android:hint="نام کاربری"
android:gravity="center"
android:inputType="textPersonName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/edtName"
android:textColor="#ffffff" />
<EditText
android:hint="کلمه عبور"
android:gravity="center"
android:inputType="numberPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/edtPass"
android:textColor="#ffffff" />
<Button
android:gravity="center"
android:text="ورود"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnLogin"
android:layout_margin="5dp" />
<Button
android:gravity="center"
android:text="ایجاد حساب"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnRegisterPage"
android:layout_margin="5dp" />
<Button
android:gravity="center"
android:text="نمایش کاربران"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnShow"
android:layout_margin="5dp" />
</LinearLayout>
<ListView
android:minWidth="25px"
android:minHeight="25px"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/listVIEW" />
</LinearLayout>


این در واقع صفحه آبی رنگ توی تصاویر ضمیمه هست !

و اینم لایه رجیستر (یا همون ثبت نام و ورود اطلاعات توسط کاربر)



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:minWidth="25px"
android:minHeight="25px">
<ImageView
android:src="@android:drawable/ic_menu_gallery"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/imageView" />
<Button
android:text="انتخاب تصویر"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnSelectPic" />
<EditText
android:hint="نام کاربری"
android:gravity="center"
android:inputType="textPersonName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/edtName" />
<EditText
android:hint="کلمه عبور"
android:gravity="center"
android:inputType="numberPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/edtPass" />
<EditText
android:hint="توضیحات"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/edtDescription" />
<CheckBox
android:text="خانم هستید؟"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/checkGender" />
<Button
android:text="ثبت و ادامه"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnCreatAccunt" />
</LinearLayout>


نکته : اینجا یه لایه خالی داریم که به هیچ اکتیویتی ای مربوط نمیشه و در واقع ایجاد یک لیست ویو سفارشی هست ش



<?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"
android:minWidth="25px"
android:minHeight="25px">
<TextView
android:text="نام کاربری"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/txtName" />
<TextView
android:text="جنسیت"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/txtGender" />
<TextView
android:text="توضیحات"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/txtDescription" />
</LinearLayout>


این لایه نمایشی توی یک لایه که مربوط به اکتیویتی نمایش لیست اعضا هست نمایش داده میشه
لایه لیست اعضا تنها حاوی یه لیست ویو هست !

ghasem110deh
شنبه 27 آذر 1395, 18:30 عصر
خوب حالا بیام سراغ کار با دیتابیس و سی شارپ :-)

اول دیتابیس رو توی پوشه Assets پروژه اضافه کنید ... و یه کلاس ایجاد کنید به اسم Database یا هر اسم دیگه ای که دوست دارین :

using Android.App;
using Android.Util;
using SQLite;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace ExistingSqliteSample.Resources.Model
{
public class DataBase
{
#region copy and create database and tables
public string sqliteCon()
{
try
{
string path = Environment.GetFolderPath(Environment.SpecialFolde r.Personal);
string dbPath = Path.Combine(path, "fitnessDBupdate.db");
CopyDatabase("fitnessDBupdate.db");
string conn = dbPath;
return conn;
}
catch (SQLiteException ex)
{
Log.Info("SQLite Ex", ex.ToString());
return null;
}
}

private void CopyDatabase(string dataBaseName)
{
try
{
var dbPath = Path.Combine(Environment.GetFolderPath(Environment .SpecialFolder.Personal), dataBaseName);
if (!File.Exists(dbPath))
{
var dbAssetStream = Application.Context.Assets.Open(dataBaseName);
var dbFileStream = new FileStream(dbPath, FileMode.OpenOrCreate);
var buffer = new byte[1024];
int b = buffer.Length;
int length;
while ((length = dbAssetStream.Read(buffer, 0, b)) > 0)
{
dbFileStream.Write(buffer, 0, length);
}
dbFileStream.Flush();
dbFileStream.Close();
dbAssetStream.Close();
}
}
catch (SQLiteException ex)
{
Log.Info("SQLite Ex", ex.ToString());
}
}

public void createTables()
{
try
{
using (var conn = new SQLiteConnection(sqliteCon()))
{
conn.CreateTable<Members>();
}
}
catch (SQLiteException ex)
{
Log.Info("SQLite Ex", ex.ToString());
}
}
#endregion

#region tbl Members
public bool insertMembers(Members members)
{
try
{
using (var conn = new SQLiteConnection(sqliteCon()))
{
conn.Insert(members);
}
return true;
}
catch (SQLiteException ex)
{
Log.Info("SQLite EX", ex.ToString());
return false;
}
}

public bool updateMembers(Members members)
{
try
{
using (var conn = new SQLiteConnection(sqliteCon()))
{
conn.Query<Members>("Update tblMembers Set fullName=?, gender=?, memDescription=?, pic=?, password=? Where id=?",
members.fullName, members.gender, members.memDescription, members.pic, members.password, members.id);
}
return true;
}
catch (SQLiteException ex)
{
Log.Info("SQLite EX", ex.ToString());
return false;
}
}

public bool deleteMembers(Members members)
{
try
{
using (var conn = new SQLiteConnection(sqliteCon()))
{
conn.Delete(members);
}
return true;
}
catch (SQLiteException ex)
{
Log.Info("SQLite EX", ex.ToString());
return false;
}
}

public bool selectMembers(int id)
{
try
{
using (var conn = new SQLiteConnection(sqliteCon()))
{
conn.Query<Members>("Select * From tblMembers Where id=?", id);
}
return true;
}
catch (SQLiteException ex)
{
Log.Info("SQLite EX", ex.ToString());
return false;
}
}

public bool loginMembers(string fullName, string password)
{
try
{
using (var conn = new SQLiteConnection(sqliteCon()))
{
conn.Query<Members>("Select * From tblMembers Where (fullName=? And password=?)", fullName, password);
}
return true;
}
catch (SQLiteException ex)
{
Log.Info("SQLite EX", ex.ToString());
return false;
}
}

public List<Members> listMembers()
{
try
{
using (var conn = new SQLiteConnection(sqliteCon()))
{
return conn.Table<Members>().ToList();
}
}
catch (SQLiteException ex)
{
Log.Info("SQLite EX", ex.ToString());
return null;
}
}
#endregion
}
}

چون دوستان سی شارپ کار میکنید دیگه توضیحی در مورد کد ها نمیدم ... فقط اگه سوالی بود بپرسین !
اگه بتونم جواب میدم :-)

ghasem110deh
شنبه 27 آذر 1395, 18:39 عصر
کلاسی برای تعریف فیلد های جدول و ...
یه پوشه به اسم model اضافه کنید و داخل اون کلاس رو ایجاد کنید :


using SQLite;

namespace ExistingSqliteSample.Resources.Model
{
[Table("tblMembers")]
public class Members
{
[PrimaryKey, AutoIncrement, Column("id")]
public int id { get; set; }

[MaxLength(50), Column("fullName")]
public string fullName { get; set; }

[Column("gender")]
public bool gender { get; set; }

[MaxLength(100), Column("memDescription")]
public string memDescription { get; set; }

[Column("pic")]
public byte[] pic { get; set; }

[MaxLength(16), Column("password")]
public string password { get; set; }
}
}

ghasem110deh
شنبه 27 آذر 1395, 18:40 عصر
ایجاد کلاس آداپتر برای خوندن اطلاعات جدول و نمایش در لیست ویو ...



using Android.App;
using Android.Views;
using Android.Widget;
using ExistingSqliteSample.Resources.Model;
using System.Collections.Generic;

namespace ExistingSqliteSample.Resources
{
public class ViewHolder : Java.Lang.Object
{
public TextView txtName { get; set; }
public TextView txtGender { get; set; }
public TextView txtDescription { get; set; }
}

public class ListViewAdapter : BaseAdapter
{
private Activity activity;
private List<Members> lstmem;

public ListViewAdapter(Activity activity, List<Members> lstmem)
{
this.activity = activity;
this.lstmem = lstmem;
}

public override int Count
{
get
{
return lstmem.Count;
}
}

public override Java.Lang.Object GetItem(int position)
{
return null;
}

public override long GetItemId(int position)
{
return lstmem[position].id;
}

public override View GetView(int position, View convertView, ViewGroup parent)
{
var view = convertView ?? activity.LayoutInflater.Inflate(Resource.Layout.us er_listview, parent, false);
var txtName = view.FindViewById<TextView>(Resource.Id.txtName);
var txtGender = view.FindViewById<TextView>(Resource.Id.txtGender);
var txtDescription = view.FindViewById<TextView>(Resource.Id.txtDescription);
txtName.Text = lstmem[position].fullName;
if (lstmem[position].gender)
txtGender.Text = "آقا";
else
txtGender.Text = "خانم";
txtDescription.Text = lstmem[position].memDescription;
return view;
}
}
}

ghasem110deh
شنبه 27 آذر 1395, 18:41 عصر
اکتیوی اصلی :



using Android.App;
using Android.OS;
using Android.Widget;
using ExistingSqliteSample.Resources;
using ExistingSqliteSample.Resources.Model;
using System;
using System.Collections.Generic;

namespace ExistingSqliteSample
{
[Activity(Label = "ExistingSqliteSample", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{

Button btnRegister;
Button btnLog;
Button btnDisplay;
EditText edtName;
EditText edtPass;

protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);

// معرفی کنترل ها
btnRegister = FindViewById<Button>(Resource.Id.btnRegisterPage);
btnLog = FindViewById<Button>(Resource.Id.btnLogin);
btnDisplay = FindViewById<Button>(Resource.Id.btnShow);
edtName = FindViewById<EditText>(Resource.Id.edtName);
edtPass = FindViewById<EditText>(Resource.Id.edtPass);

// رویدادها
btnLog.Click += delegate
{

};

btnRegister.Click += delegate
{
StartActivity(typeof(RgisterActivity));
};

btnDisplay.Click += delegate
{
StartActivity(typeof(UserinfoActivity));
};
}
}
}

ghasem110deh
شنبه 27 آذر 1395, 18:42 عصر
رجیستر اکتیوتی :



using Android.App;
using Android.Content;
using Android.Graphics;
using Android.OS;
using Android.Util;
using Android.Widget;
using ExistingSqliteSample.Resources.Model;
using SQLite;
using System;
using System.IO;

namespace ExistingSqliteSample
{
[Activity(Label = "RgisterActivity")]
public class RgisterActivity : Activity
{
Button btnselectImage;
Button btnCreateAcount;
EditText edtuserName;
EditText edtpassword;
EditText edtdescription;
CheckBox checkGender;
ImageView userImg;

public static readonly int PickImageId = 1000;
bool gender = false;

DataBase db;

protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Register);
// Create your application here

btnselectImage = FindViewById<Button>(Resource.Id.btnSelectPic);
btnCreateAcount = FindViewById<Button>(Resource.Id.btnCreatAccunt);
edtpassword = FindViewById<EditText>(Resource.Id.edtPass);
edtuserName = FindViewById<EditText>(Resource.Id.edtName);
edtdescription = FindViewById<EditText>(Resource.Id.edtDescription);
userImg = FindViewById<ImageView>(Resource.Id.imageView);
checkGender = FindViewById<CheckBox>(Resource.Id.checkGender);

checkGender.CheckedChange += delegate
{
if (checkGender.Checked)
gender = true;
else
gender = false;
};

btnCreateAcount.Click += delegate
{
try
{
userImg.DrawingCacheEnabled = true;
userImg.BuildDrawingCache();
Bitmap bm = userImg.GetDrawingCache(true);
MemoryStream stream = new MemoryStream();
bm.Compress(Bitmap.CompressFormat.Png, 0, stream);
byte[] byteArray = stream.ToArray();
Members mem = new Members()
{
fullName = edtuserName.Text.Trim(),
password = edtpassword.Text.Trim(),
memDescription = edtdescription.Text.Trim(),
gender = gender,
pic = byteArray
};
db = new DataBase();
db.insertMembers(mem);
Toast.MakeText(this, "کاربر جدید ثبت شد", ToastLength.Short).Show();
}
catch (Exception ex)
{
Toast.MakeText(this, ex.ToString(), ToastLength.Short).Show();
}
};

btnselectImage.Click += delegate
{
try
{
Intent = new Intent();
Intent.SetType("*.Png");
Intent.SetAction(Intent.ActionGetContent);
StartActivityForResult(Intent.CreateChooser(Intent , "انتخاب عکس"), PickImageId);
}
catch (SQLiteException ex)
{
Log.Info("SQLite Ex", ex.ToString());
}
};
}

protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
try
{
if ((requestCode == PickImageId) && (resultCode == Result.Ok) && (data != null))
{
Android.Net.Uri uri = data.Data;
userImg.SetImageURI(uri);
}
}
catch (SQLiteException ex)
{
Log.Info("SQLite Ex", ex.ToString());
}
}
}
}

ghasem110deh
شنبه 27 آذر 1395, 18:43 عصر
آپدیت اکتیویتی :



using Android.App;
using Android.Content;
using Android.Graphics;
using Android.OS;
using Android.Util;
using Android.Widget;
using ExistingSqliteSample.Resources.Model;
using SQLite;
using System;
using System.IO;

namespace ExistingSqliteSample
{
[Activity(Label = "UpdateActivity")]
public class UpdateActivity : Activity
{
Button selectImage;
Button upadte;
Button delete;
ImageView imgUser;
public EditText edtName;
EditText edtPass;
public EditText edtDesc;
public CheckBox checkGender;

public static readonly int PickImageId = 1000;
bool gender = false;

DataBase db;

protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Update);

selectImage = FindViewById<Button>(Resource.Id.UDbtnSelectImage);
upadte = FindViewById<Button>(Resource.Id.UDbtnUpdate);
delete = FindViewById<Button>(Resource.Id.UDbtnInsert);
edtName = FindViewById<EditText>(Resource.Id.UDedtName);
edtPass = FindViewById<EditText>(Resource.Id.UDedtPass);
edtDesc = FindViewById<EditText>(Resource.Id.UDedtDescription);
checkGender = FindViewById<CheckBox>(Resource.Id.UDcheck);

selectImage.Click += delegate
{
try
{
Intent = new Intent();
Intent.SetType("*.Png");
Intent.SetAction(Intent.ActionGetContent);
StartActivityForResult(Intent.CreateChooser(Intent , "انتخاب عکس"), PickImageId);
}
catch (SQLiteException ex)
{
Log.Info("SQLite Ex", ex.ToString());
}
};

upadte.Click += delegate
{
try
{
imgUser.DrawingCacheEnabled = true;
imgUser.BuildDrawingCache();
Bitmap bm = imgUser.GetDrawingCache(true);
MemoryStream stream = new MemoryStream();
bm.Compress(Bitmap.CompressFormat.Png, 0, stream);
byte[] byteArray = stream.ToArray();
Members mem = new Members()
{
id = int.Parse(edtName.Tag.ToString()),
fullName = edtName.Text.Trim(),
password = edtPass.Text.Trim(),
memDescription = edtDesc.Text.Trim(),
gender = gender,
pic = byteArray
};
db = new DataBase();
db.updateMembers(mem);
Toast.MakeText(this, "کاربر ویرایش شد", ToastLength.Short).Show();
}
catch (Exception ex)
{
Toast.MakeText(this, ex.ToString(), ToastLength.Short).Show();
}
};

delete.Click += delegate
{
try
{
imgUser.DrawingCacheEnabled = true;
imgUser.BuildDrawingCache();
Bitmap bm = imgUser.GetDrawingCache(true);
MemoryStream stream = new MemoryStream();
bm.Compress(Bitmap.CompressFormat.Png, 0, stream);
byte[] byteArray = stream.ToArray();
Members mem = new Members()
{
id = int.Parse(edtName.Tag.ToString()),
fullName = edtName.Text.Trim(),
password = edtPass.Text.Trim(),
memDescription = edtDesc.Text.Trim(),
gender = gender,
pic = byteArray
};
db = new DataBase();
db.deleteMembers(mem);
Toast.MakeText(this, "کاربر حذف شد", ToastLength.Short).Show();
}
catch (Exception ex)
{
Toast.MakeText(this, ex.ToString(), ToastLength.Short).Show();
}
};

checkGender.CheckedChange += delegate
{
if (checkGender.Checked)
gender = true;
else
gender = false;
};
}

protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
try
{
if ((requestCode == PickImageId) && (resultCode == Result.Ok) && (data != null))
{
Android.Net.Uri uri = data.Data;
imgUser.SetImageURI(uri);
}
}
catch (SQLiteException ex)
{
Log.Info("SQLite Ex", ex.ToString());
}
}
}
}

ghasem110deh
شنبه 27 آذر 1395, 18:44 عصر
یوزر اینفو اکتیوتی :
(نمایش اطلاعات دیتابیس با لیست ویو)



using Android.App;
using Android.OS;
using Android.Util;
using Android.Widget;
using ExistingSqliteSample.Resources;
using ExistingSqliteSample.Resources.Model;
using SQLite;
using System.Collections.Generic;

namespace ExistingSqliteSample
{
[Activity(Label = "UserinfoActivity")]
public class UserinfoActivity : Activity
{
ListView lslmem;
List<Members> lsltable = new List<Members>();
DataBase db;

protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Userinfo);
db = new DataBase();
lslmem = FindViewById<ListView>(Resource.Id.listView);
LoadData();
lslmem.ItemSelected += delegate
{
lslmem.GetChildAt(0).SetBackgroundColor(Android.Gr aphics.Color.DarkGray);
};

lslmem.ItemLongClick += (s, e) =>
{
StartActivity(typeof(UpdateActivity));

};
}

private void LoadData()
{
try
{
lsltable = db.listMembers();
var adapter = new ListViewAdapter(this, lsltable);
lslmem.Adapter = adapter;
}
catch (SQLiteException ex)
{
Log.Info("SQLite Ex", ex.ToString());
}
}
}
}

ghasem110deh
شنبه 27 آذر 1395, 18:47 عصر
دوستان ببخشید اگه زیادی مختصر و مفید شد :-)
سوالی بود بپرسین ...

یه نکته هم حیفم میاد نگم : خودم شخصا ترجیح دادم برم سراغ اندروید استودیو !
ولی به این معنی نیست که زامارین جواب نمیده .

M aJi D
چهارشنبه 25 اسفند 1395, 23:47 عصر
سلام
دوستانی که دوست دارن آموزشی برای کار با زامارین ببینند می تونند به مرجع فارسی آموزش زامارین (http://xamarinfa.ir) مراجعه کنند .