0

テキスト ビューのテキスト プロパティを動的に設定しようとしています。しかし、アプリを強制的に閉じます。以下のコードの問題は何ですか?

public class DataStorageActivity extends Activity {
    /** Called when the activity is first created. */


    public static final String PREFS_NAME = "MyPrefsFile";



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


        SharedPreferences settings = getSharedPreferences(PREFS_NAME,0);

        SharedPreferences.Editor editor=settings.edit();

        editor.putInt("myValue", 7);

        editor.commit();

        TextView tv=(TextView)findViewById(R.id.textView);

       int value=settings.getInt("myValue", 0);

        tv.setText(value);

    }
}

編集

@agamovによると、上記の問題を修正しました。しかし、文字列型を setText メソッドに渡した後でも、以下のコードで同じ問題が発生しました。ここで何が問題ですか?

public class InternalStorageActivity extends Activity {

    public String fileName="HelloFile";

    public TextView textview;

     @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


        String helloString="Hello";
        byte[] b = null;

        try {
            FileOutputStream fos=openFileOutput(fileName, MODE_PRIVATE);

            fos.write(helloString.getBytes());

            fos.close();

            FileInputStream fis=openFileInput(fileName);
            fis.read(b);
            String input=b.toString();

            textview=(TextView)findViewById(R.id.textView);

            textview.setText(input);

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}
4

1 に答える 1

1

int を TextView に渡しています。これでバグが修正されるはずです:

int value=settings.getInt("myValue", 0);
tv.setText("" + value);
于 2013-03-02T11:19:19.733 に答える