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);
Related
Hello I want to have an Add function that allows me to input items to my GridView
For Background: I have a standard GridView and an XML activity (which contains 2 TextView) that I want to convert to my GridView. I also have a custom ArrayAdapter class and custom Word object (takes 2 Strings variables) that helps me do this.
My problem: I want to have an Add button that takes me to another XML-Layout/class and IDEALLY it input a single item and so when the user goes back to MainActivity the GridView would be updated along with the previous information that I currently hard-coded atm. This previous sentence doesn't work currently
Custom ArrayAdapter and 'WordFolder' is my custom String object that has 2 getters
//constructor - it takes the context and the list of words
WordAdapter(Context context, ArrayList<WordFolder> word){
super(context, 0, word);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View listItemView = convertView;
if(listItemView == null){
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.folder_view, parent, false);
}
//Getting the current word
WordFolder currentWord = getItem(position);
//making the 2 text view to match our word_folder.xml
TextView title = (TextView) listItemView.findViewById(R.id.title);
title.setText(currentWord.getTitle());
TextView desc = (TextView) listItemView.findViewById(R.id.desc);
desc.setText(currentWord.getTitleDesc());
return listItemView;
}
}
Here is my NewFolder code. Which sets contentview to a different XML. it's pretty empty since I'm lost on what to do
public class NewFolder extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_folder_view);
Button add = (Button) findViewById(R.id.add);
//If the user clicks the add button - it will save the contents to the Word Class
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//make TextView variables and cast the contents to a string and save it to a String variable
TextView name = (TextView) findViewById(R.id.new_folder);
String title = (String) name.getText();
TextView descText = (TextView) findViewById(R.id.desc);
String desc = (String) descText.getText();
//Save it to the Word class
ArrayList<WordFolder> word = new ArrayList<>();
word.add(new WordFolder(title, desc));
//goes back to the MainActivity
Intent intent = new Intent(NewFolder.this, MainActivity.class);
startActivity(intent);
}
});
}
In my WordFolder class I made some TextView variables and save the strings to my ArrayList<> object but so far it's been useless since it doesn't interact with the previous ArrayList<> in ActivityMain which makes sense because its an entirely new object. I thought about making the ArrayList a global variable which atm it doesn't make sense to me and I'm currently lost.
Sample code would be appreciative but looking for a sense of direction on what to do next. I can provide other code if necessary. Thank you
To pass data between Activities to need to do a few things:
First, when the user presses your "Add" button, you want to start the second activity in a way that allows it to return a result. this means, that instead of using startActivity you need to use startActivityForResult.
This method takes an intent and an int.
Use the same intent you used in startActivity.
The int should be a code that helps you identify where a result came from, when a result comes. For this, define some constant in your ActivityMain class:
private static final int ADD_RESULT_CODE = 123;
Now, your button's click listener should looks something like this:
addButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent=new Intent(MainActivity.this, NewFolder.class);
startActivityForResult(intent, ADD_RESULT_CODE);
}
});
Now for returning the result.
First, you shouldn't go back to your main activity by starting another intent.
Instead, you should use finish() (which is a method defined in AppCompatActivity, you can use to finish your activity), this will return the user to the last place he was before this activity - ActivityMain.
And to return some data, too, you can use this code:
Intent intent=new Intent();
intent.putExtra("title",title);
intent.putExtra("desc",desc);
setResult(Activity.RESULT_OK, intent);
where title and desc are the variables you want to pass.
in your case it should look something like this:
public class NewFolder extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_folder_view);
Button add = (Button) findViewById(R.id.add);
//If the user clicks the add button - it will save the contents to the Word Class
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//make TextView variables and cast the contents to a string and save it to a String variable
TextView name = (TextView) findViewById(R.id.new_folder);
String title = (String) name.getText();
TextView descText = (TextView) findViewById(R.id.desc);
String desc = (String) descText.getText();
//Save it to the Word class
ArrayList<WordFolder> word = new ArrayList<>();
word.add(new WordFolder(title, desc));
Intent intent=new Intent();
intent.putExtra("title",title);
intent.putExtra("desc",desc);
setResult(Activity.RESULT_OK, intent);
//goes back to the MainActivity
finish();
}
});
}
You should probably also take care of the case where the user changed his mind and wants to cancel adding an item. in this case you should:
setResult(Activity.RESULT_CANCELLED);
finish();
In your ActivityMain you will have the result code, and if its Activity.RESULT_OK you'll know you should add a new item, but if its Activity.RESULT_CANCELLED you'll know that the user changed their mind
Now all that's left is receiving the data in ActivityMain, and doing whatever you want to do with it (like adding it to the grid view).
To do this you need to override a method called onActivityResult inside ActivityMain:
// Call Back method to get the Message form other Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check the result code to know where the result came from
//and check that the result code is OK
if(resultCode == Activity.RESULT_OK && requestCode == ADD_RESULT_CODE )
{
String title = data.getStringExtra("title");
String desc = data.getStringExtra("desc");
//... now, do whatever you want with these variables in ActivityMain.
}
}
I am trying to send a string and a int type data from one activity to another but due to lack of knowledge i don't know how to do it.
With the particular coding given below now i can only send any one of the data type.
searched a lot but not found any answer appropriate for my question. If i have asked any thing wrong plzz notify me as i am new to android Dev.
Any help may be appreciated.
this is my java coding of the two activities :
First.java
public class QM extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qm);
}
public void FLG(View view) {
// Do something in response to button
EditText mEditText= (EditText)findViewById(R.id.editText1);
String str = mEditText.getText().toString();
Intent intent = new Intent(this, Q1.class);
intent.putExtra("myExtra", str);
startActivity(intent);
finish();
}
}
Second.java
public class Q1 extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_q1);
Intent intent = getIntent();
if (intent.hasExtra("myExtra")){
TextView mText = (TextView)findViewById(R.id.textView1);
mText.setText("user name "+intent.getStringExtra("myExtra")+"!"); }
}
}
You can send 2 extras or even more as long you have different keys for it, so in your problem you need 2 extras one for String and one for Integer.
sample:
pass:
Intent intent = new Intent(this, Q1.class);
intent.putExtra("myExtra", str);
intent.putExtra("myExtraInt", yourInt);
get:
Intent intent = getIntent();
if (intent.hasExtra("myExtra") && intent.hasExtra("myExtraInt")){
TextView mText = (TextView)findViewById(R.id.textView1);
mText.setText("user name "+intent.getStringExtra("myExtra")+"!");
int extraInt = intent.getIntExtra(myExtraInt);
}
I'd like to give you some information.
Imagine the Intent's extras to be a (theoretically) infinitely sized bagpack. You can put certain type of data into it in an infinite number as long as each of the data has a unique name which is a string.
Internally it's a table that maps names to values.
So: Yes you can put String and Int simultaneously into the Intent's extras like this.
String str = "Test";
int val = 2933;
Intent i = new Intent(MyActivity.this, NewActivity.class);
i.putExtra("MyStringExtraUniqueName", str);
i.putExtra("MyIntExtraUniqueName", val);
To check for it use i.hasExtra("MyStringExtraUniqueName") as you did already and to get it use i.getExtra("MyStringExtraUniqueName").
BUT if you only use getExtra you'll be returned data of type object. Remember to cast the returned value to the appropriate type or use one of the specialized getter methods for some predefined data types.
See this for the available getters: http://developer.android.com/reference/android/content/Intent.html
Bundle data = new Bundle();
data.putInt("intKey", 5);
data.putString("stringKey", "stackoverflow");
Intent i = new Intent(MyActivity.this, NewActivity.class);
i.putExtras(data);
//And in the second acitvity fetch this way
Bundle data = getIntent().putExtras(b);
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.
What am I doing wrong?
I've looked at other questions and thought I was doing the exact same things, but since its not working for me, obviously I'm doing something wrong!
I have my MainActivity.class that gets JSON data (coordinates) from a URL. This part works. I then want to load up a MapView, called OverlayActivity.class, and send this data to this map so I can populate it with overlays etc.
I pull varying numbers of points down and dynamically create buttons. Depending on what button is clicked, it sends different data.
Here's the code for this loop:
final LinearLayout layout = (LinearLayout) findViewById(R.id.menuLayout);
layout.removeAllViewsInLayout();
String itemName="";
int itemID=0;
for (int i = 0; i < dataSetsMap.size(); i++) {
itemID=i+1;
itemName=dataSetsMap.get(itemID);
Button b = new Button(this);
b.setText(itemName);
layout.addView(b);
// These need to be final to use them inside OnClickListener()
final String tempName=itemName;
final int tempID=itemID;
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent();
Bundle b = new Bundle();
i.setClass(myContext, OverlayActivity.class);
Log.i(TAG, "Setting extras: 1:"+tempName+" and 2:"+tempID);
b.putInt(tempName, tempID);
i.putExtras(b);
startActivity(i);
}
});
} // End for()
So obviously I want to read this data on the other side, assuming I'm sending it correctly. So, to read it, I've been trying a few different things:
//Method 1:
String test1=intent.getStringExtra("name");
String test2=intent.getStringExtra("id");
//Method 2:
String meh=getIntent().getExtras().getString("id").toString();
String bleh=getIntent().getExtras().getString("name");
//Method 3:
String value=savedInstanceState.getString("name");
String id=savedInstanceState.getString("id").toString();
//Method 4:
Bundle bundle = getIntent().getExtras();
String id=bundle.getString("id");
String value = getIntent().getExtras().getString("name");
i get a NullPointerException when trying to use any of these methods. Its my first time using these types of methods so can someone point me in the right direction or tell me where I've gone wrong?
Firstly, using Bundle b when you've already got Button b isn't really a good idea if for no other reason than it gets confusing, ;)
Secondly, you don't need to use a Bundle to pass a string and an int. Just add them to your Intent directly...
Intent i = new Intent(myContext, OverlayActivity.class);
i.putExtra("name", tempName);
i.putExtra("id", tempID);
startActivity(i);
To retrieve them in your OverlayActivity use...
Intent i = getIntent();
String name = i.getStringExtra("name");
int id = i.getIntExtra("id", -1); // -1 in this case is a default value to return if id doesn't exist
Why not just do this:
Intent i = new Intent();
i.setClass(myContext, OverlayActivity.class);
Log.i(TAG, "Setting extras: 1:"+tempName+" and 2:"+tempID);
i.putExtra("name", tempName);
i.putExtra("id", tempID);
startActivity(i);
and then you can fetch them with:
String name = getIntent().getStringExtra("name", "");
int id = getIntent().getIntExtra("id", 0);
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.