how to pass list of objects through intent - java

I am trying to pass the list of object from one activity to another. But not able to send it.
Here is my code.
setPrefBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent homePageIntent = new Intent(SetPreferences.this,
KlarityHome.class);// Connecting setPreferences page
// with Klarity Home Page
List<PracticeVO> tempList = new ArrayList<PracticeVO>();
tempList.add(practiceObj);
homePageIntent.putExtra("SelectedPractice", tempList.toArray());
startActivity(homePageIntent);
}
});
And retriving in 2nd activity like this :
Intent prefIntent = new Intent();
List preferencedPractices = (List) getIntent().getExtras().get("SelectedPractice");
ArrayAdapter<PracticeVO> praticeAdapter = new ArrayAdapter<PracticeVO>(this, android.R.layout.simple_spinner_item,
preferencedPractices);
praticeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
practiceSpin.setAdapter(praticeAdapter);

You need to use putExtra() function to pass values to another activity
Intent newIntent = new Intent(MainActivity.this, ResultActivity.class);
newIntent.putExtra("yourTxtField",yourTxtField.getText());
to receive you need to use other getIntent and Bundle.
Intent myIntent = getIntent();
Bundle valores = myIntent.getExtras();
//Objeto que vai calcular os resultados
Resultado resultado = new Resultado();
//Recupera os valores recebidos pelo intent
double seuDinheiro = Double.parseDouble((String) valores.get("seuDinheiro").toString());
To pass objects see this SO post
How do I pass an object from one activity to another on Android?
How to pass an object from one activity to another on Android

Try in this manner
ArrayList<Object> object = new ArrayList<Object>();
Intent intent = new Intent(Current.class, Transfer.class);
Bundle args = new Bundle();
args.putSerializable("ARRAYLIST",(Serializable)object);
intent.putExtra("BUNDLE",args);
startActivity(intent);
In the Transfer.class
Intent intent = getIntent();
Bundle args = intent.getBundleExtra("BUNDLE");
ArrayList<Object> object = (ArrayList<Object>) args.getSerializable("ARRAYLIST");

What type is PracticeVO? In order to do what you are intending, PracticeVO needs to implement the Parcelable interface (http://developer.android.com/reference/android/os/Parcelable.html). Then you can use this version of the putExtra() method: http://developer.android.com/reference/android/content/Intent.html#putExtra(java.lang.String, android.os.Parcelable[]).

Notification fundinProgram = (Notification) getIntent().getSerializableExtra(DETAIL_OBJECT);

implement Serializable in your PracticeVO class file
When sending from an activity:
List<PracticeVO> PracticeVO = new ArrayList<PracticeVO>;
Intent intent = new Intent(SourceActivity.this, TargetActivity.class);
intent.putExtra("PracticeVO", ArrayList<PracticeVO> PracticeVO);
startactivity(PracticeVO);
At the receiver side:
List<Question> questions = new ArrayList<Question>();
questions = (ArrayList<Question>)getIntent().getSerializableExtra("QuestionListExtra");
source: Link

I was able to achieve it this way:
Make your model class (PracticeVO) as well as your Activity class (KlarityHome) implement Serializable.
public class MyClass implements Serializable {...}
In your activity class, store your objects in an ArrayList rather than a List.
Finally, you can do this:
// create intent
Intent homePageIntent = new Intent(SetPreferences.this, KlarityHome.class);
// create your ArrayList and add your item(s)
List<PracticeVO> tempList = new ArrayList<PracticeVO>();
tempList.add(practiceObj);
// add your arraylist to your intent
homePageIntent.putExtra("SelectedPractice", tempList);
// go go go ;-)
startActivity(homePageIntent);
I hope this helps. Merry coding!

Related

Convert Bundle to Integer (Intents)

I am attempting to pass an int through an intent to another class and have managed to successfully pass through the integer however I am unsure as how to convert a Bundle to an Integer.
Code from Intent:
private void nextPage()
{
Intent intent = new Intent(this, Timer.class).putExtra("totalTime", totalTime);
startActivity(intent);
}
Code in Timer class:
Bundle time = getIntent().getExtras();
if(time == null)
{
timeDisp.setText("Failed.");
}
else
{
totalTimeMs = Integer.parseInt(String.valueOf(time));
timeDisp.setText(totalTimeMs);
}
Thanks in advance :)
Intent can hold directly all java primitives types and parcelable/serializable objects.
You may have a confusion that it can also hold Bundles.
Do you really need to put your integer in a Bundle? It can be true for multiple values that logically coupled.
Check Intent API.
If your totalTime is of type int which you pass through putExtra() the you can use:
int time = getIntent().getExtras().getInt("totalTime");
You are not adding your intent to a Bundle, so on the recieving activity you are trying to get data out of an empty Bundle.
You would Add the data to a bundle by:
private void nextPage()
{
Intent intent = new Intent(this, Timer.class);
Bundle b = new Bundle():
b.putString("totalTime", totaltime);
intent.putExtras(b);
startActivity(intent);
}
Then you would retrieve the String from the bundle:
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String time = extras.getString("totalTime");

