setting textview to the string passed from another activity - java

I have an edittext in first activity (apples.java). User can write anything using edittext which is passed as a string to second activity (Bacon.java) on clicking a button. Second activity has a textview written Bacon. When a string is passed from first activity, Bacon is replaced with the passed string/text.
What is happening : When nothing is written using editText and button is clicked to go to second activity, Bacon disappears.
My requirment is that if nothing is passed using EditText and only button is clicked, Bacon should not get replaced.If something is passed, it should replace Bacon.
apples.java:
Intent i = new Intent(apples.this,Bacon.class);
final EditText applesInput = (EditText) findViewById(R.id.applesInput);
String userMessage = applesInput.getText().toString();
i.putExtra("applesMessage",userMessage);
startActivity(i);
Bacon.java
final TextView baconText = (TextView) findViewById(R.id.baconText);
Bundle applesData = getIntent().getExtras();
if(applesData==null){
Toast.makeText(Bacon.this, "Love u", Toast.LENGTH_SHORT).show();
return;
}
String applesMessage = applesData.getString("applesMessage");
baconText.setText(applesMessage);
This is first activity
This is second activity

Do this:
if (!TextUtils.isEmpty(applesMessage))
baconText.setText(applesMessage);

In apples.java write if(applesInput.getText().toString().equals(""); { i.putExtra("applesMessage",userMessage);} just add this..

your problem is that Bundle is not null, so the condition is never satisfied.no string is set does not mean that your bundle is Null
change it to
final TextView baconText = (TextView) findViewById(R.id.baconText);
Bundle applesData = getIntent().getExtras();
if(applesData!=null){
String applesMessage =applesData.getStrng("applesMessage")
if(applesMessage ==null ||applesMessage .trim().equals("")){ //trim to delete spaces
Toast.makeText(Bacon.this, "Love u", Toast.LENGTH_SHORT)
.show();
return;
}
baconText.setText(applesMessage);
}
}

Related

How to pass strings in multiple activities

I want to pass the string from activity to other activities.
For example, tell that I have 5 activities I get a text from the second to the third to the forth to the fifth but when I click a button to go to the third the text is not saved how can I save the string when I pass it?
i try to pass the text that i get from second activity to all the others with Intent:
//While on MainActivity
Intent Second = new Intent(MainActivity.this, SecondActivity.class);
startActivity(Second);
//While on SecondActivity
Intent Third = new Intent(SecondActivity.this, ThirdActivity.class);
Third.putExtra("Third", String);
startActivity(Third);
//While on ThirdActivity
TextView String;
String = findViewByID(R.id.TextView1);
String.setText(string);
String string = getIntent().getStringExtra("Third");
Intent Forth = new Intent(ThirdActivity.this, ForthActivity.class);
Forth.putExtra("Forth", string);
startActivity(Forth);
And i passing strings like that until Activity 5 that has a button that goes to the third and the textview text is not saved
I expected when I click the button from activity 5 that goes to the third activity the text view on third activity to be the text from the second activity that I pass it.
Forward all Extras
You can "forward" all extras using putExtras(intent):
Intent third = new Intent(this, ThirdActivity.class);
third.putExtras(getIntent());
third.putExtra("THIRD", myString);
This will maintain the same key at every step, so if you backtrack (Activity 5 => Activity 3) you can still extract the relevant values for that activity.
Bonus: Use constants to avoid typos
Since your extras might be read in multiple Activities, I would define constants in the final Activity in your flow (I assume a summary or confirmation activity):
public class LastActivity extends AppCompatActivity {
public static final String EXTRA_NAME = "EXTRA_NAME"
public static final String EXTRA_EMAIL = "EXTRA_EMAIL"
public static final String EXTRA_BOOKING_ID = "EXTRA_BOOKING_ID"
// rest of class
}
Then you don't risk typos when you putExtra or getXxxExtra:
String name = intent.getStringExtra(LastActivity.EXTRA_NAME);

Having Trouble Passing And Recieving Data From My Intent

