3
            package com.example.tictactoeshowgrid;

            import android.os.Bundle;
            import java.io.*;
            import android.widget.Toast;
            import android.content.*;

            import java.io.FileInputStream;
            import java.io.FileNotFoundException;
            import java.io.FileOutputStream;
            import java.io.IOException;
            import java.util.Date;

            import android.content.Context;

                public class ImportOBJ {

                protected void onCreate(String filename) {
                    try
                    {
                        FileInputStream fis = openFileInput(filename);
                        BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
                        String line = null, input="";
                        while ((line = reader.readLine()) != null)
                            input += line;
                        reader.close();
                        fis.close();
                        //toast("File successfully loaded.");
                        //return input;
                    }
                    catch (Exception ex)
                    {
                        //toast("Error loading file: " + ex.getLocalizedMessage());
                        //return "";
                    }
                }
            }

I am looking at an example of File I/O for Android. I am wondering why openFileInput is coming up with an error as being an undefined function. I was thinking that maybe I missed an import? If not then there must be some other problem.

Thanks in advance...

Eae
  • 4,191
  • 15
  • 55
  • 92
  • did u got the valid file means "xyz.txt" u write onCreate()..i'm sure this is user defined method – Sam Jul 03 '13 at 04:33

2 Answers2

10

for accessing openFileInput method in non Activity class you will need to pass Activity Context to it by sending Context using parametrized method or using ImportOBJ class constructor as:

protected void onCreate(String filename,Context context) {
   try
     {
         FileInputStream fis = context.openFileInput(filename);  
         //...your code here...      
     }
   catch (Exception ex)
     {

     }
}

and from your Activity pass context as:

ImportOBJ obj_import=new ImportOBJ();
obj_import.onCreate(<File_Name_Here>,Your_Current_Activity_Name.this);
ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
  • @ρяσѕρєяK man please HELP !! http://stackoverflow.com/questions/17421506/how-to-parse-same-name-tag-in-android-xml-dom-parsing – Altair Jul 03 '13 at 14:22
1

If error is :

The method openFileInput(String) is undefined for the type ...

You have to use openFileInput in a Context.For example an Activity is a Context.So if you cahnge your class to this,error must be solve:

public class ImportOBJ extends Activity{
.
.
.

}

You can see What is Context in Android? for more details on Context.

Community
  • 1
  • 1
hasanghaforian
  • 13,858
  • 11
  • 76
  • 167