I am very new in android, i am learning.
I have created a simple login system, where it will communicate with php. Its working fine,
Right now there is 3 activity,
1st - login
2nd - menu
3rd - view
in login, they have to specify their username, i wish to get the username in view (3rd)
How can i get it? I tried google and read, none of them working for me :(
i am using
final Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
EditText name = (EditText)findViewById(R.id.name);
});
What you're looking for are intent 'extras'. These are extra pieces of information carried from Activity to Activity on the Intent.
There's an example in the source for my application Google Moderator for Android.
Creating an Intent that carries some extra information (here, 'series ID'):
Intent intent = new Intent(activity, TopicActivity.class);
intent.putExtra("seriesId", seriesId);
//...
activity.startActivity(intent);
http://www.google.com/codesearch/p?hl=en#RbTgvHmKhC4/trunk/src/com/google/android/apps/moderator/TopicListEntry.java&l=49
On another Activity, retrieving the value from the same intent (now the launching intent)'s extras:
int seriesId = getIntent().getIntExtra("seriesId", -1);
http://www.google.com/codesearch/p?hl=en#RbTgvHmKhC4/trunk/src/com/google/android/apps/moderator/TopicActivity.java&l=183
In this example, -1 is the value that will be returned if there is no "seriesId" carried with the extra.
You can set the user name to a public, static value so it can be reached from any class within your application.
Or you can pass it around your Activities using the Intent method putExtra(..) http://developer.android.com/reference/android/content/Intent.html
You can get text from an EditText widget using getText() followed by toString(). So your code should be:
final Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
EditText nameWidget = (EditText) findViewById(R.id.name);
String username = nameWidget.getText().toString();
});
Related
Here I have 3 activity and ActivityA contain textView which show username , ActivityB contain only button to redirect ActivityC, ActivityC Contain EditText and save button.
Now i want to change updated text from ActivityC to direct ActivityA when save button clicked without refreshing any Activity than what i have to do? can you please suggest simple way.
I have a same requirement in complex project, i need to save user location at server side using api call and show updated data in ActivityA.
Another way would be to use LocalBroadcastManager.
The code will be as follows.
//ACTIVITY A CODE
TextView username_tv;
String username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
username_tv = (TextView) findViewById(R.id.username_tv);
//Get your username and store it in username
username = getYourUsername();
username_tv.setText(username);
LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
lbm.registerReceiver(receiver, new IntentFilter("USER_NAME_CHANGED_ACTION"));
}
public BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null) {
username = intent.getStringExtra("username");
username_tv.setText(username);
}
}
};
//ACTIVITY C CODE
//ADD this code to your 'SAVE' Button Listener
Intent intent = new Intent("USER_NAME_CHANGED_ACTION");
intent.putExtra("username", editText.getText().toString());
// put your all data using put extra
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
For more information on localBroadcastManager look here.
I do not understand why you need this, but you can do it by saving the value of EditText in ActivityC in SparedPreferences here is an example how can make it. Then you should check in onResume() method of ActivityAif there is saved value in SparedPreferences and if has some get the value and set it to "Username" TextView.
EventBus will solve your problem
http://greenrobot.org/eventbus/
Please how do I link a new activity from my main activity using a clickable text. I have set the text to clickable from my main.xml but I don't know how to call the new activity from my MainActivity.java class. I know I have to use this code "textView.setOnClickListener(new View.OnClickListener());" I found in a similar question, but I don't know how and where to place it on my MainActivity.java class so that it calls a the next activity I named display
Check out Intent. You use these to start new activities or services within your application.
You're correct in that you have to assign an OnClickListener interface to your text, after you made it clickable. In the interface's onClick() method you would need to do something like this.
For example:
#Override
public void onClick(View v) {
// Create the intent which will start your new activity.
Intent newActivityIntent = new Intent(MainActivity.this, NewActivity.class);
// Pass any info you need in the next activity in your
// intent object.
newActivityIntent.putExtra("aString", "some_string_value");
newActivityIntent.putExtra("anInteger", some_integer_value);
// Start the new activity.
startActivity(newActivityIntent);
}
In the next activity, you can retrieve the intent used to start it, so that you'll have access to the data you passed from the first activity, like so:
#Override
public void onCreate(Bundle savedInstanceState) {
// Get the intent that started this activity.
Intent startingIntent = getIntent();
// Retrieve the values.
String aString = startingIntent.getStringExtra("aString");
Integer anInteger = startingIntent.getIntExtra("anInteger", 0); // 2nd param is the default value, should "anInteger" not exist in the bundle.
// Use the values to your hearts content.
}
Hope that helps.
Hi everyone.
I'm new in android and I'm working on an app in which I need to recall the same activity to enter the information of a variable amount of entities (passengers).
I have the following:
btnContinue3.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
for (int i=0; i<Pssngr; i++){
passenger[i] = new
Intent(getApplicationContext(), Pasajeros.class);
startActivity(passenger[i]);
}
}
});
Pssngr is the amount of passsengers or entites that need a unique activity to get their information entered.
The trigger is the button then the activities will be called one by one following an array
I try this code but after clicking on the button the app crashed.
Please someone help me find a way to make this work.
thanks
It crashes because You are trying to start x number of Activities at once.
If You have to run new Activity for each of Passengers best in this scenario will be startActivityForResult
I beliver effect You trying to get is that user clicks on button just once and activities for each passenger will open one after another.
To do it in method onClick You will start only first activity, don't use loop.
You start consequently next activities in onActivitiyResult
In addition to what Gustek mentions above, a better way to approach this would be to have one activity and just pass the different values from the parent (PassengersAvitivty) activity through the intent as below:
final Intent intent = new Intent(PassengersAcitivty.this, PassengersEntityActivity.class);
intent.putExtra("PASSENGER_FIRSTNAME", passenger[i].getName());
intent.putExtra("PASSENGER_LASTNAME", passenger[i].getLastName());
intent.putExtra("PASSENGER_EMAIL", passenger[i].getEmail());
startActivity(intent);
and here is how you can retrieve them on your activity (PassengerEntityActivity)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (extras != null)
{
firstname = extras.getString("PASSENGER_FIRSTNAME");
lastname = extras.getString("PASSENGER_LASTNAME");
email = extras.getString("PASSENGER_EMAIL");
}
else
{
//Log.v("NO VALUE", "OOPS");
}
I can clarify further if needed.
I am currently attempting to pass a string across activities. The string is used to set an image in the second activity. So the user is clicking a button in the first activity and then the appropriate image is loaded in the second activity based upon what was selected. There are three buttons in the first activity all which should send a String value to the next activity.
This is what I have in my first activity:
Button archerButton = (Button) findViewById(R.id.Button_Archer);
archerButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String selection = "archer";
Bundle basket = new Bundle();
basket.putString("key", selection);
Intent i = new Intent(SelectCharacterActivity.this, LevelOneActivity.class);
i.putExtras(basket);
startActivity(i);
finish();
}
});
}
The receiving activity has the following code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.level_one);
ImageView img = (ImageView) findViewById(R.id.Character_Chosen);
Bundle extras = getIntent().getExtras();
String Toon = extras.getString("key");
if(Toon=="archer"){
img.setImageResource(R.drawable.archer);
}
if(Toon=="mage"){
img.setImageResource(R.drawable.mage);
}
if(Toon=="warrior"){
img.setImageResource(R.drawable.warrior);
}
}
I know that the receive if statements section works because if I manually set the value Toon the image will load. So somewhere the information is not being sent or read properly. I followed a tutorial online and but am stumped on this.
issue is Java 101. string equality test is done using the equals method.
Toon.equals("archer");
Extra tip : inverse your test to avoid null pointer exception :
"archer".equals(Toon);
Extra extra tip : considering your cases are mutually exclusive, use if else if to avoid testing all cases.
You are comparing your strings wrong,
Toon=="Anything"
will never be true, you need to use
Toon.equals("Anything")
for it to work.
EDIT:
This is true because "==" will just compare the memory addresses of the Strings, and "Anything" will just have been allocated and definitely won't match Toon. .equals however actually compares the chars in the string.
Also to test things like this try putting in a
Log.i("YourAppName", "Toon value is: " + Toon);
after
String Toon = extras.getString("key");
try to use SharedPreferences, Set it after/with the button-click and get it on 2. Activity OnCreate
If you just want to pass a simple String, you can use the following:
On sending:
Intent i = new Intent(SelectCharacterActivity.this, LevelOneActivity.class);
i.putExtra("key", selection);
startActivity(i);
On receiving:
String selection = getIntent().getStringExtra("key");
If there is no parameter with this key, selectionwill be null.
Try this
Intent i = new Intent(FirstActivity.this, SecondActivity.class);
i.putExtra("email", "lol#hotmail.com");
startActivity(i);
and
Intent i = getIntent();
String myemail = i.getStringExtra("email");
Furthermore, to compare String, use .equals() not ==
This is probably quite basic but I've only needed a use for a feature like this now. I have a button that carries out a calculation when I click on it. The output is a number. I want to put that number into a TextView on a different layout. On it's own page basically.
I can already get what I want on the same page. Just do the whole
TextView.setText();
Can anyone help me put the data onto it's own page? So when I click the button it carries out the calculation AND opens this new page to put the answer on it?
I tried putting the TextView in a new layout file and calling it via a findViewById but that gave me a force close.
Any solutions? Thanks.
EDIT: Here's the code, I'm trying to display the time on another page. See below
public void getWakeUpTime (View v) {
LocalTime localtime = new LocalTime();
LocalTime dt = new LocalTime(localtime.getHourOfDay(), localtime.getMinuteOfHour());
LocalTime twoHoursLater = dt.plusHours(2);
DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm");
Text1.setText("Time: " + twoHoursLater.toString(formatter));
}
Right now it displays on the same page under the TextView Text1.
You can pass integer to next activity using this code:
String num;
Intent i = new Intent(this, NextActivity.class);
i.putExtra("value", num);
startActivity(i);
You can retrieve the data on next activity as shown below:
Intent i = getIntent();
String num = i.getStringExtra("value");
textview.setText("Number is: "+num);
So brother, here you want is that you have calculated a value in 1st page and you want to show it on the 2nd page am I right?
For this brother you need to pass some data(i.e. Bundle) while calling the next activity.
Here's a similar Application that I built few months back. It passes the message created in one activity to another. Hope this works for you.
The following code is from the first activity where message is created and it is bundled and sent to the next activity.
public void yourMethod(View view ){
// Fetching the message to be sent to the next activity.
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
Intent intent = new Intent(this, DisplayMessageActivity.class);
// Remember this constant(or any string you can give). to be used on other activity.
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
And this is what I did on the onCreate Method of the Activity which was called by the previous Activity.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
// save the passed message as string so that it can be displayed anywhere in this activity.
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
Hope My Program give you enough light to your solution. Hope that satisfies you.
Thanks brother.
You need to send the data as an Extra. Starting Another Activity has all the information you need.