I'm trying to make a pretty simple app to help my girlfriend feel safer.
Im really bad at this, and a little help would go a long way. I've been trying to work with intents, and I really feel as if I'm super close to the solution at hand, I just need a little help.
So, the opening page is supposed to wait until you have data in your shared Preferences and then it will act on it.
The second page is supposed to take some data from EditTexts and store it in your intent. For some reason though, my data is not being stored, and when I pull something from the intent it is "".
CLASS 1:
public void ActivateAlarm(View view){
Bundle myBundle = getIntent().getExtras();
if(myBundle == null){
Log.i("The bundle is empty!", "Smashing success!");
}
else{
SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.jackson.distressalarm", Context.MODE_PRIVATE);
String NumberToCall = sharedPreferences.getString("CallNumber", "");
String TextOne = sharedPreferences.getString("1Text", "");
String TextTwo = sharedPreferences.getString("2Text", "");
String TextThree = sharedPreferences.getString("3Text", "");
Button myButton = (Button) findViewById(R.id.button);
myButton.setText(TextOne);
Log.i("MY NUMBER TO CALL", NumberToCall);
/*Take in the data from the settings. Check it for consistency.
1)Are the numbers empty?
2)Is the number 911 or a 7 digit number?
3)Do they have a passcode?
4)Is the number real? No philisophical BS
*/
}
}
CLASS 2:
public void GoToAlarm(View view){
EditText NumberToCall = (EditText) findViewById(R.id.callNumber);
EditText text1 = (EditText) findViewById(R.id.textNumOne);
EditText text2 = (EditText) findViewById(R.id.textNumTwo);
EditText text3 = (EditText) findViewById(R.id.textNumThree);
Intent intent = new Intent(this, AlarmActive.class);
intent.putExtra("callNumber", NumberToCall.getText().toString());
intent.putExtra("1Text", text1.getText().toString());
intent.putExtra("2Text", text2.getText().toString());
intent.putExtra("3Text", text3.getText().toString());
startActivity(intent);
}
I think the problem is coming from a bit of a mix-up between Intents and SharedPreferences.
An Intent is a way to pass data from one activity to another. You're passing data correctly in Class 2, but you're not retrieving it in Class 1. Here's how you can do that:
String NumberToCall = intent.getStringExtra("CallNumber");
String TextOne = intent.getStringExtra("1Text");
String TextTwo = intent.getStringExtra("2Text");
String TextThree = intent.getStringExtra("3Text");
SharedPreferences are a way to save user data. If you want to save data in addition to passing it between activities, you'll need to add it to SharedPreferences with the following code:
SharedPreferences preferences = this.getSharedPreferences("com.example.jackson.distressalarm", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("callNumber", NumberToCall.getText().toString());
editor.putString("1Text", text1.getText().toString());
editor.putString("2Text", text2.getText().toString());
editor.putString("3Text", text3.getText().toString());
editor.apply();
You can retrieve the values with the code you were using in Class 1.

Transfer textview data between activities?

I'm currently making an app that has edittext and 2 buttons, everytime I write something in to edittext and then press button1, a new textview is added. This is the code:
public void novVnos (View v){
EditText eText = (EditText) findViewById(R.id.editText1);
LinearLayout mLayout = (LinearLayout) findViewById(R.id.linearLayout);
mLayout.addView(createNewTextView(eText.getText().toString()));
}
private TextView createNewTextView (String text){
final LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
final TextView newTextView = new TextView(this);
newTextView.setLayoutParams(lparams);
newTextView.setText(text);
return newTextView;
}
Basically what I'm doing is adding new "players" and once I've added them all I want to press button2. Button2 opens a new activity and the new activity should read all the textviews that I've added in the previous activity.
What I would do is create a "Player" class and make a static ArrayList<String> players inside your Player.java class. Every time you call createNewTextView(textView) add whatever variable text is to the players ArrayList.
In your next Activity you just call Player.players.get(index) or whatever ArrayList function you need to do whatever work you want with it in the next class. You also could create this ArrayList in your current Activity and pass it as an extra in the Intent but I think creating a separate class for the players would be easiest.
Your ArrayList obviously doesn't need to hold Strings. It could hold whatever you want including a Player object.
ArrayList Docs
this is an example :
in the first activity :
Button search = (Button) findViewById(R.id.Button02);
search.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, result.class);
Bundle b = new Bundle();
EditText searchtext = (EditText) findViewById(R.id.searchtext);
b.putString("searchtext", searchtext.getText().toString());
//Add the set of extended data to the intent and start it
intent.putExtras(b);
startActivityForResult(intent,RESULT_ACTIVITY);
}
});
and in the second activity at onCreat :
Bundle b = getIntent().getExtras();
String searchtext = b.getString("searchtext"); //here you get data then use it as you want
//here I use it to show data in another edittext
EditText etSearch = (EditText) findViewById(R.id.searchtext2);
etSearch.setText(searchtext);
Implementing a "Player" class will be a way to go. In that regard, you don't have to worry about transferring data between two activities. You can use Singleton method to make sure your class has been defined only once. You need to make sure it gets defined only once because let's say if you user closes application or kills app, then when he opens app again, it would create another class, so all of your data will be lost.

