Declare textView in program containing multiple xml files (android) - java

I'm just beginning to learn to develop android apps, using eclipse.
I created multiple .xml files and put a textView in each one. However, they are all called textView1. So in my main activity, if I want to declare a textView, like
TextView hello = (TextView)findViewById(R.id.textView1);
how will the compiler know which xml file to look at? How should I specify?

In the method
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
here you are setting one xml to your activity.
and when you are declaring
TextView hello = (TextView)findViewById(R.id.textView1);
so textview1 of main.xml will called.

When you specify a file in the onCreate using setContentView, it knows which xml file you are talking about

You dont need to worry about that. Android system is smart enough to find the exact id.Android gets the view id from the layout you specify in setContentView() method.
So feel free to use same id in other xml layout file.
Note:--
In same xml file, id of any View should be unique.

Related

Why does the change in position of the setContentView change the behavior of the the app?

When I place "setContentView" above the "NumbersClickListners" line the app works as expected.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NumbersClickListners numbersClickListners = new NumbersClickListners();
TextView numbers = (TextView) findViewById(R.id.numbers);
numbers.setOnClickListener(numbersClickListners);
}
But as soon as the "setContentView" is placed below the three lines starting with "NumbersClickListners" the app crashes. The code looks like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
NumbersClickListners numbersClickListners = new NumbersClickListners();
TextView numbers = (TextView) findViewById(R.id.numbers);
numbers.setOnClickListener(numbersClickListners);
setContentView(R.layout.activity_main);
}
I'm pretty much unsure of the reason for this behavior. Can anybody help me with that please?
Let's look at the life of layout.
First of all, you have to create it by declaring XML file, where you do your design in a user-friendly way and name the elements according to your needs.
Now your layout is just a file, that Android doesn't really care about for performance reasons.
Next thing you wanna do is use your layout. To do that your file needs to be converted to internal structure of objects known as ViewGroup and Views.
This process is called inflating. That's the point where the system can find the views for you by calling findViewById().
So in the second snippet you ask activity to find you a button, which is not inflated. That leads to throwing exception.
Generally speaking, first thing you want to do in the onCreate is to call setContentView().

How do I change the main xml file from another activity?

I am very new to Java. I am doing a school project at the moment and I have my main activity, then I have a settings activity. I am trying to modify the xml from the main activity with the settings activity. I am able to modify the settings xml file with the settings.java, but I would like to modify the main activity xml with settings.java
public class Settings extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
// Get the Intent that started this activity and extract the string
Switch switchButton;
final RelativeLayout mRelativeLayout = (RelativeLayout) findViewById(R.id.activity_settings);
final RelativeLayout mRelativeLayoutMain = (RelativeLayout) findViewById(R.id.activity_main);
switchButton = (Switch) findViewById(R.id.switch1);
switchButton.setChecked(true);
switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean bChecked) {
if (bChecked) {
mRelativeLayoutMain.setBackgroundColor(Color.GRAY);
mRelativeLayout.setBackgroundColor(Color.GRAY);
} else {
mRelativeLayoutMain.setBackgroundColor(Color.WHITE);
mRelativeLayout.setBackgroundColor(Color.WHITE);
}
}
});
if (switchButton.isChecked()) {
mRelativeLayoutMain.setBackgroundColor(Color.GRAY);
mRelativeLayout.setBackgroundColor(Color.GRAY);
} else {
mRelativeLayoutMain.setBackgroundColor(Color.WHITE);
mRelativeLayout.setBackgroundColor(Color.WHITE);
}}
public void toast1(View view) {
android.widget.Toast.makeText(this, "Created by Cody Walls and Tommy Serfas", android.widget.Toast.LENGTH_LONG).show();
}
/*public void switch1(View view) {
ScrollView mScrollView = (ScrollView) findViewById(R.id.scrollView);
mScrollView.setBackgroundColor(Color.GRAY);
}*/
}
In the Code I am trying to change the background of the main activity xml with :
mRelativeLayoutMain.setBackgroundColor(Color.GRAY);
and when I run the app and click the intent it will crash with the error:
"java.lang.NullPointerException: Attempt to invoke virtual method
'void android.widget.RelativeLayout.setBackgroundColor(int)' on a null
object reference"
I think the easiest way is to create an PreferenceManager.SharedPreferences, in which I recommend you to store current app data. This will help you not to loose any changes in app after you exit the it. Here is short instructions:
Create button in settings activity which will change something in main activity.
Create onClickListener for your button.
Use .SharedPreferences to store was you button clicked or not. (I recommend storing boolean variables, this way you can store was button clicked or not.)
I both of your activities in onCreate method call .getSharedPreferences to read saved app values. (I mean to read was the button clicked or not.)
Use app values you got from 4. to change any element in activity. (For example if you stored that button was clicked, then change some TextView text or etc.)
I hope you understood the idea.
Link to the Android developer tutorial about App key values storing & saving
Link to the StackOverflow much easier explanation & examples
There are a couple of ways of doing this (Some of which depends on how you are switching back and forth from each activity). It also depends on what things you are changing.
From your settings page, as you are changing different settings, you'll save this content within Preferences. (You can see more how to use Preferences here: https://examples.javacodegeeks.com/android/core/ui/settings/android-settings-example/ or by just Googling it).
On you main activity, depending on how you come back to it (onStart most likely), you can setup the things you need to programmatically.
So, you may need to do a little research on the Android lifecycle and how each cycle works (https://developer.android.com/guide/components/activities/activity-lifecycle.html), how to program the UI programmatically through Java (http://startandroid.ru/en/lessons/220-lesson-16-creating-layout-programmatically-layoutparams.html), and the Preferences Android library to save certain settings.
The xml isn't meant to be "altered". You can change the UI programmatically. It's possible to build an Android app without any xml. When Android was first built, it didn't use the xml to create the UI. It was all done through Java. It was then added to use xml to create your activities or fragments or any UI component. This made things easier for more static activities or activities with very little dynamic content.

How to handle exception while clicking link using textview in android

I am working on an android project in which i have to add links i am following the given below example.. But when i am clicking on the link neither it is highlighting nor i am able to access the link. Clicking on the link is causing an exception which says
android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
I want to open the link in the browser when i am clicking on the link.How to do it efficiently?. I am expecting an answer soon !Thank you
NB: i am using a dynamic textview in my actual project
public class StackOverflowActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView link = new TextView(getApplicationContext);
String linkText = "Visit the <a href='http://stackoverflow.com'>StackOverflow</a> web page.";
link.setText(Html.fromHtml(linkText));
link.setMovementMethod(LinkMovementMethod.getInstance());
}
Use android:autoLink="web" in your TextView xml. And if it does not work, try android:linksClickable="true"
Based on your error, if using dynamic TextView make sure you refer your view with this object as
TextView yourView = new TextView(this);
this refers to your Activity context where I think you might have made a little mistake.
You should not use getApplicationContext for creating a view with Activity context.
I believe you have to inflate the layout that contains your TextView before you can use it, like so:
getActivity().getLayoutInflater()