Pass data object to an Activity from another activity (Fragment -> its Activity-> new Activity)

I have created listFragment class called "EventFragment" and i need to pass data object on its click event to pass drawerActivity class (fragment class) and then i need to pass that object to another activity called EventDisplayActivity class. I could manage get data object to the drawerActivity class but i cant send that to the EventDisplayActivity class.
//DrawerActivity code
#Override
public void OnEventItemClick(ZEvent zEventObject) {
Log.i("URI uri", ""+zEventObject.getEventName());
zEventItem = (ZEvent)zEventObject;
Bundle b = new Bundle();
b.putParcelable("EVENT_ITEM", zEventItem);
Intent i = new Intent(DrawerActivity.this, EventDisplayActivity.class);
i.putExtra("DUMMY","dummytext");
i.putExtras(b);
startActivity(i);
}
// EventDisplayActivity
#Override
protected void onInit(ModelBase... data) {
System.out.println("onInit() Called in Event Display Activity");
SharedPreferences sessionkey = getApplicationContext().getSharedPreferences("session_detail", Context.MODE_PRIVATE);
session_token = sessionkey.getString("session", "");
logged_user_type = sessionkey.getString("user_type", "");
logged_user_id = sessionkey.getString("user_id", "");
Intent i = getIntent();
Bundle extras = i.getExtras();
ZEvent zEventbundle = extras.getParcelable("EVENT_ITEM");
mProposalId = zEventbundle.getProposalID();
String mDummy = getIntent().getStringExtra("DUMMY");
Log.i("id>>>",""+mProposalId +"Dummy"+mDummy);
params = new RequestParams();
params.put("token", session_token);
params.put("proposal_id", mProposalId);
mApiClient.getView(eventViewURL, params, eventResponse);
}
//LOgCat
java.lang.RuntimeException: Unable to start activity
ComponentInfo{gg.zing/gg.zin.zing.events.activities.EventDisplayActivity}: java.lang.NullPointerException
Caused by: java.lang.NullPointerException
at gg.zin.zing.events.activities.EventDisplayActivity.onInit(EventDisplayActivity.java:431)
I assume your ZEvent implements Parcelable...
If it does, then put in in the intent using putExtra (instead of creating new Bundle and using putExtras), and extract the same way using getParcelableExtra.
// Put
final Intent intent = new Intent(context, <class>);
intent.putExtra("MY_EVENT", obj); // <-- Should be parcelable
// Get.
ZEvent obj = intent.getParcelableExtra("MY_EVENT");
You can also define a static attribute in a class which is used to hold the data in static fields.
public class AppData{
public static String user = "Ben";
}
You can use it like this:
public void setUser(String user){
AppData.user = user;
}

Passing an array to activity (Android)

In the activity A, I have built an array q1 of Question and I passed to activity B:
Intent i = new Intent(getApplicationContext(), B.class);
i.putExtra("questions", q1);
startActivity(i);
finish();
In the activity B:
Object c= getIntent().getExtras().getSerializable("questions");
Now, how can I reconvert "c" in an array of Questions? I can not make a cast (Question[])
this will be helpful.
Question[] questions = (Question)context.getIntent().getExtras().get(key)
Your objects need to implement the Parcelable interface.
In your Question class must implement parcelable interface. See the following code,
Question[] questions = //assign value;
Parcelable[] output = new Parcelable[questions.length];
for (int i=questions.length-1; i>=0; --i) {
output[i] = questions[i];
}
Intent i = new Intent(...);
i.putExtra("QuestionArray", output);
//retreiving it from intent
Question[] questions = (Question[])intent.getParcelableArrayExtra("QuestionArray");
In your first activity you can send the array inside a bundle and then in the next activity that was created with the intent you can extract the array list from the bundle.
Bundle b=new Bundle();
b.putStringArrayList("option", optionMod);
Intent i = new Intent(getApplicationContext(), ad45.hw.hwapp.confirmation.class);
i.putExtras(b);
startActivity(i);
Then when you want to read the content in your new activity, create a new array List to store the one that was sent with the intent and extract the array from the bundle:
public void getInfo(){
Bundle extras = getIntent().getExtras();
if (extras != null) {
options = extras.getStringArrayList("option");
}
}
Your Question object must implement the Parcelable interface. You can put only primitive objects or objects that implement Parcelable.

