我的对象只有在onCreate()中实例化时才有效

时间:2015-05-17 18:09:29

标签: android android-intent

我有一个对象模型,它在第一个活动中创建,并由Intent转移到第二个活动。当在第二个活动中初始化对象时,我只能在onCreate()中使用它,但是当我在另一个方法中使用它时,应用程序会崩溃。

1-Activity创建对象并添加到Intent:

Intent intent = new Intent(ModelCreatorActivity.this, ModelCreatorBluetooth.class);
Model m = new Model(name);
m.setStreamType(Model.StreamType.valueOf(type));
intent.putExtra("Model_new", new Gson().toJson(m));
ModelCreatorActivity.this.startActivity(intent);

第二活动

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_model_creator_bluetooth);

    String jsonMyObject = null;
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        jsonMyObject = extras.getString("Model_new");
    }
    m = new Gson().fromJson(jsonMyObject, Model.class);
    //here normal work
    Log.d("Models", m.getName() );

}

  public void connectToDevice(String address) {
    if (btt != null) {btt = null;
    }

    btt = new BluetoothThread(address, new Handler() {

        @Override
        public void handleMessage(Message message) {
            Context c = getApplicationContext();
            String s = (String) message.obj;
            s = s.replace("\n", "").replace("\r", "");
            if (s.equalsIgnoreCase("CONNECTED"))
            {
                Toast t = Toast.makeText(c, "CON", Toast.LENGTH_LONG);
                t.show();
                //here are crashing
                Log.d("Models", m.getName() );
            }
            else if (s.equals("DISCONNECTED"))
            {
                Toast t = Toast.makeText(c, "DSC", Toast.LENGTH_LONG);
                t.show();
            }
            else if (s.equals("CONNECTION FAILED"))
            {

                t.show();
                btt = null;
            }
        }
    });
  }

感谢您的帮助:)

0 个答案:

没有答案