pass listview values from one activity to another activity - android

I have one list view and there are different values within it such as name, qty,unit,disc,price. I want to pass these values to next activity. I set 5 text boxes in new activity. this new activity is for update the values. how to pass values and display the same in new activity.???
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent myIntent = new Intent(getApplicationContext(), Update.class);
myIntent.putExtra("ItemName", "value");
startActivity(myIntent);
}
});

You can use following ways for sharing data in android:
Intent and put extra data in the Bundle
SharePreferences in the Application class
SQLite database
Static variable

You can pass the data via Intent Extras eg :-
Intent intent = new Intent(this,calledActivity.class);
intent.putExtra("Caller",THIS_ACTIVITY);
startActivity(intent);
In this example Caller is the Key and THIS_ACTIVITY contains the value to be passed. This is then retrieved in the called activity like :-
String caller = getIntent().getStringExtra("Caller");

You can pass an entire object through Intents, as long as they implement the Parcelable / Serializable class.
public class Myclass implements Parcelable {}
Implementing these classes will ensure that your Object can be serialized.
Then you will be able to attach it to your Intent, and later retrieve it by calling getParcelableExtra or other methods.

Related

Generalized Android Activity

I am new to Android programming. My question is that i have a list (ListView) of 8 restaurant headings. Upon clicking of any of these, a new page (activity) would start containing the menu and details of the restaurant. I understand that implementing 8 activities would be wasteful so probably i will have a general restaurant detail activity.
Now i am figuring out how to display this information out in an efficient way. I have so far implemented this which helps me to send a message across to the other activity according to the restaurant selected. But how can i send big chunks of information:
----MainActivity.java------
String [] restaurants = {"abc","def"....};
int POSITION_ACT;
list.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
POSITION_ACT=position;
customActivity(view);
}
});
public void customActivity(View view) {
Intent intent = new Intent(this, RestaurantDetails.class);
intent.putExtra(MESSAGE, "You clicked this restaurant: " + restaurants[POSITION_ACT]);
startActivity(intent);
}
--generalrestaurant.java----
Intent intent = getIntent();
String msg = intent.getStringExtra(foodActivity.MESSAGE);
TextView tt1 = (TextView) findViewById(R.id.tt1);
tt1.setText(msg);
You shouldn't be passing lots of information. Your model information should be in instances of a Restaurant class. Then you can keep all those instances in an ArrayList in a singleton. Write a getter for the singleton that returns a Restaurant instance and then call it from the RestaurantDetails activity using the extra you sent (maybe you want to make this a UUID). Finally, when the activity dies, you should save the Restaurant data from the singleton to a raw XML file or something and read it back in when the app starts up again.
You can create a POJO for your restaurant information and write data like Name, Location, Per head cost, rating etc to it. Then your POJO must implement Serializable or Parcelable. In your intent you can pass your POJO using intent.putExtra(String, Serializable) or intent.putExtra(String, Parcelable). In your second activity you can get the object and display your data in your Activity. Have a look at the below links :
http://developer.android.com/reference/java/io/Serializable.html
http://developer.android.com/reference/android/os/Parcelable.html

How can I get access to a fragment method from another activity