Can I send class as extra with intent?

I'm trying to pass class name with extra, how to do that ?
Intent p = new Intent(StartScreen.this, Setting.class);
p.putExtra(" ",StartScreen.this);
I want to get the class name in Setting class but I don't want it to be String cause I'm going to use this class name like that :
Bundle extras = getIntent().getExtras();
extras.getString("class");
Intent i = new Intent(Setting.this, class);
startActivity(i);
you can use this code
Intent p = new Intent(StartScreen.this, Setting.class);
p.putExtra("class","packagename.classname");
and in setting class
Bundle extras = getIntent().getExtras();
String classname=extras.getString("class");
Class<?> clazz = Class.forName(classname);
Intent i = new Intent(Setting.this, clazz);
startActivity(i);
A tidier way than the accepted answer would be to use Serializable or Parcelable.
Here is an example of how to do it using Serializable:
In your first activity...
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("EXTRA_NEXT_ACTIVITY_CLASS", ThirdActivity.class);
startActivity(intent);
Then in your second activity...
Bundle extras = getIntent().getExtras();
Class nextActivityClass = (Class<Activity>)extras.getSerializable("EXTRA_NEXT_ACTIVITY_CLASS");
Intent intent = new Intent(SecondActivity.this, nextActivityClass);
startActivity(intent);
Doing it with Parcelable is pretty much the same, except you would replace extras.getSerializable("EXTRA_NEXT_ACTIVITY_CLASS") in the above code with extras.getParcelable("EXTRA_NEXT_ACTIVITY_CLASS").
The Parcelable method will be faster, but harder to set up (as you need to make your third Activity implement Parcelable - see http://developer.android.com/reference/android/os/Parcelable.html).

Action before startActivity()

I'm new in Android development and I've a problem when I create my new activity.
I want to use my activity before start it. For example, I have try it:
MyActivity menu = new MyActivity();
menu.setXmppreception(reception);
Intent intent = new Intent(Screen.this,MyActivity.class);
Screen.this.startActivity(intent);
But, my "menu" and "MyActivity.class" aren't the same instance. Consequently I have try it:
MyActivity menu = new MyActivity();
menu.setXmppreception(reception);
Intent intent = new Intent(Screen.this,menu);
Screen.this.startActivity(intent);
But it doesn't work...
Have you a solution for help me?
Thanks for help and sorry for the bad english.
You can't do that like you want, if you are looking to pass data between an activity you must use Extras, and you can pass just Serializable items.
First Context (can be Activity/Service etc)
You have a few options:
1) Use the Bundle from the Intent:
Intent mIntent = new Intent(this, Example.class);
Bundle extras = mIntent.getExtras();
extras.putString(key, value);
2) Create a new Bundle
Intent mIntent = new Intent(this, Example.class);
Bundle mBundle = new Bundle();
mBundle.putString(key, value);
mIntent.putExtras(mBundle);
3) Use the putExtra() shortcut method of the Intent
Intent mIntent = new Intent(this, Example.class);
mIntent.putExtra(key, value);
New Context (can be Activity/Service etc)
Intent myIntent = getIntent(); // this getter is just for example purpose, can differ
if (myIntent !=null && myIntent.getExtras()!=null)
String value = myIntent.getExtras().getString(key);
}
NOTE: Bundles have "get" and "put" methods for all the primitive types, Parcelables, and Serializables. I just used Strings for demonstrational purposes.
you don't have to create the new activity yourself, Android system does it for you.
If you want to go from Screen Activity to MyActivity, you can do this :
Intent intent = new Intent(Screen.this,MyActivity.class);
startActivity(intent);
and then, in you MyClass java file, in the onCreate method, you could do :
this.setXmppreception(reception);
This way, I think you get you wanted, no?

Categories