I have a log in page that pulls information from a data base, I then want to use this some of this information to populate different textviews on a new page/activity. I can get a textview to change on the activity where I have my submit button, but when I try to change the textview on my second activity, it just crashed (The application has stopped unexpectedly).
Here's my code for changing the textview (where txtID is my textview on a separate activity)
TextView test2 = (TextView) findViewById(R.id.txtID);
test2.setText(test);
my xml for seperate activity
<TextView android:text="TextView" android:id="#+id/txtID"
android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
Oh, I'm using a tableview for my login page, then tabs for my the rest of my pages. I'm pretty new to this, so sorry if this is something simple, but any help would be greatly appreciated!! :-)
You don't want to directly touch the UI elements of another Activity. You can make use of bundles to pass information back and forth. Here is an example:
Say we have Activity A, and it has some information as a String it wants to pass to become the text of a TextView in Activity B.
//Setup our test data
String test = "Some text";
//Setup the bundle that will be passed
Bundle b = new Bundle();
b.putString("Some Key", test);
//Setup the Intent that will start the next Activity
Intent nextActivity = new Intent(this, ActivityB.class);
//Assumes this references this instance of Activity A
nextActivity.putExtras(b);
this.startActivity(nextActivity);
So now in the onCreate method for Activity B, we can get that String and assign it as the text to the TextView like you have
public void onCreate(Bundled savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); //Setup some layout, set to your own
String test = getIntent().getExtras().getString("Some Key");
TextView test2 = (TextView) findViewById(R.id.txtID);
test2.setText(test);
}
I'd probably let each separate Activity take care of its own display, and not try to have Activity 1 directly update the display of Activity 2, which is kind of what it looks like you were doing.
The Notepad Tutorial demonstrates an application with two Activities, where one Activity calls another, passing in data. (Take a look at onListItemClick in Notepadv3.) You could maybe follow this model to pass data from Activity 1 to Activity 2, where Activity 2 then takes care of its proper display, using the data it received.
If you're still having problems (like your application crashing), then please post the complete minimal code necessary to replicate your problem. Note the Notepad Tutorial and the Hello, World Tutorial include steps for debugging, which might help you isolate the exact problem.
Andy... If you try to directly touch a UI widget in another activity, your app will crash. Been there, done that accidentally. Instead, consider passing an immutable stateful object between the activities. This can be done using startActivityForResult for instance. I have some sample code here.
Related
I am creating my first app. In this app, I have an expandable list with many items. When I select any of these items, I want several paragraphs to be displayed. Do I need to create an Activity for each of these items if text is the only thing I want displayed? I know that there has to be an easier way. I did create it like this at first and it seemed very bulky (30+ activities), so now I have it set up so that when an item is selected, the setContentView opens the corresponding layout with the text that needs to be displayed. This works but there is a catch, whenever I hit the back button, it takes me back to my main activity class and not my expandable list class. I want the user to be able to go back and select something else from the list. Any guidance as to what I need to do would be appreciated.
I would suggest creating string resources for each item you would like to display, then creating one activity with a TextView. Then, instead of creating new intents for each activity, create an intent that goes to the new activity, and add an extra that contains the text for the TextView. For example:
Activity1:
myButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
Intent intent = new Intent(this, ParagraphView.class);
intent.putExtra("textData", getResources().getString(R.string.myText));
getBaseContext().startActivity(intent);
}
});
In the onCreate of the viewer, add this to get your TextView:
Intent intent = getIntent();
String textData = intent.getStringExtra("text");
Now, we need to write the text into the TextView:
TextView tv = (TextView) findViewById(R.id.myTextView);
tv.setText(textData);
All you have to to is set up your string resources and button click listeners. You may consider this easier than having lots of activities (it's definitely easier to manage entries this way) but does require a bit of setup.
Edit: Thanks to #ianhanniballake for pointing out a much better way (I don't even know what I was thinking at the time...)
Edit2: Wow, I REALLY messed up my code. (Hopefully) Fixed now
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.
My app has 2 layouts (main layout) and (preference (prefs) layout).
When the MainActivity loads, I set setContentView(R.layout.main); - main layout
I need to then set text for a TextView in the preference layout, but it never gets set.
LayoutInflater factory = getLayoutInflater();
View inflate = factory.inflate(R.layout.prefs, null);
TextView eSerial = (TextView) inflate.findViewById(R.id.editTextSerial);
mSerial = "Test";
eSerial.setText(mSerial);
The way I get to the preference page is with a menu and then the page loads up with no change to TextView
I have searched and not found an answer yet.
Please help.
Thank you.
When the menu kicks off your prefs activity, you can populate the view with the values. user1853479 points out one way of doing this, which is to add the values to an intent. Assuming you want to store these prefs for future runs, you can also set any that for that specific run and save them in your local store. Another method is to create a singleton to store your settings, load it when your app starts, modify and save as needed, and access it from any of your activities.
Short answer: You can't do this.
Long answer:
If you are launching the preference page yourself, you must be creating an Intent to do so. Call putExtra() to store your text inside that intent. In your PreferenceActivity, call getIntent().getStringExtra() to get the text, then put it in your TextView.
I am calling an activity from within itself - basically i've a list of new storys and two filter buttons that when clicked restart the activity with an intent passed that changes the news stories.
When i run the app it works, but for a second i get the old activity UI while the app reads from the new xml feed and then the UI updates. Is there any way to stop this from happening and get the activity to restart cold.
here's the code I am currently attaching to the onclicklistener
public void openFootballNews(View v) {
Intent i = new Intent(this, News_Landing.class); // News_landing class is the class this code is in
Bundle bundle = new Bundle();
bundle.putString("code", "football"); // this, if set, changes the xml feed to read
i.putExtras(bundle);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
this.onCreate(null); //this has halved the time the old UI is on the screen for but I cant get rid of it completely
startActivity(i);
}
any help would be great, thanks!
Starting an activity from itself doesn't make much sense (unless your aim is to do something esoterically recursive ;) ). Also, I may be mistaken, but I believe activities are kept in a stack so that as you flip between news stories, you're piling up one nearly-identical activity after another. I'd similarly think calling onCreate() by hand is bad form.
Would need to see all of your code, but my guess is that you are reading your feed and creating your list inside onCreate(), and that your best bet is to refactor that into a openNews(String sport) method, which you call once in onCreate() and again in your listener(s).
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