Passing data from one activity to another in Android [duplicate] - android

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to pass a value from one Activity to another in Android?
I have an activity with a list of titles and their bodies(content) (list6 example from ApiDemos). And I have an activity, where I add a note. When I click on "Add" button, I want the title of my note to appear on the list. Same with body. The problem is, that in List activity there are two String[] arrays with predefined hard-coded titles and bodies. What should I do to be able to add my own new titles with a content instead of having these hard-coded values?
I know I must use intents with startActivityForResult, but that's probably all I know...

You have two option:
1) make the listview and the two arraylists static
This way you can use the same instances of it from the activity with add button and modify the listview as:
FirstActivity.listTitlesArrayList.add(listTitleString);
FirstActivity.listDescriptionArraylist.add(listDescriptionString);//this is probably your note
FirstActivity.listView.invalidateViews();
2)if you want to use intents:
while going to the ListActivity pass data by..
intent.putExtra("Title", listTitleString);
intent.putExtra("Content", listDescriptionString);
startActivity(intent);
and to recover it in second activity use:
title= getIntent().getExtras().getString("Title");
...and so on..

There are several ways to share data between activities.
In your case probably the easiest way is to have a reference to list in Application. This answer summs it up nicelly: Making data obtained in one activity available to all the activities

Related

How to update the UI in android

I have an activity A with a listview and upon selecting some items in the list, and navigating to another activity B with the selected items in the list of Activity A. And made some modifications. After return to A. My screen is not updating with the latest modifications.
Please guide me how to do this. Thank you in advance.
If you have unified data storage for both activities (so that you know that this problem is purely UI issue, because the data itself is updated upon returning from activity B), then you should call this method on your ListView adapter:
yourListView.getAdapter().notifyDataSetChanged()
In order to display what you want, you need to have some TextViews in your other activity and then just add a text to them to display what you need.
When you get the data, just do like this in the onCreate method:
TextView tv = (TextView)inflate.findViewById(R.id.myTextView);
tv.setText(theDataStringYouReceived);

Open several layouts from a single activity (listview)

I created a list of drugs in my main activity using a ListView in Android Studio.
Since drugs are many and have same characteristics (indication, contraindication, posology) I'd like to know if there is an alternative to create an activity for each drug. In other words: is it possible to open different layouts from one single activity? Is it possible to create a "template" layout and insert only the contents (posology and so on...)? I tried with Fragment but I failed miserably. Alternatively, creating a lot of activity can slow down my application? Thank you (I apologyze for my terrible english grammar)
What I would suggest doing is creating something like a DrugDetail activity which you pass information about the drug to. This means instead of creating loads of activities for every drug you just create one activity and pass it all the drugs information.
So what you would do is set an onItemClickListener onto your drug listview the. Inside that listener method have something like this
Intent intent = new Intent(MyActivity.this, DrugDetail.class);
intent.putExtra("drugName", "drugnamestring");
intent.putExtra("drugDescription", "drugDescriptionString");
startActivity(intent);
In your case the best practice is creating base layout (extends common layouts e.g. FrameLayout or RelativeLayout) witch you will inflate in your own class witch will extends ListView class for all items of this custom ListView. When user clicks on list's item it extends and shows him all information about particular drug. This video is all you need, enjoy! http://www.youtube.com/watch?v=mwE61B56pVQ

Android: Dynamically Change Activity Title to Text of Selected List Item

I'm new to Android development.
I created a simple master-detail app that starts with a simple, vertical scrolling list of topics.
When the user selects a topic, a details screen appears, replacing the first screen, with a list of details that pertain to the selected topic.
I want the title for the details screen to show the topic the user has selected on the first page, but haven't been able to solve the problem after working for almost a week.
All I need to know is, Can this be done? Not looking for someone to solve this for me, but maybe a hint or a link to a tutorial that shows how this can be done.
Note: I'd post a drawing of what I want to do, but I'm new here and don't have 10 reputation yet.
Thanks,
SonCoder
Not exactly sure what you want but either way..
-You have a listview. Each view (the data) in the listview should be a represented by a model. (aka a separate class containing specific information that you want to represent for each listitem.
-Write a custom list adapter (extend from base adapter).
http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/
In the getView method of this class you load the the String field of the model that you want in the textview.
-Make sure to use the viewholder pattern in the adapter above. I noticed the example doesnt use one. This speeds up scrolling in the list because there are much fewer calls to findViewById.
-in the list activity set up a View onClick listener. This should create an intent (for launching an activity) or a fragment transaction (for fragments). Send the instance of your entire model (will get from
parent.getAdapter().getItem(position);
in the on click method) into the detail activity.
-if you want to set a textview title just get the textview and set it from the model. It will be the same filed you inflated in the getView method of the adapter.
-if you want to set the titile in the actionbar set:
this.getActionBar().setTitle(title)
This is simple. Just send extra data in the intent that starts the activity and then in the activity's onCreate read the data and then use the setTitle(myString) method from the activity.
setTitle(String title) can be called from anywhere using the activity by the way.
So, your in your listadapter, then you set a listener on your view right? A simple onClickListener on the whole "root" view is just fine.
In the listener you say something in the ways of this:
Intent intent = new Intent(myActivity, MySubActivity.class);
intent.putExtra(key, titleName);
myActivity.startActivity(intent);
Note that the activity reference should be set in the constructor of the adapter and that the "key" String is something you get from your strings.xml. Do not duplicate these in code since if you change one and forget to change the others you might get some wierd NPEs.
Continue in your MySubActivity's onCreate()
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String key = getString(R.string.my_title_key);
String title = intent.getString(key);
setTitle(title);
}
NOTE: I'm not sure of all method names are correct and such but something like this.

Pass fragments between activities

