【发布时间】:2020-05-20 12:10:30
【问题描述】:
所以我一直在开发一个应用程序,它会告诉你随机的话题来谈论。 我尝试读取文件并显示文件中包含随机主题的文本。 我的代码在这里:
package com.example.nosir;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import android.util.Log;
import java.util.Random;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final String TAG = MainActivity.class.getSimpleName();
public static final String mPath = "example.txt";
private QuoteBank mQuoteBank;
private List<String> mLines;
Random random = new Random();
TextView text1;
String theTopic;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = findViewById(R.id.button1);
button1.setOnClickListener(this);
text1 = (TextView) findViewById(R.id.text1);
mQuoteBank = new QuoteBank(this);
mLines = mQuoteBank.readLine(mPath);
for (String string : mLines)
Log.d(TAG, string);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
text1.setText(mLines.get(random.nextInt(mLines.size())));
break;
default:
break;
}
}
}
package com.example.nosir;
import android.content.Context;
import android.content.res.AssetManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.ArrayList;
public class QuoteBank {
private Context mContext;
public QuoteBank(Context context) {
this.mContext = context;
}
public List<String> readLine(String path) {
List<String> mLines = new ArrayList<>();
AssetManager am = mContext.getAssets();
try {
InputStream is = am.open(path);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null)
mLines.add(line);
} catch (IOException e) {
e.printStackTrace();
}
return mLines;
}
}
但是当我按下按钮显示随机文本时,我的应用程序只是关闭并且什么都不做。 我在 OnePlus6 上进行测试。 我真的不知道是什么问题。 我希望有人能帮助我。 提前致谢。
【问题讨论】:
-
如果我改变“text1.setText(mLines.get(random.nextInt(mLines.size())));”到“text1.setText(mLines.toString());”它不会关闭应用程序,而只会显示“[]”
-
我建议通过调试器运行应用程序,这样当发生关闭/崩溃时,您可以看到是哪一行导致了故障。从它在按钮上崩溃的事实来看,它最有可能是
text1.setText(mLines.get(random.nextInt(mLines.size())));所以检查 example.txt 是否存在,你可以从你的班级中阅读。 -
close 意味着我认为它崩溃了检查你的 logcat 你会得到原因或发布堆栈跟踪
标签: java android file android-studio testing