java - 如何在文本文件中简单地写入和读取整数数据?

标签 java android

我的主菜单中有这个应用程序,我想在写入文本文件的 TextView 中显示获得的星星。此外,如果我获得了更多星星,我想读取数据并添加获得的星星并附加到 txt 文件。由于某些原因,我的应用程序崩溃了,我已经被困在这里几个小时了。谁能帮我解决这个问题吗?

这是我的代码:

import android.widget.TextView;

public class MainActivity extends Activity {

  private static TextView txt_stars;
  private static final String FILENAME = "Stars.txt";

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

 
    onButtonClickListener();
    txt_stars = (TextView) findViewById(R.id.txtStars);
    //This is where I should view the number of stars remaining
  }

  public void onButtonClickListener {

    button_next = (Button) findViewById(R.id.btnNext);
    button_next.setOnClickListener(
      new View.OnClickListener() {
      
      @Override
        public void onClick(View v) {
          AlertDialog.Builder alert = new AlertDialog.Builder(context);
          alert.setMessage("You have earned 50 stars");
          alert.setCancelable(false);
          alert.setPositiveButton("next", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
              //Can anyone please help me here?
            //this should compute the data inserted in textfile and the stars earned, and the result should append to the file.
            }
          });
          AlertDialog alertDialog = alert.create();
          alertDialog.show();
        }
      }
    );

  }


}

感谢您的帮助。

最佳答案

您可以编写两个辅助方法来读取和写入。

 private String readStars(String file) {
    BufferedReader reader = null;
    String stars = null;
    StringBuffer buffer = new StringBuffer(); 
    try {
        reader = new BufferedReader(new FileReader(file));
        if(reader != null){
        while((stars = reader.readLine())!= null){buffer.append(stars);};// if you have more lines in your text if not you can simply say reader.readLine()
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return buffers.toString(); // or you can send the length to get the number of stars but you should take care to remove emptylines and empty strings.
}

private String appendStars(String file, String starData) {
    BufferedWriter writer = null;
    String stars = null;
    try {
        writer = new BufferedWriter(new FileWriter(file));
        if(writer != null){
            writer.append(starData);
        }
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return stars;
}

并在对话框和按钮监听器中调用它们并获取数据并将数据附加到文件中。

    SharedPreferences preferences = null;

在 OncreateView 中:

  //This is where I should view the number of stars remaining
    String starsData = readStars("stars.file"); // or you can read it from preference as other said
    /* if you are trying to get it from preferences . here is the sampel*/
    preferences = getSharedPreferences("your preferences key", MODE_PRIVATE); // mode completely depends on you. you can change it as per requirements.
    starsData = preferences.getString("your stars edittext key", ""); // default values can be anything either 1 or empty if string. your choice
    txt_stars.setText(starsData);       

在对话监听器中:

     //Can anyone please help me here?
    //this should compute the data inserted in textfile and the stars earned, and the result should append to the file.

    String newStars = txt_stars.getText().toString();
    //do the stars calculation and depending . If it is a sample app you can simply append the star in the new line to the file and see if it works for you and later you can modify based on the requirements.
    appendStars("stars.txt", newStars);


    // if you want to use the sharedpreferences
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString("your stars edittext key", newStars);
    editor.commit();

关于java - 如何在文本文件中简单地写入和读取整数数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34692265/

相关文章:

Android错误循环 "for"计数

android - fragment 和 Intent 过滤器

java - box2d 接触监听装置顺序

java - ArrayList快速查找自定义对象

java - 如何向 < 添加对象?扩展接口(interface)>?

android - 使用Eclipse的Media Player播放YouTube视频

java - 我可以在 Android 中设置 AlarmManager 的结束时间吗?

java - 从另一个类返回时变量中的值丢失

java - 如何使用斯坦福 CoreNLP 从 TreeAnnotation 中提取未标记/未类型化的依赖树?

java - 对我的 Android 游戏进行逆向工程 + 预防