Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with reading text file from assets (xamarin)

I have problem with reading simple txt from assets directory. I can't really figure out why it doesn't work and what is wrong.

Here is the code of method I wrote:

        private string ReadFile(){
        var stream = Assets.Open ("sampleText.txt");
        StreamReader sr = new StreamReader (stream);
        string text = sr.ReadToEnd ();
        sr.Close ();
        return text;
    }

And here is the error:

Java.Lang.NullPointerException: Exception of type 'Java.Lang.NullPointerException' was thrown.
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/data/lanes/2970/46c3f7e0/source/mono/external/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143 
at Android.Runtime.JNIEnv.CallNonvirtualObjectMethod (IntPtr jobject, IntPtr jclass, IntPtr jmethod) [0x00084] in /Users/builder/data/lanes/2970/46c3f7e0/source/monodroid/src/Mono.Android/src/Runtime/JNIEnv.g.cs:596 
at Android.Content.ContextWrapper.get_Assets () [0x0005f] in /Users/builder/data/lanes/2970/46c3f7e0/source/monodroid/src/Mono.Android/platforms/android-19/src/generated/Android.Content.ContextWrapper.cs:154 

I had no problems with running my whole application on windows, just I have problems to run it on android. Tried various things, like instance of AssetManager, but didn't work as well.

The text file is marked as AndroidAsset.

This is my TextChangeBench:

public class TextChangeBench : Activity
{
    public TextChangeBench (){}

    private void SaveFile(string[] tab){

        string saveLocation = "sampleTextReworked.txt";
        StreamWriter sw = new StreamWriter (saveLocation);
        foreach (string s in tab) {
            sw.Write (s);
        }
        sw.Close ();
    }

    private string ReadFile(){
        var stream = Assets.Open ("sampleText.txt");
        StreamReader sr = new StreamReader (stream);
        string text = sr.ReadToEnd ();
        sr.Close ();
        return text;
    }
    public void ChangeText(){
        try{
            File.Delete("sampleTextReworked.txt");
        }catch(FileNotFoundException e){Console.WriteLine (e);}

        try{
            string text = ReadFile ();
            char c;
            string[] newTab = new string[text.Length];
            for (int i = 0; i < text.Length; i++)
            {
                c = (char)text [i];
                if (Char.IsUpper(c))
                {
                    newTab[i] = text[i].ToString().ToLower();
                }
                else if (Char.IsLower(c))
                {
                    newTab[i] = text[i].ToString().ToUpper();
                }
                else
                {
                    newTab[i] = text[i].ToString();
                }
            }
            SaveFile(newTab);
        }
        catch(Exception e){Console.WriteLine ("{0} ", e);}
    }
}

This is my MainActivity:

[Activity (Label = "csBench", MainLauncher = true, Icon = "@mipmap/icon")]
public class MainActivity : Activity
{
    protected override void OnCreate (Bundle savedInstanceState)
    {
        base.OnCreate (savedInstanceState);

        SetContentView (Resource.Layout.Main);
        Button startButton = FindViewById<Button> (Resource.Id.start);
        startButton.Click += delegate {

            MathBench mb = new MathBench ();
            TextChangeBench tcb = new TextChangeBench ();
            PassedTime pt = new PassedTime ();
            EditText et = (EditText)FindViewById (Resource.Id.textInfo);

            for (int i = 0; i < 5; i++) {
                pt.StartMeasuring ();
                //mb.Silnia (25);
                //mb.Fibonacci (32);
                //mb.BubbleSort ();
                tcb.ChangeText ();
                if (i == 4) {
                    pt.StopMeasuring ();

                    et.SetText(pt.ReturnResult(), TextView.BufferType.Normal);
                    //et.SetText(pt.ReturnResult().ToString());
                    //Console.WriteLine(pt.ReturnResult ());
                    pt.ResetTimers ();
                }
            }  
        };

    }
}

Any help is welcome, thanks in advance.

like image 724
definitelyNotLazy Avatar asked Dec 25 '22 07:12

definitelyNotLazy


1 Answers

This error is occurring because manually creating an instance of an activity such as TextChangeBench circumvents the Android frameworks setup process leaving the activity in an invalid state.

Activities are used as a point of user interaction, binding a view/screen to logic in your application. As TextChangeBench only implements application logic, it doesn't need to be derived from Activity and would be better suited as a plain C# class.

Remove the inheritance to activity to simplify the code for TextChangeBench. This means we no longer have access to the Assets property thus cannot retrieve assets. We can fix this by instead using the global application context:

var stream = Android.App.Application.Context.Assets.Open("sampleText.txt");

The combination of removing the activity inheritance and using the global context to access the asset manager will fix the Java.Lang.NullPointerException.

The final code would look like this:

public class TextChangeBench 
{
    private void SaveFile(string[] tab)
    {

        string saveLocation = "sampleTextReworked.txt";
        StreamWriter sw = new StreamWriter(saveLocation);
        foreach (string s in tab)
        {
            sw.Write(s);
        }
        sw.Close();
    }

    private string ReadFile()
    {
        var stream = Android.App.Application.Context.Assets.Open("sampleText.txt");

        StreamReader sr = new StreamReader(stream);
        string text = sr.ReadToEnd();
        sr.Close();
        return text;
    }
    public void ChangeText()
    {
        try
        {
            File.Delete("sampleTextReworked.txt");
        }
        catch (FileNotFoundException e) { Console.WriteLine(e); }

        try
        {
            string text = ReadFile();
            char c;
            string[] newTab = new string[text.Length];
            for (int i = 0; i < text.Length; i++)
            {
                c = (char)text[i];
                if (Char.IsUpper(c))
                {
                    newTab[i] = text[i].ToString().ToLower();
                }
                else if (Char.IsLower(c))
                {
                    newTab[i] = text[i].ToString().ToUpper();
                }
                else
                {
                    newTab[i] = text[i].ToString();
                }
            }
            SaveFile(newTab);
        }
        catch (Exception e) { Console.WriteLine("{0} ", e); }
    }
}

See:

  • Xamarin Toast Message error (C#)
  • How to use the method of an Activity in a DialogFragment?
like image 122
matthewrdev Avatar answered Dec 29 '22 06:12

matthewrdev