I want to make an application that can support portrait and landscape. The layout has two panes, on the left is the options and the right shows the result. When an option is selected the right pane shows it. But for portrait there is not enough room, so a separate activity is needed. Each option produces a different type of fragment, so I don't want to make an activity for each option when all that changes between activities is what fragment is being added there. I want to pass a fragment from the main activity to the new one, how would I do this?
EDIT: Moved what asker actually wants to top.
If you want to pass data to an Activity when creating it, call a version of Intent.putExtra() on the intent that is used in startActivity(). You can then use getIntent().getStringExtra() to (for example) get a string extra in the activity.
Say you have a piece of string data in your first activity called myString.
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra(EXTRA_NAME_CONSTANT, myString);
startActivity(intent);
Now in your new activity in onCreate you would do:
String myString = this.getIntent()
.getStringExtra(EXTRA_NAME_CONSTANT, "default return value here");
A few notes:
For that EXTRA_NAME_CONSTANT, I do mean to make a string constant of the form "your.package.name.SomeString" for example "com.example.MyString". Personally I'd even use a resource (accessed in the form getString(R.string.extra_my_string)) for the extra's name. They recommend you prefix it with your package name.
You can put and get many types of data from strings to arrays to even serializable data.
Instead of making a separete activity for different layout orientations consider using resource qualifiers to provide alternative layouts.
To summarize, make two layouts in a structure like so:
/res/layout/yourlayout.xml
/res/layout-land/yourlayout.xml
Where both XML files are named the same. Then make your default portrait layout in one and a landscape version in the other.
When you inflate the layout in onCreate (and when it does so automatically on a layout change during runtime) it will select the correct layout for you.
I want to pass a fragment from the main activity to the new one, how would I do this?
You wouldn't. At most, you would follow #Ribose's answer -- pass a flag into the activity via an extra to indicate what set of fragments to create.

How to use intent between tabs in java/Android?

I would need to know how to handle the intent between tabs. For example, I have a tab activity with two tabs. First on content is a text view. another one is a map view. When i click that text view it redirects to the tab2. it can be easily achieved by setCurrentTab(1) or setCurrentTabByTag("tab2") methods. But i want to pass lat and long values to that Map Activity to drop pin. What is the better way to use intents or getter/setter in java? What do you prefer? if your answer is "Intents". How?
A interesting problem. I understand it that you want to change to the second tab on a click in the first tabview but also pass special data to the second tab that is dependent on the action in the first tab.
I would generally start your views inside the tabs with an activity. However this is done at the moment the tab host is configured. That means both intents the one for the activity that lets the user choose lat long and the one that shows lat long are openend at the same time.
Therefore you can't add the information to the intent used to intialize the tab host.
I don't like the solution but the only thing that comes to my mind (using different activities for the tabs) is using a custom application that stores a reference to an object containing the data that you need to update the view in the second tab. You have to extend application with an own class and add this class in you manifest, now you can call getApplication in the first tab cast it to your application class set lat and long just before you call setCurrentTab. In the second tab you can call getApplication() again and you will then get the application object that is the same for every activity at every moment of your app running. You then have cast it again to your application object and retrieve lat and long value. See this page in the google refs on how to use a custom application class.
To use a custom application class add the following to your application tag in your manifest:
<application
...
android:name=".somepackage.CustomAppClass"
This will tell Android to instantiate the CustomAppClass as your Application class at the moment your app starts. You need to extend Application to avoid errors on start up.
Another solution but not the one I would prefer is to initialize the views yourself and initialize the tabhost with views and not activities. With a map view in one of the tabs this could be very memory heavy.
If you want to pass values between activities, I suggest looking at
http://developer.android.com/reference/android/content/SharedPreferences.html
the best way to get values from one itent to another.
With sharedPrefrences, there is only one instance of the class for the whole application, which means that you can store values in the files, switch intents or activities, and then recall those sharedPrefrence files that have the data in them.
The only downside is that you have to pass primitive types (int, string, boolean) but I'm sure you'll figure ways around this :).
I dont see the Problem here:
Maybe its a little bit of hackish but following Code works for me:
public boolean onClick(View v) {
//get your data you wanna send.
//If it is an Object it would be good if it is Parcelable
Object o = getYourData();
// or Parcelable p = getYourData
Activity activity = getParent();
//I'm assuming were inside an Activity which is started by TabActivity
if (activity instanceof TabActivity){
TabActivity ta = (TabActivity)activity;
//now determine the Tab you wanna start
ta.getTabHost().setCurrentTabByTag("yourTag");
//or ta.getTabHost().setCurrentTab(yourID);
Activity current = ta.getCurrentActivity();
//check if the Activity is the one you wanna start
if (current instanceof YOUR_ACTIVITY_YOU_WANNA_START){
//Cast to your Activity
YOUR_ACTIVITY_YOU_WANNA_START yourActivity =
(YOUR_ACTIVITY_YOU_WANNA_START)current;
// you only need to put Data inside your Intent
Intent intent = new Intent();
intent.putExtra("EXTRA_DATA_TAG", o);
//your Activity must Override onNewIntent and make it public,
//or simply add another method
//with whatever You like as parameter
yourActivity.onNewIntent(intent);
return true;
}
}
return false;
}
this way you don't have to mess with Application, SharedPrefs or other unnessesary stuff mentioned here
If you make the intent you are using to start the second tab activity a global intent.
You can then add extra's to this intent in the onPause() of the first tab. Note: you have to define all your tabs in separate activitys than your tabhost TabActivity as this activity's onPause() is never called.
This also help's with the answer above, if you are using a global variable saved in your activity that extends application, you can set this in the onPause() as it is fired before the activity is switched, which you might find an issue if setting this elsewhere

Categories

Resources