Error caused when converting android activity based app to fragment based

I am new to Android Development and I have a simple list app which I have been asked to create.I have had no problems having the app as activity based however I have to extend the functionality and use fragments for a 'universal' app. My main activity is:
I was able to successfully compile your code by taking the following steps:
It looks like this line is the problem (inside Main.java):
contactCursor = contactDBAdapter.getAllContactsCursor();
I looked at how your contactDBAdapter gets initialized and it turns out you initialize it after you setContentView for your activity. However, your view involves calls to contactDBAdapter. So in Main.java you need to move the following two lines to the TOP of the onCreate window:
public void onCreate(Bundle savedInstanceState)
{
contactDBAdapter = new ContactDBAdapter(this);
contactDBAdapter.open();
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
....
}
Furthermore, the following line in Main.java needs to be removed (or commented out):
contact.clear();
Also, I had to make two further changes to how you call ListView
In list_view.xml, the way you identify a ListView for Android is :
android:id="#+id/android:list"
In ContactListFragment.java, then call the ListView this way :
parent.myListView = (ListView)v.findViewById(android.R.id.list);
have you not just tried using the Eclipse Template which set up everything for you just copy in your existing code?
File>New>Android Application Project then under the Create Activity Step select
Your Fragment class needs an empty default constructor. See Android Reference

Android development toggling TextView visibility

Im having some trouble with setting textview to invisible/visible.
basicly i want this to happen when an on/off button has been clicked.
what i did is kind of like
textview.setVisibility(TextView.VISIBLE);
textview.setVisibility(TextView.INVISIBLE);
when i try executing this the emultor says that the app has stopped unexcpetedly
Are you building this from XML or programmatically?
I would make it with an XML file then when the Activity runs change the property. Be sure to use setContentView(R.layout.main); before you try to get the TextView with findViewById(...).
Call .setVisibility(View.GONE); on the TextView to hide it.
Call .setVisibility(View.VISIBLE); to on the TextView to show it.
I have an example that does something like this. You can see the code here: https://github.com/ethankhall/Morse-Messenger/blob/master/src/com/kopysoft/MorseMessenger/Translate.java
Without more code or a stack trace, it's hard to say, but it sounds like you haven't initialized the text view. Here's how to do it:
TextView myTextView = (TextView) findViewById(R.id.tv_text);
Where 'tv_text' is the id of the textview as defined in the xml layout file.
Hope that helped!
Read about DDMS and logcat to obtain a stacktrace and to see what the problem is: http://developer.android.com/guide/developing/debugging/debugging-projects.html
This is what you are looking for:

Categories