-2

我试图通过读取文件在 EditText 中设置文本,但应用程序每次都会关闭。有人能说出这段代码有什么问题吗?

package com.example;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.widget.*;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;


public class EditNoteActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        String FILENAME = "note_file";
        EditText text = (EditText) findViewById(R.id.editText1);
        byte[] buffer = new byte[100];


        super.onCreate(savedInstanceState);
        setContentView(R.layout.editnote);

        //Intent intent = getIntent();

        FileInputStream fos = null;
        try {
            fos = openFileInput(FILENAME);
        } catch (FileNotFoundException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        assert fos != null;
        try {
            fos.read(buffer, 0, 10);
            String str = buffer.toString();
            text.setTextSize(48);
            text.setText(str);
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }
    public void onClickSave(View theButton) {
        //Intent intent = new Intent(this, MyActivity.class);
        //startActivity(intent);
        String FILENAME = "note_file";

        EditText text = (EditText) findViewById(R.id.editText1);


        FileOutputStream fos = null;
        try {
            fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
        } catch (FileNotFoundException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        assert fos != null;
        try {
            fos.write(text.getText().toString().getBytes());
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        finish();
    }
    public void onClickBack(View theButton) {
        //Intent intent = new Intent(this, MyActivity.class);
        //startActivity(intent);
        finish();
    }
}

我试图编辑它以删除不相关的代码,但出现错误,“您的帖子没有太多上下文来解释代码部分;请更清楚地解释您的场景。”。不幸的是,没有多少,无论如何这个问题已经得到了回答。

4

2 回答 2

0

您在设置内容视图之前初始化 EditText(文本),以便在通过 id 查找编辑文本时 EditText 对象为空,这就是应用程序崩溃的原因。

修改你的代码如下

super.onCreate(savedInstanceState);
setContentView(R.layout.editnote);

String FILENAME = "note_file";
EditText text = (EditText) findViewById(R.id.editText1);
byte[] buffer = new byte[100];

仅供参考:在提问时,也发布错误日志,然后只有您才能获得快速和正确的答案。

更新

参考: 从 Eclipse 获取错误日志

于 2012-10-06T06:05:31.990 回答
0

for converting byte array into string byte[] bytes = {...} String str = new String(bytes, "UTF8"); // for UTF8 encoding

this is the issue.

于 2012-10-06T06:08:38.443 回答