パスワードをアクティビティに保存しようとしましたが、別のアクティビティに復元したいのですが、アプリケーションが 2 番目のアクティビティを起動するとクラッシュします。誰かが私を助けることができますか?
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);
}
}