如何将对象从一个活动转移到另一个活动?

时间:2017-04-14 22:32:33

标签: android appcompatactivity

我试图修改消息传递应用程序,我有两个单独的活动。我有Connect活动和Client活动。我也为客户提供课程。客户端用于Connect和Client活动,但我不知道如何将ConnectActivity中使用的Client对象传送到ClientActivity。

我的ConnectActivity:

public class ConnectActivity extends AppCompatActivity {

    private Client client;

    private EditText txtServerAddress;

    private EditText txtPortNumber;

    private EditText txtUsername;

    private TextView lblErrors;

    public ConnectActivity(){}

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_connect);

        final EditText txtServerAddress = (EditText) findViewById(R.id.edit_text_server_address);
        this.txtServerAddress = txtServerAddress;

        final EditText txtPortNumber = (EditText) findViewById(R.id.edit_text_port_number);
        this.txtPortNumber = txtPortNumber;

        final EditText txtUsername = (EditText) findViewById(R.id.edit_text_username);
        this.txtUsername = txtUsername;

        final TextView lblErrors = (TextView) findViewById(R.id.text_view_errors);
        this.lblErrors = lblErrors;

        Button btnLogIn = (Button) findViewById(R.id.button_log_in);
        btnLogIn.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                String username = txtUsername.getText().toString().trim();
                if(username.length() == 0)
                    return;

                String portNumber = txtPortNumber.getText().toString().trim();
                if(portNumber.length() == 0)
                    return;

                String serverAddress = txtServerAddress.getText().toString().trim();
                if(serverAddress.length() == 0)
                    return;

                int port;

                try
                {
                    port = Integer.parseInt(portNumber);
                }
                catch(Exception en)
                {
                    return;
                }

                client = new Client(serverAddress, port, username, new ClientActivity(), ConnectActivity.this);


                if(!client.start())
                    return;

                Intent intent = new Intent(ConnectActivity.this, ClientActivity.class);
                startActivity(intent);
            }
        });

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }

    public void append(String str)
    {
        lblErrors.setText(str);
    }
}

我的ClientActivity:

public class ClientActivity extends AppCompatActivity {

    // for I/O
    private Client client;

    private ListView lstMessages;

    private EditText txtMessage;

    private Button btnSend;

    private ArrayList<ChatMessage> messages;

    private ArrayAdapter<ChatMessage> messageAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_client);

        final ListView lstMessages = (ListView) findViewById(R.id.list_messages);

        final EditText txtMessage = (EditText) findViewById(R.id.edit_text_message);

        final Button btnSend = (Button) findViewById(R.id.button_send);
        btnSend.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                String message = txtMessage.getText().toString();
                txtMessage.setText("");

                client.sendMessage(new ChatMessage(ChatMessage.MESSAGE, message));
            }
        });

        messages = new ArrayList<>();
        messageAdapter = new ArrayAdapter<ChatMessage>(ClientActivity.this, R.layout.chat_message, messages);
        lstMessages.setAdapter(messageAdapter);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }

    public void connectionFailed()
    {
        Intent intent = new Intent(this, ConnectActivity.class);
        startActivity(intent);
    }

    public void display(String msg)
    {
        messageAdapter.add(new ChatMessage(ChatMessage.ERROR, msg));
    }

    public void append(String str)
    {
        messageAdapter.add(new ChatMessage(ChatMessage.MESSAGE, str));
    }

}

4 个答案:

答案 0 :(得分:2)

您可以使用Parcelable将对象从一个Activity传递到另一个。

通过ConnectActivity.java btnLogIn onClick方法,parcel Client对象:

// Bundle
Bundle bundle = new Bundle();
bundle.putParcelable("CLIENT", client);

// Intent
Intent intent = new Intent(ConnectActivity.this, ClientActivity.class);
intent.putExtras(bundle);

startActivity(intent);

ClientActivity.java onCreate()方法中,获取Client对象:

// Get data from Intent
Bundle bundle = getIntent().getExtras();

if(bundle != null)
{
    Client client = bundle.getParcelable("CLIENT");
}

仅供参考,确保您的Client班级实施Parcelable

希望这会有所帮助〜

答案 1 :(得分:1)

使您的Client类实现Parcelable,然后使用

传递Intent中的Client对象
Bundle bundle = new Bundle(); 
bundle.putParcelable("client", client); 
intent.putExtra(bundle); 
startActivity(intent);

Here是实现Parcelable的示例代码。

答案 2 :(得分:1)

您可以在多个活动之间共享数据:

  1. 如果数据应该是永久性的,请将其存储在数据库,平面文件或SharedPreferences中。每个活动都直接从永久存储中访问数据。

  2. 如果数据不应永久存储,请将您的Client类设为Parcelable并将其传递给Intent。其他人已经对此进行了描述,因此我不会详细介绍。

答案 3 :(得分:-2)

您可以通过在B类中创建A类实例并传递任何您想要的内容

来轻松完成