「グローバル」というクラスが 1 つと、他に 2 つのアクティビティがあります。各アクティビティで、"textfile" というテキスト ファイルの最初の行を読み取るために、Global クラスのインスタンスを作成したいと考えています。なぜかうまくいかない
グローバル クラスのコードは次のとおりです (ファイル Global.java 内)。
import android.app.Activity;
public class Global extends Activity {
public String line;
public Global() {
InputStream file = getResources().openRawResource(R.raw.textfile);
BufferedReader input = new BufferedReader(new InputStreamReader(file));
try {
line = input.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
}
クラス Global のインスタンスを持ち、「textfile」の最初の行を表示する「HelloWorld」(HelloWorld.java ファイル内) というアクティビティのコードを次に示します。
public class HelloWorld extends Activity{
Global gb;
TextView myTV;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.helloworld);
gb=new Global();
myTV = (TextView) findViewById(R.id.textView1);
myTV.setText("First line is: "+gb.line);
}
}