将我的值保存在一个活动中,并将此值显示在不同的活动中

时间:2013-05-12 18:07:59

标签: android

我尝试将密码保存到活动&我想将它恢复到不同的活动,但当我的应用程序启动第二个活动时,它会崩溃。 有人可以帮助我吗?

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);
    }

}

5 个答案:

答案 0 :(得分:4)

我知道在活动之间传递变量的最简单方法如下:

在您的活动中,您将创建一个新的意图:

Intent intent = new Intent(getApplicationContext(), NextActivity.class);
intent.putExtra("nameofvariable","valueofvariable");
startActivity(intent);

从下一个Activity中,您可以通过以下方式检索此值:

Bundle extras = getIntent().getExtras();
if (extras != null) {
    String value = extras.getString("nameofvariable");
}

但是,使用FileInputStream的正确方法是:

FileInputStream in = openFileInput("hello_file.txt");
    InputStreamReader inputStreamReader = new InputStreamReader(in);
    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = bufferedReader.readLine()) != null) {
        sb.append(line);
    }

答案 1 :(得分:2)

如果您想在活动之间共享数据,您可以执行以下操作:

  1. 意图并将更多数据放入Bundle
  2. SharePreferences(即使应用程序关闭并再次重新启动,您也可以访问它)
  3. SqLite数据库(即使应用程序关闭并再次重新启动,您也可以访问它)
  4. 静态类
  5. 这是您使用SharedPrefs的方法 - >

    SharedPreferences pref = getBaseContext().getSharedPreferences(PREFERENCE_NAME, 0); 
    SharedPreferences.Editor editor editor = pref.edit();
    editor.putString("KEY_PASSORD", "Password to Save");
    editor.commit();
    

    如果您想从SharedPrefs检索密码,请执行此操作 - >

    SharedPreferences Pref = getBaseContext().getSharedPreferences(PREFERENCE_NAME, 0);
    String password = pref.getString("KEY_PASSWORD","Default Password");
    

答案 2 :(得分:1)

如果您想在活动之间共享数据,可以使用:

  • 意图并将更多数据放入Bundle
  • Application类中的SharePreferences
  • SQLite数据库
  • 静态变量

答案 3 :(得分:0)

我在模拟器(8级)和三星Galaxy S3(16级)上测试了你的应用程序,它运行正常!

第二项活动的textView是1234。

您测试哪些设备?

你能给我们发一个logcat日志吗?

不要错过在AndroiManifest.xml文件中声明所有活动。

由于

答案 4 :(得分:0)

您可以在第一个活动中使用SharedPreferences并将密码保存到其中:

package com.example.test;

public class FirstActivity extends Activity {
SharedPreferences pref;
SharedPreferences.Editor editor editor;

private final String KEY_PASSWORD = "password";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button button = (Button)findViewById(R.id.button);
    button.setText(finall);
    button.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v) {
            pref  = getSharedPreferences("passwordPref", 0); 
            SharedPreferences.Editor editor editor = pref.edit();
            editor.putString(KEY_PASSWORD ,YourEditBox.getText());
            editor.commit();
            Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
            startActivity(intent);

        }
    });

}

}

在第二个活动中使用它来检索密码:

package com.example.test;

public class SecondActivity extends Activity {
SharedPreferences pref;
SharedPreferences.Editor editor editor;

private final String KEY_PASSWORD = "password";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    pref = getSharedPreferences("passwordPref", 0);
    YourEditText.setText(pref.getString(KEY_PASSWORD,""));
}

}