我需要在应用小部件中读取 txt 文件。
我在名为“NASTAVENI”的外部集活动中创建了 txt:
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.set);
editor=(EditText)findViewById(R.id.editor);
Button btn=(Button)findViewById(R.id.close);
btn.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
phoneNo = editor.getText().toString();
finish();
}
});
}
public void onResume() {
super.onResume();
try {
InputStream in=openFileInput("notes.txt");
if (in!=null) {
InputStreamReader tmp=new InputStreamReader(in);
BufferedReader reader=new BufferedReader(tmp);
String str;
StringBuilder buf=new StringBuilder();
while ((str = reader.readLine()) != null) {
buf.append(str+"\n");
}
in.close();
editor.setText(buf.toString());
}
}
catch (java.io.FileNotFoundException e) {
}
catch (Throwable t) {
Toast
.makeText(this, "Exception: "+t.toString(), 2000)
.show();
}
}
/*BACK**************************************************************************************************************************************/
public void onPause() {
super.onPause();
try {
OutputStreamWriter out=
new OutputStreamWriter(openFileOutput("notes.txt", 0));
out.write(editor.getText().toString());
out.close();
}
catch (Throwable t) {
Toast
.makeText(this, "Exception: "+t.toString(), 2000)
.show();
}
}
}
应用小部件的主要活动名称为“小部件”。我需要在此活动“Widget”中读取外部活动“NASTAVENI”的 txt 文件。Activity Widget 和 NASTAVENI 在同一个包中。
这段代码不好(错误 java.lang.NullPointerException)
try {
InputStream in=openFileInput("notes.txt");
InputStreamReader tmp=new InputStreamReader(in);
BufferedReader reader=new BufferedReader(tmp);
String str;
StringBuilder buf=new StringBuilder();
while ((str = reader.readLine()) != null) {
buf.append(str+"\n");
}
in.close();
editor.setText(buf.toString());
phoneNo = "77";
}
catch (java.io.FileNotFoundException e) {
Toast toast=Toast.makeText(context, "Error FFE!", 1000);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
catch (Throwable t) {
Toast toast=Toast.makeText(context, "Error T!" +t.toString(), 1000);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
对不起我的英语不好