Passing an array to activity (Android) - java

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.

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");

how to pass list of objects through intent

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!

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).

How to pass String from 2 activities to one?

I have two activitys with lists.
One for tablet's and one for regular density phones.
When an item in the list is clicked it launches the same activity for either activity with list's.
The problem is when an item is clicked i have getter and setter class that gets the URL for a particular item and passes it to the launching activity like this...
private String URL = null;
try{
URL = com.fttech.AbstractFeedsActivity.feed_url;
}
catch(IllegalArgumentException e){
e.printStackTrace();
URL = com.fttech.ItemsActivity.url;
}
As you see what i tried to do is try and catch.
So if the first one isnt found then the second one will be retrieved.
But it doesnt seem to work.
It returns null each time.
For what i have describe what is the best way to implement this?
Is my way logic? Or is there a better way.
Thanks
Try this,
private String URL = null;
try{
URL = com.fttech.AbstractFeedsActivity.feed_url;
if(TextUtils.isEmpty(URL)){
URL = com.fttech.ItemsActivity.url;
// Pass this URL
}
else{
// If its not empty then it will pass the first URL
}
}
catch(IllegalArgumentException e){
e.printStackTrace();
}
No need to pass String to 2 activities, if you want to just pass strings to one or as many activities as you want, just put them in SharedPreferences or declare a variable in static class and then set/get it whenever you want.
Passing values from one Activity to another:
Intent intent = new Intent(context, CalledActivity.class);
intent.putExtra(key, value);
startActivity(intent);
If you want some data back from called Activity then you can use startActivityForResult() as:
Intent intent = new Intent(context, CalledActivity.class);
intent.putExtra(key, value);
startActivityForResult(intent, requestCode);
In called activity you can set data as:
setResult(RESULT_OK, intent);
Note: Here you set the value in intent and pass it to setResult().
On returning back to calling Activity you can get data by overriding:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
//Get data from Intent "data" and do your task here....
}
}
Note: You can pass primitive data type values thru Intent and if you want to pass other types then you have to use Bundle like this.
Bundle data = new Bundle();
data.putIntArray(key, value);
//same way you can set other values.......
//Now set this Bundle value to Intent as you do for primitive type....
Intent intent = new Intent(context, CalledActivity.class);
intent.putExtra(data);
startActivity(intent);
Receiving data in Activity:
//For primitive values:
DataType var_name = getIntent().getExtras().get(key);
//For Bundle values:
Bundle var_name = getIntent().getExtras().getBundle(key);

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