I'm trying to right a messaging application, and I have two separate activities. I have the Connect activity, and the Client activity. I also have a class for the client. The client is used in both the Connect and Client activities, but I don't know how to carry the Client object used in the ConnectActivity to the ClientActivity.
My 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);
}
}
My 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));
}
}
You can use Parcelable to pass an object from one Activity to another.
From your ConnectActivity.java btnLogIn onClick method , parcel Client object:
// Bundle
Bundle bundle = new Bundle();
bundle.putParcelable("CLIENT", client);
// Intent
Intent intent = new Intent(ConnectActivity.this, ClientActivity.class);
intent.putExtras(bundle);
startActivity(intent);
In your ClientActivity.java onCreate() method, get Client object:
// Get data from Intent
Bundle bundle = getIntent().getExtras();
if(bundle != null)
{
Client client = bundle.getParcelable("CLIENT");
}
FYI, Make sure your Client class implement Parcelable.
Hope this will help~
You have several options for sharing data between activities:
If the data should be permanent, store it in a database, flat file, or SharedPreferences. Each activity accesses the data directly from the permanent storage.
If the data should not be stored permanently, make your Client class Parcelable and pass it with an Intent. Others have already described this, so I will not go into more details.
Make your Client class implement Parcelable then pass the Client object in the Intent using
Bundle bundle = new Bundle();
bundle.putParcelable("client", client);
intent.putExtra(bundle);
startActivity(intent);
Here is a sample code to implement Parcelable.
You can easly do it by create an instance of Class A in Class B and pass anything you want
Related
I'm french so sorry for my bad english.
I need to update on my second activity my TextView with a EditText of my first Activity. But I don't how to do.
That is my code on First Activity:
public class MainActivity extends AppCompatActivity {
private TextView mGreetingTextView;
private EditText mLoginEditText,mEmailEditText,mPasswordEditText;
private Button mLoginButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGreetingTextView = findViewById(R.id.main_textview_info);
mLoginEditText = findViewById(R.id.main_edittext_login);
mEmailEditText = findViewById(R.id.main_edittext_email);
mPasswordEditText = findViewById(R.id.main_edittext_password);
mLoginButton = findViewById(R.id.main_button_log);
mLoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validateLogin();
}
String login = mLoginEditText.getText().toString();
});
}
private void validateLogin(){
if (mEmailEditText.getText().toString().equals("admin#admin.com") &&
mPasswordEditText.getText().toString().equals("admin")) {
Toast.makeText(getApplicationContext(), "Login successful",Toast.LENGTH_SHORT).show();
callHome();
} else {
Toast.makeText(getApplicationContext(), "Wrong login",Toast.LENGTH_SHORT).show();
}
}
public void callHome(){
Intent i = new Intent(getApplicationContext(),HomeActivity.class);
i.putExtra("mLoginText", mLoginEditText.getText());
startActivity(i);
}
But I search a same topic who has the same problem and I don't find.
Apologize for my bad level on Android but I'm student on Android. This is my first topic on StackOverFlow ^^
You are calling mLoginEditText.getText() and that returns Editable. You will need to call mLoginEditText.getText().toString() and that will be a String.
You can update your second activity (HomeActivity) like this
public class HomeActivity extends AppCompatActivity {
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
textView = findViewById(R.id.textView);
// get the text from main activity
Intent intent = getIntent();
String text = intent.getStringExtra("mLoginText");
textView.setText(text);
}}
I found a result :)
MainActivity:
public class MainActivity extends Activity {
public final static String LOGIN_DATA = "mLoginText";
private EditText mLoginEditText,mEmailEditText,mPasswordEditText;
private Button mLoginButton;
private boolean isValid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLoginEditText = findViewById(R.id.main_edittext_login);
mEmailEditText = findViewById(R.id.main_edittext_email);
mPasswordEditText = findViewById(R.id.main_edittext_password);
mLoginButton = findViewById(R.id.main_button_log);
mLoginButton.setOnClickListener(v -> {
isValid = validateLogin();
if (isValid){
callHome();
}
});
}
private boolean validateLogin(){
if (mEmailEditText.getText().toString().equals("admin#admin.com") &&
mPasswordEditText.getText().toString().equals("admin")) {
Toast.makeText(getApplicationContext(), "Login successful",Toast.LENGTH_SHORT).show();
return true;
} else {
Toast.makeText(getApplicationContext(), "Wrong login",Toast.LENGTH_SHORT).show();
return false;
}
}
public void callHome(){
Intent i = new Intent(MainActivity.this,HomeActivity.class);
i.putExtra(LOGIN_DATA, mLoginEditText.getText().toString());
startActivity(i);
}
}
HomeActvity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mHelloText = findViewById(R.id.home_textview_hello);
Intent intent = getIntent();
String login = intent.getStringExtra(MainActivity.LOGIN_DATA);
mHelloText.setText(login);
With that, the login name of the first activity is in the second activity :)
public class MainActivity extends Activity
{
public static String EXTRA_MESSAGE;
private Intent ceec;
private EditText cc;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);}
public void sendMessage(View view)
{
ceec = new Intent(this, ToActivity.class);
cc = (EditText) findViewById(R.id.edit_message);
String message = cc.getText().toString();
ceec.putExtra(EXTRA_MESSAGE, message);
startActivity(ceec);
}}
And
public class ToActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setText(message);
textView.setTextColor(Color.rgb(5,8,100));
if( message == "hi"){
textView.setTextSize(80);
}
// Set the text view as the activity layout
setContentView(textView);
}}
[ if( message == "hi"){
textView.setTextSize(80);
} ]
It didn't work why? And how to fix it and thank you
Instead of
message == "hi"
You should do:
message.equal("hi")
Never compare Strings with ==, check out this question to understand why.
Use .equals() method as,
if(message.equals("hi")){
textView.setTextSize(80);
}
else
{
// do your else stuff
}
this should work.
Can someone help me? How do I open a new activity after passing basic login argument, here's my code and I don't know what's going, I get an error:
public class MainActivity extends AppCompatActivity {
EditText usern = (EditText)findViewById(R.id.user_name);
String user_name = usern.getText().toString();
EditText passw = (EditText)findViewById(R.id.password);
String pass_word = passw.getText().toString();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/** Called when the user clicks the Send button */
public void nextPage(View view) {
// Do something in response to button
if (user_name.equals("sheldonmad") && pass_word.equals("password")) {
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
}
}
#Sheldon Madison : Try this way . Need proper Initialization of Global or local variables .
Please read Official Documents
http://developer.android.com/intl/es/index.html
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/** Called when the user clicks the Send button */
public void nextPage(View view) {
EditText usern = (EditText)findViewById(R.id.user_name);
String user_name = usern.getText().toString();
EditText passw = (EditText)findViewById(R.id.password);
String pass_word = passw.getText().toString();
// Do something in response to button
if (user_name.equals("sheldonmad") && pass_word.equals("password")) {
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
}
}
Try
public class MainActivity extends AppCompatActivity {
EditText usern,passw;
String user_name,pass_word;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usern = (EditText)findViewById(R.id.user_name);
passw = (EditText)findViewById(R.id.password);
}
/** Called when the user clicks the Send button */
public void nextPage(View view) {
user_name = usern.getText().toString();
pass_word = passw.getText().toString();
// Do something in response to button
if (user_name.equals("sheldonmad") && pass_word.equals("password")) {
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
}
}
I have two major classes in my project. The first is for creating the connection between the client and the server. The second is for switching between activities.
first:
public class MyActivity extends Activity{
private ListView mList;
private ArrayList<String> arrayList;
private MyCustomAdapter mAdapter;
public TCPClient mTcpClient;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
boolean flag = getIntent().getBooleanExtra("flag",false);
arrayList = new ArrayList<String>();
final EditText editText = (EditText) findViewById(R.id.editText);
Button send = (Button)findViewById(R.id.send_button);
Button menu = (Button)findViewById(R.id.button1);
if (flag == true)
{
//relate the listView from java to the one created in xml
mList = (ListView)findViewById(R.id.list);
mAdapter = new MyCustomAdapter(this, arrayList);
mList.setAdapter(mAdapter);
new connectTask().execute("");
Intent myIntent = new Intent(MyActivity.this,Menu.class);
startActivity(myIntent);
}
send.setOnClickListener(new View.OnClickListener() {
// #Override
public void onClick(View view) {
String message = editText.getText().toString();
//clean the listView to 1 item
if (message.equals("clean"))
{
arrayList.removeAll(arrayList);
mList.removeAllViewsInLayout();
}
//add the text in the arrayList
arrayList.add("c: " + message);
//sends the message to the server
if (mTcpClient != null) {
mTcpClient.sendMessage(message);
}
//refresh the list
mAdapter.notifyDataSetChanged();
editText.setText("");
}
});
//change Activity to live screen mode (live)
menu.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent myIntent = new Intent(MyActivity.this, Menu.class);
startActivity(myIntent);
}
});
}
public class connectTask extends AsyncTask<String,String,TCPClient> {
#Override
protected TCPClient doInBackground(String... message) {
//we create a TCPClient object and
mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
// #Override
//print the message as an Item
public void messageReceived(String message) {
//this method calls the onProgressUpdate
publishProgress(message);
}
});
mTcpClient.run();
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
//in the arrayList we add the messaged received from server
arrayList.add(values[0]);
// notify the adapter that the data set has changed. This means that new message received
// from server was added to the list
mAdapter.notifyDataSetChanged();
}
}
}
the object TCPClient mTcpClient is the major factor in my app. I use it communicate with the server. In addition, even if I switch between activities it is still running properly so I still get info from server even though I am not in that activity.
second:
public class Menu extends Activity
{
public MyActivity myActivity;
public TCPClient mtcp;
protected void onCreate(Bundle savedInstanceState, MyActivity myActivity)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
ImageView action = (ImageView) findViewById(R.id.imageView1);
action.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event)
{
// here I would like to use mTcpClient object mentioned in the first class
return false;
}
});
}
Basically what I need is a help on how to create in the second class reference to the object mTcpClient that is described in the first class.
You are doing it wrong. If you want to use TcpClient class regardless of context it should NOT be related to first Activity. What you should do is to use singleton pattern:
class TcpClient {
protected static TcpClient mInstance = null;
public TcpClient() {
// your init code...
}
public static TcpClient getInstance() {
if( mInstance == null ) {
mInstance = new TcpClient();
}
return mInstance;
}
...
}
and then, whenever you want to use TcpClient you just do:
TcpClient client = TcpClient.getInstance();
I am trying to pull in a string from one activity to another but every time I try to open the one activity I get a forceclose on .getString.
Logcat Error
10-26 10:36:45.444: ERROR/AndroidRuntime(15112): at http.www.hotapp.com.timeandlocation.email.EmailSettings.onCreate(ThisActivity.java:29)
Activity Calling the string
public class ThisActivity extends Activity{
private TextView reciever;
private String rec;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.elayout);
reciever = (TextView) findViewById (R.id.Reciver);
rec =
getIntent()
.getExtras()
.getString
("send");
reciever.setText(rec);
}
Activity with the string
public class OtherActivity extends Activity{
private EditText sendto;
private Button save;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.emailactivity);
sendto = (EditText) findViewById(R.id.sendto);
save = (Button) findViewById(R.id.Save);
save.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Intent intent = new Intent (EmailActivity.this,EmailSettings.class);
intent.putExtra("send", sendto.getText().toString());
startActivity(intent);
}
});
}
}
Thanks for the help.
try using getIntent().getStringExtra("send");
If you want to check if the extra is there use:
getIntent().hasExtra("send");
Try this:
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
rec = extras.getString("send");
}
try this by eliminating NULL EXCEPTION from getString() function