我尝试将我的密码保存到一个活动中,并且我想将其恢复到不同的活动中,但是当我的应用程序启动第二个活动时,它崩溃了。有人可以帮助我吗?
package com.example.test;
public class MainActivity extends Activity {
String finall;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String FILENAME = "hello_file.txt";
String string = "1234";
FileOutputStream fos;
try
{
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
}
catch (FileNotFoundException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
try
{
FileInputStream in = openFileInput("hello_file.txt");
StringBuffer fileContent = new StringBuffer("");
byte[] buffer = new byte[4];
while(in.read(buffer) != -1)
{
fileContent.append(new String(buffer));
}
finall = fileContent.toString();
in.close();
}
catch (FileNotFoundException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
Button button = (Button)findViewById(R.id.button);
button.setText(finall);
button.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
sendGo(v);
}
});
}
public void sendGo(View v)
{
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
}
第一部分工作,因为我可以在同一个活动中读取我保存的文件。但是当我尝试将它读入另一个活动时,它不起作用:
package com.example.test;
public class SecondActivity extends Activity {
String finall="";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
// Show the Up button in the action bar.
setupActionBar();
try
{
FileInputStream in = openFileInput("hello_file.txt");
StringBuffer fileContent = new StringBuffer("");
byte[] buffer = new byte[4];
while(in.read(buffer) != -1)
{
fileContent.append(new String(buffer));
}
finall = fileContent.toString();
in.close();
}
catch (FileNotFoundException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
TextView text = (TextView)findViewById(R.id.mehmet);
text.setText(finall);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}