问题描述
我尝试创建一个应用程序,用户可以在其中按下一个按钮(将来这一步应该通过摇动手机来代替)并且应该会出现一个列表中的字符串。我可以按下按钮,然后随机选择此列表中的一个对象并将其放在屏幕上,但是我在从列表中删除使用过的对象时遇到了一些麻烦,我猜是保存和读取我创建的文件在手机上永久保护这些数据(不知道,这对我的使用是否真的有必要?)。
以下是我来自 Activity 的 Java 代码。 顺便说一句,这是我第一次编写应用程序。
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
public class SmallActivity extends AppCompatActivity {
String[] small = {"ab","cd","ef"};
int length = small.length-1;
Random random = new Random();
int rand = random.nextInt(length);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_small);
readFile();
TextView output = (TextView)findViewById(R.id.output);
readFile();
getSupportActionBar().hide();
output.setVisibility(output.INVISIBLE);
}
public void push(View view) {
view.setVisibility(View.GONE);
TextView output = (TextView)findViewById(R.id.output);
output.setVisibility(output.VISIBLE);
output.setText(small[rand]);
delete(small);
}
public void delete(String[] small){
List<String> tmp = new ArrayList<String>();
for(int i = 0; i < small.length; i++){
if(i == rand){
}
else{
tmp.add(small[i]);
}
}
small = tmp.toArray(new String[tmp.size()]);
writeFile();
}
public void writeFile(){
String textToSave = small.getClass().toString();
try{
FileOutputStream fileOutputStream = openFileOutput("small activities.txt",MODE_PRIVATE);
fileOutputStream.write(textToSave.getBytes());
fileOutputStream.close();
}
catch (FileNotFoundException e){
e.printstacktrace();}
catch (IOException e){
e.printstacktrace();
}
}
public void readFile(){
try{
FileInputStream fileInputStream = openFileInput("small activities.txt");
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer stringBuffer = new StringBuffer();
String lines;
while ((lines = bufferedReader.readLine()) != null) {
stringBuffer.append(lines + "\n");
}
}
catch (FileNotFoundException e){
e.printstacktrace();
}
catch (IOException e){
e.printstacktrace();
}
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)