I'm getting problems using the Intent for navigate through the screens. I want to send a variable and use it in the other class.
I'm using a method, the method takes the variable but i don't know how to send it with the intent to the new screen, which will use it to do some things.
Main class calls the metod:
private void pantallaDetalles(final int identificador)
{
startActivityForResult(new Intent(this,MostrarDetalles.class),REQST_CODE);
}
MostrarDetalles.class is the *.java which will take the variable. I'm begining it like this:
public class MostrarDetalles extends Activity {
SQLiteDatabase db;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.detalles);
//more code...
Cursor c = db.rawQuery("SELECT * FROM table WHERE _id="+ identificador, null);
}
Did you see? I'm talking about this. I don't know how to send the "identificador" variable from the main class to the second class through the Intent.
Can you help me with this? Thank you very much in advice.
JMasia.
Use the extras bundle in the intent.
Intent i = new Intent(...);
i.putExtra("name_of_extra", myObject);
Then on onCreate:
getIntent.getIntExtra("name_of_extra", -1);
Screen 1:
Intent i=new Intent("com.suatatan.app.Result");
i.putExtra("VAR_RESULT", "Added !");
startActivity(i);
Screen 2: (Receiver):
TextView tv_sonuc = (TextView) findViewById(R.id.tv_sonuc);
Bundle bundle = getIntent().getExtras();
String var_from_prev_intent = bundle.getString("VAR_RESULT");
tv_sonuc.setText(var_from_prev_intent);
You can use Intent.putExtra() to bundle the data you want to send with the intent.
Related
How can I receive a custom ArrayList from another Activity via Intent? For example, I have this ArrayList in Activity A:
ArrayList<Song> songs;
How could I get this list inside Activity B?
The first part to understand is that you pass information from Activity A to Activity B using an Intent object, inside which you can put "extras". The complete listing of what you can put inside an Intent is available here: https://developer.android.com/reference/android/content/Intent.html (see the various putExtra() methods, as well as the putFooExtra() methods below).
Since you are trying to pass an ArrayList<Song>, you have two options.
The first, and the best, is to use putParcelableArrayListExtra(). To use this, the Song class must implement the Parcelable interface. If you control the source code of Song, implementing Parcelable is relatively easy. Your code might look like this:
Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putParcelableArrayListExtra("songs", songs);
The second is to use the version of putExtra() that accepts a Serializable object. You should only use this option when you do not control the source code of Song, and therefore cannot implement Parcelable. Your code might look like this:
Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putSerializableExtra("songs", songs);
So that's how you put the data into the Intent in Activity A. How do you get the data out of the Intent in Activity B?
It depends on which option you selected above. If you chose the first, you will write something that looks like this:
List<Song> mySongs = getIntent().getParcelableArrayListExtra("songs");
If you chose the second, you will write something that looks like this:
List<Song> mySongs = (List<Song>) getIntent().getSerializableExtra("songs");
The advantage of the first technique is that it is faster (in terms of your app's performance for the user) and it takes up less space (in terms of the size of the data you're passing around).
Misam is sending list of Songs so it can not use plain putStringArrayList(). Instead, Song class has to implement Parcelable interface. I already explained how to implement Parcelable painless in post here.
After implementing Parcelable interface just follow Uddhavs answer with small modifications:
// First activity, adding to bundle
bundle.putParcelableArrayListExtra("myArrayListKey", arrayList);
// Second activity, reading from bundle
ArrayList<Song> list = getIntent().getParcelableArrayListExtra("myArrayListKey");
I hope this helps you.
1. Your Song class should be implements Parcelable Class
public class Song implements Parcelable {
//Your setter and getter methods
}
2. Put your arraylist to putParcelableArrayListExtra()
public class ActivityA extends AppCompatActivity {
ArrayList<Song> songs;
#Override
protected void onCreate(Bundle savedInstanceState) {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), ActivityB.class)
.putParcelableArrayListExtra("songs", (ArrayList<? extends Parcelable>) songs));
}
});
}
3. In the ActivityB
public class ActivityB extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
final ArrayList<Song> songs = intent.getParcelableArrayListExtra("songs");
//Check the value in the console
buttonCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (Song value : songs) {
System.out.println(value.getTitle());
}
}
});
}
to send a string arrayList in Java you can use,
intent.putStringArrayListExtra("key", skillist <- your arraylist);
and
List<String> listName = getIntent().getStringArrayListExtra("key");
Please note, bundle is one of the key components in Android system that is used for inter-component communications. All you have to think is how you can use put your Array inside that bundle.
Sending side (Activity A)
Intent intent1 = new Intent(MainActivity.this, NextActivity.class);
Bundle bundle = new Bundle();
Parcelable[] arrayList = new Parcelable[10];
/* Note: you have to use writeToParcel() method to write different parameters values of your Song object */
/* you can add more string values in your arrayList */
bundle.putParcelableArray("myParcelableArray", arrayList);
intent1.putExtra("myBundle", bundle);
startActivity(intent1);
Receiving side (Activity B)
Bundle bundle2 = getIntent().getBundleExtra("myBundle"); /* you got the passsed bundle */
Parcelable[] arrayList2 = bundle.getParcelableArray("myParcelableArray");
I explained this badly originally. This is my question: The Intent I send to the startActivity() method, contains a private field, mMap, which is a Map containing the strings I sent to putExtra(). When the target activity starts, a call to getIntent() returns an Intent that does not contain those values. The mMap field is null. Obviously, something in the bowels of the View hierarchy or the part of the OS that started the new activity created a new Intent to pass to it, since the object IDs are different.
But why? And why are the putData() values not carried fowrard to the new Intent?
The activity that starts the new activity extends Activity. Here's the startup code:
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case 4:
i = new Intent(this, StatList.class);
i.putExtra("Name1", "Test1");
i.putExtra("Name3", "Test2");
startActivity(i);
}
}
I've tried the key values with and without the (recommended) complete package name prefix.
In the Eclipse debugger, I have verified the values for the player names are being inserted into i.mExtras.mMap properly.
Here's the code from the startee:
public class StatList extends ListActivity {
private final StatsListAdapter statsAdapter;
public StatList() {
statsAdapter = StatsListAdapter.getInstance(this);
} // default ctor
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Intent i = getIntent();
final Bundle extras = i.getExtras();
< more code here >
}
When execution gets to this method, mIntent.mExtras.mMap is null, and mIntent.mExtras.mParcelledData now contains some values that don't look sensible (it was null when startActivity() was called). getIntent() returns mIntent.
I've also tried startActivityForResult(), with the same result.
From the docs and the samples I've seen online & in the sample apps, this should be easy. I've found another way to meet my immediate need, but I'd like to know if anyone can help me understand why something this simple doesn't work.
In your main Activity:
i = new Intent(this, StatList.class);
i.putExtra("Name1", "Test1");
i.putExtra("Name3", "Test2");
startActivity(i);
Then in StatList.class
Bundle extras = getIntent().getExtras();
String name1 = extras.getString("Name1");
String name3 = extras.getString("Name3");
Log.i("StatList", "Name1 = " + name1 + " && Name3 = " + name3)
Update the following two line
final Intent i = getIntent();
final Bundle extras = i.getExtras();
Replace it with
Bundle extras = getIntent().getExtras();
if(extras!= null){
String var1= extras.getString("Name1");
String var2= extras.getString("Name2");
}
How do I pass an ArrayList between classes? I want to pass an ArrayList from this class/method that extends Activity...
public class OpportunityActivity extends Activity {
public void updateOpportunities(ArrayList<Opportunity> opportunities) {
Intent intent = new Intent(this, OppListActivity.class);
startActivity(intent);
}
...over to OppListActivity class that extends ListActivity where I use this opportunities ArrayList to populate my custom ListView using the elements in the arraylist opportunities:
public class OppListActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
I'd like to pass opportunities arraylist between the two intact. Should I...
- use a bundle (I've tried but can't work out the right syntax, and this seems like overkill/maybe there's a better way?)
- make opportunities public / somehow exposed to both classes
- pass opportunities as a parameter?
Specific syntax (not pseudocode) appreciated.
You can't create an Activity like this:
public void updateOpportunities(ArrayList<Opportunity> opportunities) {
OppListActivity a = new OppListActivity();
}
You should always use an Intent. In the Intent you can add an "extra" with your ArrayList, which you will read later in your ListActivity. Note that you will probably need to make your Opportunity implement Parcelable. There's a lot of info on both of these topics both in StackOverflow and in the official docs.
You need to use intents to start a new activity. And you can actually put serializable objects in your intent's extra data:
public void updateOpportunities(ArrayList<Opportunity> opportunities) {
Intent intent = new Intent(this, OppListActivity.class);
intent.putExtra("opportunities", opportunities);
startActivity(intent);
}
And in your OppListActivity activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
ArrayList<Opportunity> opportunities = intent.getSerializableExtra("opportunities");
}
But you probably need to make sure that Opportunity class extends Serializable.
On way is to use putExtra if you are using an Intent to trigger the next activity. It would look something like this:
ArrayList<String> test_array = new ArrayList<String>();
// do something with test_array
Intent launchNextActivity = new Intent(getApplicationContext(), nextActivity.class);
launchNextActivity.putExtra("array", test_array);
startActivity(launchNextActivity);
And then in the activity you launch, you could use the following to get it:
Intent sender = getIntent();
ArrayList<String> passedInArray = new ArrayList<String>();
passedInArray = sender.getStringArrayExtra("array");
usually you add an extra bundle when starting a new intent when switching to some other activity. e.g
ArrayList<String> theArrayList = new ArrayList<String>();
Intent i = new Intent(this,TheNewActivity.class);
i.putStringArrayListExtra("list",theArrayList);
startActivity(i);
finish();
hiiii..... You can use Bean,with the one ArrayList
e.g
ArrayList<RowItem> aryListbean=new ArrayList<rowItem>(); //your arraylist
RowItem rowItem=new RowItem(); // that is your bean class
now You have to create a class RowItem,that is your Bean,which have getter/setter method
for(....)
{
rowItem.setUserId(); // set method's example
rowItem.setPassword() // set method's exampl
aryListbean.add(rowItem);
}
Now you can use your data in every Activities using getmethod
e.g
getUserId();
getUserPassword();
how to pass 2D Array as a parameter to another Activity?? i try it stack over flow solution but is not work im using this code
in activity 1 is correctly show value in this line bundle.putSerializable("xmlResponee", xmlRespone);
but is not showe value in activity2 class what is wrong? tell me please
public class Activity1 extends Activity {
private String[][] xmlRespone;
Intent i = new Intent(this.getApplicationContext(), Activity2.class);
Bundle bundle = new Bundle();
bundle.putSerializable("xmlResponee", xmlRespone);
i.putExtras(bundle);
startActivity(i);
and
public class Activity2 extends Activity {
private String[][] xmlRespone;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2);
Bundle bundle = getIntent().getExtras();
String[][] xmlRespone2 = (String[][]) bundle.getSerializable("xmlResponee");
You can make a static class.. with private String[][] xmlRespone. in first Activity you can Assign value to it,and in another activity you can call data from it..
Activity A ---> Static class X ---> Activity B.
Hey just use Parcelable objects to pass objects between android activities.
Here is a really awesome example. I guess this is the same thing you want to achieve.
You can put it directly on the intent no need bundle.
Intent intent = new Intent();
intent.putExtra("MyXML", xmlRespone);
And to read:
#Override
public void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
String[] xmlRespone = intent.getStringArrayExtra("MyXML");
}
As the title says I want to transfer data, in this case the information introduced by the user on an EditText and a Spinner, from one activity to another.
I am following a tutorial from a book but it doesn't work (I think its not complete). Here the code of the program:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
this.location=(EditText)findViewById(R.id.location);
this.cuisine=(Spinner)findViewById(R.id.cuisine);
this.grabReviews=(Button)findViewById(R.id.get_reviews_button);
ArrayAdapter adapter = ArrayAdapter.createFromResource(this, R.array.cuisine, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
this.cuisine.setAdapter(adapter);
this.grabReviews.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
handleGetReviews();
}
}
);
}
private void handleGetReviews() {
RestaurantsActivity application= (RestaurantsActivity) getApplication();
application.setReviewCriteriaCuisine(this.cuisine.getSelectedItem().toString());
application.setReviewCriteriaLocation(this.location.getText().toString());
Intent intent=new Intent(Constants.INTENT_ACTION_VIEW_LIST);
startActivity(intent);
}
This code above doesn't work. I dont understand four things:
-RestaurantsActivity must be the actual activity right?
-In all the examples I have seen over the internet there is an application extends class, in this example there isnt.
-setReviewCriteria function is missing
-Where does Constants.INTENT_ACTION_VIEW_LIST come from ?
So your target is to get the data to Restaurantsactivity?
Normally data in android are handed over from one activtiy to another by using Intents.
So first you create an intent.
Then you put the data you want to transfer into the intent by using the intent.putExtra() method.
In the activity that gets the intent you can get the data by using getIntent().getExtra() method (getExtra can be something like getStringExtra()).
Here is a small example for a edit box called "name":
public void onCreate(Bundle iBundle){
//do some stuff here
//perhaps define some Buttos and so on
//now lets start the activity
Intent intent = new Intent(currentActivityname.this, ActivityYouWantToStart.class);
intent.putExtra("name", name.getText().toString())
startActivity(intent); // you can also start an startActivityForResult() here :)
}
In our receiving activity you can now handle the intent (e.g. in the onCreate() method
public void onCreate(Bundle iBundle){
String name = this.getIntent().getStringExtra("name",some default value);
}
Try to put data in the Bundle and start Activity with this Bundle
Intent intent = new Intent(this, YourSecondActivity.class);
intent.putExtra(... HERE YOUR BUNDLE WITH DATA ...);
startActivity(intent);
Hope, it help you!