Refer activity layout from another activity - android

I have been developing web apps for a few years now, and just decided to start my way with android development using this book: Beginning Android Application Development of wrox.
At some point the book explains how to get a result from an intent (under the title "Returning results from an intent").
These are the steps:
The book describes how to change the main.xml layout file by adding some new controls.
The book describes how to change the activity that will be the second one (​Activity2), it says that this activity should refer to the layout of a different activity by calling
​Button btn = (Button) findViewById(R.id.btn_OK);
since btn_OK was defined in the layout of the main activity (and not the one of ​Activity2, it is in main.xml) the method returns null.
The official documentation describes:
public View findViewById (int id)
Since: API Level 1
Finds a view that was identified by the id attribute from the XML that was processed in onCreate(Bundle).
So am I missing something here or is this book incorrect?

Using findViewById() in an Activity searches in the layout xml file that was used in setContentView() in onCreate().
If the two activities use different layout.xml files the button inside those files may have the same id and will not be confused (by findViewById()).

In Activity1
public static Button btn;
void onCreate(...) {
btn = (Button) findViewById(R.id.btn_OK);
}
In Activity2:
​Button btn = Activity1.btn;
Note: when you use Intent to navigate to Activity2, do not call activity1.finish(), as this will destroy btn;

Related

Too many Activities in Android App. Any alternatives?

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

A button which goes onto an Activity

I have been trying to figure this thing out with no luck in eclipse. I have created 3 screens. One being the main menu which a button leading to another button which then leads to an Activity. I can get the button from the main menu to lead onto the button onto the second screen but i can't get the second button to lead onto the third screen.
Can anybody help me?
appproject
You should really post some code so we can help you...but it seems like you need to look at your onClick() method for the second button.
Providing you have three separate Activities for each of these three screens (I'll call them ActivityA, ActivityB, and ActivityC), you'll also probably need an XML layout for each. There are ways of doing it without an XML layout, but for now just stick with that.
The next thing is you want to make sure your Button is initialized properly. ActivityB should look like:
public class ActivityB extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b);
Button b = new (Button) findViewById(R.id.button2);
b.setOnClickListener(new OnClickListener() {
#Override
protected void onClick() {
startActivity(new Intent(this, ActivityC.class);
}
});
}
The first thing you should do is check to make sure your button functions in a way similar to how I've described here. If that doesn't change anything, make sure you are initializing your Button in accordance to how it is defined in the layout XML. You must use an id for a Button that is in the same XML layout as the one you set in setContentView(). If not, it will do nothing, no matter what you put in the onClick() method.
I hope that helps!!

Double Activity window when using intent for achartengine graph

Development Environment: Eclipse 3.7.0
Developing: Android 3.2 application for Market Place
Using: aChartEngine 0.7.0
I'm new to the development scene but have done a bit of coding in the past various languages, I've created the ZopaStats(on Marketplace) app, but I'm now trying to convert a text based stats page to be displayed in a bar graph using achartengine.
I can get the graph to display from an activity via another activity i.e.:
Intent achartIntent = new TemperatureChart().execute(this);
startActivity(achartIntent);
but this gives me an additional activity screen i.e.:
Main Screen -> 1st Activity (Original Text Stats View) -> 2nd Activity (Graph)
Therefore, with I hit back on the graph screen, I get the blank 1st activity screen.
I hope I'm making sense here.
So what I tried to do was launch the activity from the Main Screen (i.e. my Main class) e.g.
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent achartIntent = new TemperatureChart().execute(this);
startActivity(achartIntent);
}
});
But eclipse gives me the following error in the code:
The method execute(Context) in the type TemperatureChart is not applicable for the arguments new (View.OnClickListener(){}}
I've tried letting Eclipse change the method but this then causes other problems, so I think what I'm really looking for (in a round about way) is to find out what the difference is when I can try to start the activity from another Activity class rather than starting it from the main class.
I apologise for the misuse of terms etc, as I say I'm new. I've been looking at this for a few days now but the Intent and Activity documentation doesn't help me much so I just need a few pointers.
Thanks,
In your example, the this reference that you're passing to execute() is your annonymous inner subclass of OnClickListener. This is not a context object, which is what eclipse is complaining about.
Rather, you want to pass in the activity instance. Assuming the code snippet you posted lives in a class named MyExampleActivity, then you can use MyExampleActivity.this from inside the inner class to access the instance of the containing class. You should be able to pass that to TemperatureChart.execute()
There is no difference in starting an activity from the main activity or from any other activity. You just create an intent, and call startActivity on it.
For completeness, the new code is this:
N.B. My original class is called ZopaStats.class
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent achartIntent = new MarketZopaGraph().execute(ZopaStats.this);
startActivity(achartIntent);
}
});
This works great, only a single Activity windows, once again many thanks for the quick response, in record time ;)
when we use achartengine to draw graph in includes it own activity...i.e.org.achartengine.GraphicalActivity..
when we press back it shows own activity which is used to show graph..to hide these activity call finish() method on onPause() method.

Create new "screens" dynamically

I have an application that gets information from a database and it creates ImageButtons dynamically. What I want is, when I click a dynamically created ImageButton, I want it to make a search in my database (which I know how to do) and then create a new activity (or screen) with new ImageButtons created dynamically, too.
How can I do this?
You cannot create activities without declaring them in the manifest file. You can either call setContentView after creating the new layout(I do not recomend this.).
Or use the viewflipper and add the the different layouts as childs to it. So you can use the viewflipper to switch between layouts.
Best option is to read the android developer documentation on how Intents can be used to launch a New Activity
An Intent object is passed to Context.startActivity() or
Activity.startActivityForResult() to launch an activity or
get an existing activity to do something new.
(It can also be passed to Activity.setResult() to return
information to the activity that called startActivityForResult().)
ImageButton imagebutton=new ImageButton(this);
imagebutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
getDataFromDataBase();//In this method you get data from database
Intent intent=new Intent(currentactivity.this,newactivity.class);//start new screen.. in this you can create imagebutton dynamically
startActivity(intent);
finish();
}
});
just execute the code that you have inside your onCreate (wrap it in an init(Params param) method), and call that inside your onClickListener. of course exclude the setContentView and findViewById's.

Changing a textview in a separate activity in android

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.

Categories

Resources