I have a fragment which summons a custom CursorAdaper and display it on a ListView
. The thing is I want to change the cursor by changeCursor() from another activity when I add new data, How can I get access to the CursorAdapter displayed on the fragment?
Essentially you have to pass data from one Activity to another and let the fragment of you choice receive the data (each fragment of a given Activity may get the Intent that started/restarted/resumed the Activity).
Consider this code
-- pass data:
String[] myListEntries = getNewListContents();
Intent updateList = new Intent(this, ActivityThatListFragmentBelongsTo.class);
updateList.putExtra("updated_list", myListEntries);
startActivity(updateList);
-- receive data (in fragment):
#Override
public void onResume() {
Intent wasStartedWithData = getActivity().getIntent();
String[] updatedList = wasStartedWithData.getStringArrayExtra("updated_list");
// pass updatedList to adapter
}
Now you might actually have more complicated data than an Array of Strings. In this case
you could create a class that implements 'Parcelable' (http://developer.android.com/reference/android/os/Parcelable.html) and call
putExtra(Parcelable parcel) / getParcelableExtra(String name) on the Intent.

How to pass object to an activity?

I have two activities, NewTransferMyOwn.java and FromAccount.java
When I go from NewTransferMyOwn.java to FromAccount.java, I do write code as following
Intent i = new Intent(NewTransferMyOwn.this, FromAccount.class);
startActivityForResult(i, FROM_ACCOUNT);
When I do come back from FromAccount.java to NewTransferMyOwn.java, then I want to pass a complete object of class Statement
I do write code as
Statement st = ItemArray.get(arg2);//ItemArray is ArrayList<Statement>, arg2 is int
Intent intent = new Intent(FromAccount.this,NewTransferMyOwn.class).putExtra("myCustomerObj",st);
I do get error as following on putExtra,
Change to 'getIntExtra'
as I do, there is again casting st to int, what is issue over here, how can I pass Statement object towards back to acitivity?
You can also implement your custom class by Serializable and pass the custom Object,
public class MyCustomClass implements Serializable
{
// getter and setters
}
And then pass the Custom Object with the Intent.
intent.putExtra("myobj",customObj);
To retrieve your Object
Custom custom = (Custom) data.getSerializableExtra("myobj");
UPDATE:
To pass your custom Object to the previous Activity while you are using startActivityForResult
Intent data = new Intent();
Custom value = new Custom();
value.setName("StackOverflow");
data.putExtra("myobj", value);
setResult(Activity.RESULT_OK, data);
finish();
To retrieve the custom Object on the Previous Activity
if(requestCode == MyRequestCode){
if(resultCode == Activity.RESULT_OK){
Custom custom = (Custom) data.getSerializableExtra("myobj");
Log.d("My data", custom.getName()) ;
finish();
}
}
You can't pass arbitrary objects between activities. The only data you can pass as extras/in a bundle are either fundamental types or Parcelable objects.
And Parcelables are basically objects that can be serialized/deserialized to/from a string.
You can also consider passing only the URI refering to the content and re-fetching it in the other activity.

Best way to pass objects from one activity to another

I have read about global static technique in which we create a class with static fields which can be accessed in any activity. Is there any other way to pass large data sets like ArrayList<Drawables> or HashMaps ?
I have also read about Serializable but have no idea how to use it. Any example code is welcome...
Intent intent = new Intent(getBaseContext(), NextActivity.class);
intent.putExtra("arraylist", new ArrayList<String>());
If your ArrayList contains another Object that you have created yourself, for instance Friend.class, you can implement the Friend.class with Serializable and then:
Intent intent = new Intent(getBaseContext(), NextActivity.class);
intent.putExtra("friendlist", new ArrayList<Friend>());
And for receiving it on NextActivity.class:
Bundle extras = getIntent().getExtras();
if(extras != null){
ArrayList<Friend> friends = extras.getSerializable("friendlist");
}
Well, instead of passing an empty ArrayList, you'll have to put values into the ArrayList and then pass it, but you get the idea.
You should pack your information into the Intent object you create to call your next Activity. There is a extras Bundle object.
You can use either the Serializable interface or the Android-specific Parcelable interface to pass non-primitive objects.
The Android Developer site has a handy Notepad Tutorial with an example of putting information into the intent.
From their tutorial:
super.onListItemClick(l, v, position, id);
Cursor c = mNotesCursor;
c.moveToPosition(position);
Intent i = new Intent(this, NoteEdit.class);
i.putExtra(NotesDbAdapter.KEY_ROWID, id);
i.putExtra(NotesDbAdapter.KEY_TITLE, c.getString(
c.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
i.putExtra(NotesDbAdapter.KEY_BODY, c.getString(
c.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)));
startActivityForResult(i, ACTIVITY_EDIT);
As long as you stay in the same application( speak: same JVM ) you do not need to bother with intents, parcelables, serialisation etc - all objects are on same heap and can be passed via singletons, DI containers like roboguice or whatever you see fit.
If you like to push data to an other application, best technique would be to pass it as JSON/XML serialized stuff.
Passing Hashmap is pretty simple, All Collections objects implement Serializable (sp?) interface which means they can be passed as Extras inside Intent
Use putExtra(String key, Serializable obj) to insert the HashMap and on the other acitivity use getIntent().getSerializableExtra(String key), You will need to Cast the return value as a HashMap though.

How to put a List in intent

I have a List in one of my activities and need to pass it to the next activity.
private List<Item> selectedData;
I tried putting this in intent by :
intent.putExtra("selectedData", selectedData);
But it is not working. What can be done?
Like howettl mentioned in a comment, if you make the object you are keeping in your list serializeable then it become very easy. Then you can put it in a Bundle which you can then put in the intent. Here is an example:
class ExampleClass implements Serializable {
public String toString() {
return "I am a class";
}
}
... */ Where you wanna create the activity /*
ExampleClass e = new ExampleClass();
ArrayList<ExampleClass> l = new ArrayList<>();
l.add(e);
Intent i = new Intent();
Bundle b = new Bundle();
b.putSerializeable(l);
i.putExtra("LIST", b);
startActivity(i);
You have to instantiate the List to a concrete type first. List itself is an interface.
If you implement the Parcelable interface in your object then you can use the putParcelableArrayListExtra() method to add it to the Intent.
i think ur item should be parcelable. and you should use arraylist instead of list.
then use intent.putParcelableArrayListExtra
This is what worked for me.
//first create the list to put objects
private ArrayList<ItemCreate> itemsList = new ArrayList<>();
//on the sender activity
//add items to list where necessary also make sure the Class model ItemCreate implements Serializable
itemsList.add(theInstanceOfItemCreates);
Intent goToActivity = new Intent(MainActivity.this, SecondActivity.class);
goToActivity.putExtra("ITEMS", itemsList);
startActivity(goToActivity);
//then on second activity
Intent i = getIntent();
receivedItemsList = (ArrayList<ItemCreate>) i.getSerializableExtra("ITEMS");
Log.d("Print Items Count", receivedItemsList.size()+"");
for (Received item:
receivedItemList) {
Log.d("Print Item name: ", item.getName() + "");
}
I hope it works for you too.
Everyone says that you can use Serializable, but none mentioned that you can just cast the value to Serializable instead of list.
intent.putExtra("selectedData", (Serializable) selectedData);
Core's lists implementations already implement Serializable, so you're not bound to a specific implementation of list, but remember that you still can catch ClassCastException.

Categories

Resources