开发者

Used BufferedReader...Why this code doesn't work at android? It works in Java

开发者 https://www.devze.com 2023-02-16 01:26 出处:网络
I wanted to set a array and input a word from txt file. (stage.txt) It works in Java, but not in android...

I wanted to set a array and input a word from txt file. (stage.txt) It works in Java, but not in android... When I use (System.out.println(stage[0][1]), the console showed String value. But in Android, when I use

TextView show = new TextView; 
show= (TextView)findViewById(R.id.question); 
show.setText(stage[0][1]);

The TextView showed nothing... what's wrong?... please help...

String[][] stage = new String[2][3];
BufferedRea开发者_运维百科der in = new BufferedReader(new FileReader("stage.txt"));
for(int i=0; i<2;i++)
{
    for(int j=0; j<3; j++)
    {
        stage[i][j]=in.readLine();
    }
}

in.close();


Did you add the TextView to the Layout you're using? Or did you define the TextView in the layout XML-File? Then your code TextView show = new TextView; is wrong.

TextView show = new TextView; should be TextView show = new TextView(this); (in an Activity).

Could you provide the full Code before? What errors do you get?

UPDATE: I'm wondering if your file is on your SD Card (because of that path). You can access the SD Card via Environment.getExternalStorageDirectory().getAbsolutePath() to get its root path.

For your projects, change that line to:

BufferedReader br = new BufferedReader(new InputStreamReader(
                openFileInput("stage.txt")));

Full Source:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    String[][] stage = new String[2][3];
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(
                openFileInput("stage.txt")));
        for(int i=0; i<2;i++)
        {
            for(int j=0; j<3; j++)
            {
                stage[i][j]=br.readLine();
            }
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    TextView question = (TextView) findViewById(R.id.question);
    question.setText(stage[0][1]); 
}


//Assuming the 2d array is correctly filled //if not try putting the txt file in your asset folder and use getAssets()

but anyway try doing it this way, see if it helps.

Handler handler = new Handler();
handler.post(new Runnable()
{
    public void run()
    {
        question.setText(stage[0][1]);
    }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消