Is it safe to edit r.java in my case? - java

I have this line of code:
Button button = (Button) findViewById(R.id.view);
Which gives the following error:
id cannot be resolved or is not a field
That error is logical, because I have nothing what needs an Id in R.java yet, and therefore Id is missing. This will be generated when I execute the code (because I make buttons at onCreate(), and they get Id's). But Eclipse won't let me run before I fix the problem. So is it safe to add this line of code to R.java:
public static final class id {
}
Or maybe there is another sloution?

If you create buttons in onCreate, they aren't added to the resources. The resources are fixed from the moment you build your APK.
Surely if you created the button, you already have the Button object and don't need to look for it in the resources anyway?

No. Anything you add to R.java will get deleted the next time you build. It is an auto-generated file.

You cannot append R.java. But if there is anything that you want to add you can create another file of your own (like Rcustom.java), keep your stuff in it and import it wherever you use it.

findViewById() is used when you are referencing an XML layout that was usually set by setContentView(), or inflated with LayoutInflater.
So if you have a Button in your main.xml layout, with the id of "view", you would do the following in your Activity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.view);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Respond to click here
}
});
}

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.

OnClick ButterKnife, nothing happens

I'm trying to use ButterKnife to onClick. I did the code bellow and nothing happens, I've watched tutorials all over the internet, and they do the same thing as I did.
Here is the code
#BindView(R.id.startButton) protected ImageButton mStartButton;
#OnClick(R.id.startButton)
public void startTest(){
Toast.makeText(this, "testing", Toast.LENGTH_LONG).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(MainActivity.this);
}
And if I put the method startTest(); inside the OnCreate, the toast is called when the app runs for the first time, what shows that the ButterKnife is working. But I need that to happen only when the button is clicked.
Thanks
You mentioned that you have compile 'com.jakewharton:butterknife:8.4.0' in your build.gradle file. I think you may be missing the corresponding compiler. Add this to your dependencies section:
annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'
I think your onCreate method should be public. Try it.
The only two reason i can see are either
'protected' needs to be removed from your ImageView
or
'startButton' is not actually defined in activity_main

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 in using a checkbox between multiple activities

I am trying to write a settings activity in an application on Eclipse. In the Main Activity, it has a button that runs a certain command. In the settings activity, I want to have a checkbox that when checked, changes what the button in the Main Activity runs when it is tapped. Right now, I have it so that when the checkbox is checked, it changes the value of a boolean and passes it to the main activity. When the button in the main activity is tapped, it checks to see if the boolean is true or false. All of this works perfectly, but when I return to the settings activity after that, the checkbox is unchecked. What should I do to have it stay checked after I go to another activity?
I believe the comment I posted is the answer:
You need to save the state of the activity. This information can be found at Saving Android Activity state using Save Instance State but in short you need to override these two methods:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
}
and
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
you can use shared preference in android to store state. take look at this
http://developer.android.com/guide/topics/data/data-storage.html#pref
and
http://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/

Categories