pass 2 values from one to another activity

i am very new to android.
i m trying to develop a login form for practise , and i m unable to pass and display 2 values
to another activity
Intent intent = new Intent(this, Success.class);
EditText edituser = (EditText) findViewById(R.id.userinput);
EditText editpass= (EditText) findViewById(R.id.passinput);
String username = edituser.getText().toString();
String password = editpass.getText().toString();
intent.putExtra(EXTRA_USER, username);
intent.putExtra(EXTRA_PASSWORD, password);
startActivity(intent);
and target activity is
Intent intent = getIntent();
String username = intent.getStringExtra(MainActivity.EXTRA_USER);
String password = intent.getStringExtra(MainActivity.EXTRA_PASSWORD);
// Create the text view
TextView userView = new TextView(this);
TextView passView = new TextView(this);
userView.setTextSize(40);
userView.setText(username);
passView.setTextSize(40);
passView.setText(password);
// Set the text view as the activity layout
setContentView(userView);
setContentView(passView);
Your problem is that when you call setContentView() the second time, you remove the older view from the screen.
Try adding your Views to a ViewGroup like a LinearLayout and then adding that to the screen instead of individual Views.
Something like:
LinearLayout ll = new LinearLayout(this);
ll.addView(userView);
ll.addView(passView);
setContentView(ll);
You are getting the second value only, because you are setting your view twice..
the second one overrides the username..
You can use addContentView instead, or create an xml that contains 2 text views and use that..
use another layout and set intent values in the second layout....
setContentView(R.layout.anotherlayout);
TextView user = (TextView) findViewById(R.id.usertext);
TextView pass= (TextView) findViewById(R.id.passtext);
Intent intent = getIntent();
String username = intent.getStringExtra(MainActivity.EXTRA_USER);
String password = intent.getStringExtra(MainActivity.EXTRA_PASSWORD);
user.setText(username);
pass.setText(password);

Can't update TextView from another activity

I have an activity with a TextView that needs to be updated from a second activity.
I can pass the Text view data to the 2nd activity ok, but when I try to update that TextView
within the 2nd activity it crashes. My code:
1st Activity (where the TextView is defined in my xml):
Intent intent = new Intent(1stactivity.this, 2ndactivity.class);
intent.putExtra("homescore_value", ((TextView)findViewById(R.id.score_home)).getText());
startActivity(intent);
// code snippet
Then in my 2nd activity:
Bundle bundle = getIntent().getExtras();
hometext = bundle.getString("homescore_value"); // this works and displays the correct String from 1st activity,
but it crashes when I try to pull in as a TextView:
// other code snipped
int homescore = 0;
String Home_nickname = "HOME ";
TextView homestext = (TextView) bundle.get("homescore_value");
hometext.setText(Home_nickname +": "+homescore );
Please help.
You are trying to get a String as a TextView (you are setting a String in the intent from the first Activity).
You trying to cast String to TextView. The code that crashes is equivalent of:
String text = bundle.get("homescore_value"); //this is ok
TextView textView = (TextView)text; //this is bad
You should do instead:
String text = bundle.get("homescore_value");
TextView textView = (TextView)findViewById(R.id.yourTextViewId);
textView.setText(text);
This line here:
intent.putExtra("homescore_value", ((TextView)findViewById(R.id.score_home)).getText());
is attaching a String along with the intent, not a TextView.
You must inflate a new TextView within the 2nd activity, by either declaring it in the layout.xml, or programmatically placing it within the layout.
Something that solved part of this problem for me was setting the receiving String variables to null like this:
public String param1new = null;
public String param2new= null;
My issue with this is I'm trying to set background colors on several TextViews and only the first one is being set at this time.

Categories

Resources