Android阅读资源取决于所选活动
我正在开发一个包含不同测试的应用程序,每个测试(活动)都需要读取不同的txt文件。我知道这样做,但手动更改。当特定活动正在运行时,如何能够读取正确的txt。例如,对于活动1,我需要阅读1.txt等等。 这是我读TXT的代码Android阅读资源取决于所选活动,android,android-activity,switch-statement,bufferedreader,Android,Android Activity,Switch Statement,Bufferedreader,我正在开发一个包含不同测试的应用程序,每个测试(活动)都需要读取不同的txt文件。我知道这样做,但手动更改。当特定活动正在运行时,如何能够读取正确的txt。例如,对于活动1,我需要阅读1.txt等等。 这是我读TXT的代码 String questionFile = ""; questionFile = "1.txt"; questionCount = 20; Log.i("Question", questionFile + ": " + questionCount); try { I
String questionFile = "";
questionFile = "1.txt";
questionCount = 20;
Log.i("Question", questionFile + ": " + questionCount);
try {
InputStream is = context.getAssets().open(questionFile);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
// Skips lines
for (i = 0; i< questionNumber; i++) {
reader.readLine();
}
question = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
String questionFile=”“;
questionFile=“1.txt”;
问题数=20;
Log.i(“问题”,问题文件+”:“+questionCount);
试一试{
InputStream=context.getAssets().open(问题文件);
BufferedReader reader=新的BufferedReader(新的InputStreamReader(is));
//跳绳
对于(i=0;i
您需要将当前代码放在单独的类中,并根据当前运行的活动创建一个从资产中读取文件的方法:
public class GetFileAssets {
Context context;
public GetFileAssets(Context context){
this.context=context;
}
public String readFilefromAssets(String str_file_id){
String questionFile = "";
questionFile = str_file_id;
questionCount = 20;
//... your code here
return question;
}
}
现在将文件accoding传递给Activity。如Activity 1:
GetFileAssets obj=new GetFileAssets(Activity1.this);
String str=obj.readFilefromAssets("1.txt");
与活动2相同:
GetFileAssets obj=new GetFileAssets(Activity2.this);
String str=obj.readFilefromAssets("2.txt");