This is my first time on here, so I’m bit nervous and please forgive me if I don’t seem entirely clear about what I’m asking.
The problem is, Im trying to read in a file from a subfolder in the assets folder, using a method that I’ve created in a separate class. I’ve researched this for a couple of days but I’m unable to find the solution anywhere, so I’ve come here as a last resort. I needed the file reading method to be separate as there are other views/activities that will be utilising exactly the same method and I don’t think it would be wise to keep copying and pasting the same code for each activity. Ok here’s what I’ve done so far:
public class ReadAssets extends Activity {
public void read(Context context, String filepath, int textviewid) {
try {
InputStream input = getAssets().open(filepath);
int size = input.available();
// Read the entire asset into a local byte buffer.
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
// Convert the buffer into a string.
String text = new String(buffer);
// Finally insert the string into the text view.
TextView tv = (TextView) findViewById(textviewid);
tv.setText(text);
} catch (IOException e) {
// Throws an exception if an error is found
throw new RuntimeException(e);
}
}
}
The activity that I would like to place this method in:
public class GeneralSetupActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gettingstarted_layout);
ReadAssets nA = new ReadAssets();
nA.read(this,"gettingstarted/GettingStarted.txt", R.id.displayTextView);
// try {
// InputStream input =getAssets().open("gettingstarted/GettingStarted.txt");
//
// int size = input.available();
//
// // Read the entire asset into a local byte buffer.
// byte[] buffer = new byte[size];
// input.read(buffer);
// input.close();
//
// // Convert the buffer into a string.
// String text = new String(buffer);
//
// // Finally insert the string into the text view.
// TextView tv = (TextView) findViewById(R.id.displayTextView);
// tv.setText(text);
//
// } catch (IOException e) {
// // Throws an exception if an error is found
// throw new RuntimeException(e);
// }
}
}
I’d really appreciate it file someone could point me towards the right direction. And also I hope I’m not taking advantage but I’d like to know how I’d import and display a series of text files, one after another.
Cheers Guys,
Thanks 🙂
If you need this available to all different types of Activity, you should consider putting the method in a superclass so all the children can use it.
Otherwise, if this method is needed by a bunch of unrelated classes, you could put it in a utility class;
then you can call it where needed with