我正在尝试从Android项目中的assets文件夹中读取文件,但无法使其正常工作。我正在尝试这样的事情:
public class MainActivity extends AppCompatActivity {
TextView fileContentTextView;
StringBuilder stringBuilder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fileContentTextView = findViewById(R.id.file_content_textview);
stringBuilder = new StringBuilder();
AsyncTask.execute(new Runnable() {
@Override
public void run() {
AssetManager assetManager = getBaseContext().getAssets();
try {
InputStream inputStream = assetManager.open("cos.txt");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String str;
str = bufferedReader.readLine();
stringBuilder.append(str);
} catch (IOException e) {
e.printStackTrace();
}
}
});
Log.d("ECG", stringBuilder.toString());
String textToShow = stringBuilder.toString();
fileContentTextView.setText(textToShow);
}
}
但是在日志或尝试设置setText时没有任何显示。不知道我在做什么错。
谢谢。
答案 0 :(得分:0)
我不确定为什么需要使用AsyncTask.execute()。正如CommonsWare的注释所解释的那样,它在后台线程(与主UI线程分开)中执行。因此,stringbuilder.append(str)稍后被调用,而Log.d("ECG", stringBuilder.toString()); String textToShow = stringBuilder.toString(); fileContentTextView.setText(textToShow);
被更快地调用。
因此,有两种方法可以纠正此问题:
public class MainActivity extends AppCompatActivity {
TextView fileContentTextView;
StringBuilder stringBuilder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fileContentTextView = findViewById(R.id.file_content_textview);
stringBuilder = new StringBuilder();
AssetManager assetManager = getBaseContext().getAssets();
try {
InputStream inputStream = assetManager.open("cos.txt");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String str;
str = bufferedReader.readLine();
stringBuilder.append(str);
} catch (IOException e) {
e.printStackTrace();
}
Log.d("ECG", stringBuilder.toString());
String textToShow = stringBuilder.toString();
fileContentTextView.setText(textToShow);
}
}
public class MainActivity extends AppCompatActivity {
TextView fileContentTextView;
StringBuilder stringBuilder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fileContentTextView = findViewById(R.id.file_content_textview);
stringBuilder = new StringBuilder();
AsyncTask.execute(new Runnable() {
@Override
public void run() {
AssetManager assetManager = getBaseContext().getAssets();
try {
InputStream inputStream = assetManager.open("cos.txt");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String str;
str = bufferedReader.readLine();
stringBuilder.append(str);
Log.d("ECG", stringBuilder.toString());
String textToShow = stringBuilder.toString();
fileContentTextView.setText(textToShow);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
我都测试过,他们都为我工作。