Issue
After asking a related question here on this forum, am so grateful to have found code to open a file picker interface to enable user choose a file with mime type (".txt"), No i need to advance past this and load the content of that text file into an edit text present on my activity's layout... The code that opens the file picker interface lies inside a button method...To cut the long story short the rest of my code is explained below.
class Notes:AppCompatActivity
{
//Declare this edit text variable in the class so that all methods can access it without having to redefine it
EditText notes;
protected override void OnCreate(Bundle onSavedInstanceState){
//Assign the edit text
notes = this.FindViewById<EditText>(Resource.Id.editext5);
}
//This button method opens the file picker interface when the button is clicked
private void Button2_Click(object sender, EventArgs e)
{
//Program the open file text behavior from here
Intent intent = new Intent();
intent.SetType("text/plain");
intent.SetAction(Intent.ActionGetContent);
StartActivityForResult(Intent.CreateChooser(intent, "Select file"), 1);
}
//I had this idea to override StartActivityForResult method but am not even sure that is what i should do
public override void StartActivityForResult(Intent intent, int requestCode)
{
base.StartActivityForResult(intent, requestCode);
}
}
Code that will help me load the text existing in the selected file into my edit text will surely be appreciated, Thanks...
Solution
After you select file,you will get the data in the OnActivityResult
method,you could try below method:
class Notes:AppCompatActivity
{
//Declare this edit text variable in the class so that all methods can access it without having to redefine it
EditText notes;
protected override void OnCreate(Bundle onSavedInstanceState){
//Assign the edit text
notes = this.FindViewById<EditText>(Resource.Id.editext5);
}
//This button method opens the file picker interface when the button is clicked
private void Button2_Click(object sender, EventArgs e)
{
//Program the open file text behavior from here
Intent intent = new Intent();
intent.SetType("text/plain");
intent.SetAction(Intent.ActionGetContent);
StartActivityForResult(Intent.CreateChooser(intent, "Select file"), 1);
}
protected override async void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == Result.Ok)
{
var uri = data.Data;
var stream = ContentResolver.OpenInputStream(uri);
string str = "";
StringBuffer buf = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
while ((str = reader.ReadLine()) != null)
{
buf.Append(str + "\n");
}
stream.Close();
notes.Text = buf.ToString();
}
}
}
Answered By - Leo Zhu - MSFT
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.