我正在尝试学习如何创建应用程序并在一开始就陷入困境。我阅读了很多关于这个问题的主题,仍然无法找到如何做到这一点。我想我从文本文件中读取了一部分,但不知道如何显示它。有人可以帮帮我吗?感谢。
MainActivity.java
public class MainActivity extends AppCompatActivity {
public void main(String[] args) throws Exception
{
FileReader file = new FileReader("C:/Users/Eothen/AndroidStudioProjects/FutbolBorsasi/app/src/main/res/infobank.txt");
BufferedReader reader = new BufferedReader(file);
String line = reader.readLine();
while (line != null)
{
line = reader.readLine();
System.out.println("line");
}
reader.close();
}
activity_main.xml中
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="@string/nameTextView"
android:id="@+id/nameTextView"
android:layout_below="@+id/ppImageView"
android:layout_centerHorizontal="true"
android:textSize="25sp"
android:layout_marginTop="25dp"
android:background="@drawable/backgroundtextview"
android:gravity="center_vertical|center_horizontal" />
的strings.xml
<string name="nameTextView">DISPLAY HERE</string>
infobank.txt
READ HERE
编辑:此工作
public class MainActivity extends AppCompatActivity {
String line;
TextView view;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AssetManager am = getAssets();
try {
InputStream is = am.open("test.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
line = reader.readLine();
view = (TextView) findViewById(R.id.nameTxt);
view.setText(line);
} catch (Exception e) {
e.printStackTrace();
}
}
答案 0 :(得分:0)
line = reader.readLine();
System.out.println("line");
您应该在TextView中显示它,而不是在控制台中显示它。
像:
TextView view = (TextView) findViewById(R.id.counter);
view.setText(line);
并且System.out.println("line");
将显示“行”,而不是该文件的文字,您必须删除“”。
编辑:不要忘记将R.id.counter
更改为R.id.<id of your textview>
<强> EDIT2:强>
试试这个:
public void main(String[] args) throws Exception
{
FileReader file = new FileReader("C:/Users/Eothen/AndroidStudioProjects/FutbolBorsasi/app/src/main/res/infobank.txt");
BufferedReader reader = new BufferedReader(file);
String line = reader.readLine();
while (line != null)
{
line = reader.readLine();
TextView view = (TextView) findViewById(R.id.nameTextView);
view.setText(line);
}
reader.close();
}
您想如何从仿真器读取C驱动器上的文件? 试试Reading a simple text file
答案 1 :(得分:0)
这里有很多错误。第一个是在android中没有public void main(String[] args)
但是你必须在你的清单中声明你的主要活动是什么,并覆盖onCreate
,onStart
等方法由Activity
类提供。其次,android设备(或android模拟器)的文件系统与你的pc文件系统不同,然后C:/Users/Eothen/AndroidStudioProjects/FutbolBorsasi/app/src/main/res/infobank.txt
是错误的。
我建议你先开始阅读一些教程(网上有很多可用的教程),然后再试一次。