first I have to mention that I'm new to Android app development. I'm using Xamarin (C#) for developing apps. Here's the problem. I want to write simple ToDoList application to learn how to store/share data between activities.
Button "Add" is placed in Main layout. When user clicks it, another screen shows up where user can name(EditText) task and add its description(EditText). When user clicks button "Complete" in that screen, app redirects user to Main screen and add user's task to a listview.
I did some research and found out that I could do that with SharedPreferences, saving data to file on device, or sql.
I decided to go with SharedPreferences. Problem is, everything I found about SharedPrefences (and I searched a lot, believe me) is written in Java which wouldn't be such a big problem, but nobody ever mentioned sharing data between different activites using shared preferences. My code is below, I'm really struggling with this over a day, so please help me.
My MainActivity (where button "Add" is):
public class MainActivity : Activity
{
Button add;
ListView list;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
///set layout
SetContentView(Resource.Layout.Main);
///define variables, buttons, lists
add = FindViewById<Button>(Resource.Id.add);
list = FindViewById<ListView>(Resource.Id.list);
///get string from secondActivity
var prefs = Application.Context.GetSharedPreferences("todolist", FileCreationMode.Private);
var preference = prefs.GetString("task", null);
///add string (preference) to list
List<string> lista = new List<string>();
lista.Add(preference);
///"convert" list to listview
ArrayAdapter<string> adapter = new ArrayAdapter<string>(this, Resource.Layout.Main, lista);
list.Adapter = adapter;
add.Click += delegate
{
StartActivity(new Intent(this, typeof(addActivity)));
};
}
}
My second screen (second activity):
public class addActivity : Activity
{
/// define variables and create list
Button complete;
EditText name, description;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.add);
///variables
complete = FindViewById<Button>(Resource.Id.complete);
name = FindViewById<EditText>(Resource.Id.name);
description = FindViewById<EditText>(Resource.Id.description);
///converting to string
string title = name.Text.ToString();
string content = description.Text.ToString();
///pass string to MainActivity
complete.Click += delegate
{
if (String.IsNullOrEmpty(title))
{
Toast.MakeText(this, "Please enter task name", ToastLength.Short).Show();
}
else
{
var prefs = Application.Context.GetSharedPreferences("todolist", FileCreationMode.Private);
var prefEditor = prefs.Edit();
prefEditor.PutString("task", title);
prefEditor.Commit();
Toast.MakeText(this, "Task added", ToastLength.Short).Show();
StartActivity(new Intent(this, typeof(MainActivity)));
}
};
}
}