I have experience with programming languages but am a bit new to android programming.
I have a program with some fields that function as labels(textview), buttons, and data entry(edittext).
Whenever i declare them at the beginning of the program out of any methods(but in the class of course), when I start my application it crashes and simulation gives a "unfortunately, your program has stopped" alert.
Eclipse doesn't give any errors for the declaration and i did use the same way for defining regular variables with no issue. It also gives the same error when i declare a mediaplayer object in the class body.
Does anyone know why it gives error?
And is there another way to declare global objects like edittext, viewtext, etc... Declaring them over and over again in methods sounds weird to me.
Thank you!!
public class TrainerActivity extends Activity {
Button stopTimer = (Button)findViewById(R.id.StopTimer);
Button startTimer = (Button)findViewById(R.id.StartTimer);
EditText totalTime = (EditText)findViewById(R.id.TotalTime);
EditText enterMin = (EditText)findViewById(R.id.EnterMin);
EditText enterSec = (EditText)findViewById(R.id.EnterSec);
private boolean breaker = false;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startTimer.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Button_StartTimer();
}
});
stopTimer.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Button_StopTimer();
}
});
}
Without seeing example code of what you're trying it's impossible to say for definite (we don't do mind-reading here). But let me guess, you're doing something like this?...
public class MyActivity extends Activity {
TextView tv1; // This is fine.
TextView tv2 = (TextView) findViewById(R.id.textview2); // Don't do this.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv1 = (TextView) findViewById(R.id.textview1); // This is fine
tv1.setText("Some text"); // This works
tv2.setText("Some text"); // NullPointerException here
}
}
The tv2.setText(...) will fail because you used findViewById(...) BEFORE you call setContenetView(...) and as a result, tv2 will be null.
It's quite acceptable to declare your widgets as instance members in your Activity but don't try to use findViewById(...) until AFTER you have set your content view.
try declaring the widget objects names only outside the onCreate() method
Button stopTimer;
Button startTimer;
EditText totalTime;
EditText enterMin;
EditText enterSec;
then initialise them after setContentView() inside onCreate()
setContentView(R.layout.main);
stopTimer = (Button)findViewById(R.id.StopTimer);
startTimer = (Button)findViewById(R.id.StartTimer);
totalTime = (EditText)findViewById(R.id.TotalTime);
enterMin = (EditText)findViewById(R.id.EnterMin);
enterSec = (EditText)findViewById(R.id.EnterSec);
Can you post a bit of sample code that illustrates the issue? It is fine to declare a member variable that is an EditText or TextView in the class.
logcat(in DDMS) should be give you some info about the error as well. If you are using eclipse there is a tab for DDMS, if not you can just run DDMS from a command line look at the logcat tab and launch your app (with your phone plugged in via usb, of course.) You should be able to see the actual error being reported.
You can declare these variables inside the Class body or inside the method body. In the former case, the variables are global and thus can be accessed within the whole class; in the latter case, they are local and thus can be only accessed within that method. Both of them could be commonly seen in proramming.
In Android, the typical application is that you declare the variables in the Class body and instantiate them in the onCreate() method. Something like this:
public Class MyClass extends Activity{
TextView label;// so this variable can be accessed within any methods in this Class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(Bundle savedInstanceState);
setContentView(R.layout.main) // load the layout of the activity
label=(TextView)findViewById(R.id.<the TextView id defined in the layout file>); //this variable get instantiated. From now on you can manipulate it anywhere inside the class.
Button submit=(Button)findViewById(R.id.<the Button id defined in the layout file>);//you declared and instantiated it, but it could only be used within this method since you declared it here.
}
}
If you just declare a variable in the Class body,in most caeses, you can't use it until you instantiate it, because they are null before the instantiation. I think this is why you have problems. Please post the logcat so we can specify the real problem.
Related
I am very much new to Android world. I was just trying to check how a global variable can be used in onCreate() method in Android, whenever i tried doing so, it closed abruptly. When I displayed some random text in the code, it was displayed successfully.
Here's my code:
public class MyActivity extends AppCompatActivity
{
public static int num_i=0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_beer);
TextView tv = findViewById(R.id.textView);
tv.setText(num_i);
num_i++;
}
}
Please help me in this.
setText(CharSequence text)
Sets the text to be displayed. it takes String as a parameter not a number
Sample : tv.setText("PREM");
setText(int resid)
Sets the text to be displayed using a string resource identifier.
Sample : tv.setText(R.string.app_name);
first you have to convert your int value in to a String
Try this use
tv.setText(String.valueOf(num_i));
or
tv.setText(num_i+"");
instead of this
tv.setText(num_i);
Don't use tv.setText() with a number as parameter. Try using String.valueOf(num_i).
So in your case:
tv.setText(String.valueOf(num_i)) or tv.setText(num_i + "");
I am trying to define global objects using the application class.
I therefore define the following class.
public class MyApplication extends Application {
private MyObject myObject=new MyObject();
public MyObject getMyObject(){
return this.myObject;
}
}
Then, I use it in an activity, but I get an error (Cannot resolve method getApplication()):
public class AnActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mood);
Button buttonMusic=(Button) findViewById(R.id.button5);
buttonMusic.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MyApplication myApplication = ((MyApplication)this.getApplication());
Toast.makeText(MoodActivity.this, "playing music", Toast.LENGTH_SHORT).show();
}
});
}
}
I have no clue why I get this error, as it for example works when calling the getApplication() in another activity.
I'm pretty new to Android and Java, so please excuse the ingenuity of the question.
UPDATE
Then I do MyObject myObject=myApplication.getMyObject(); and I don't get any compilation issue but the app dies as soon as I get in that activity.
As I understand it is not advised to use the Application class for such use, what would be a good alternative?
You're getting this error because you call this.getApplication() inside the View.OnClickListener. Because of this, this now references the listener and not the activity.
To do what you need, just create a Context object outside of the listener in your activity's onCreate method and assign this to it. And, inside the listener, use context instead of this. Something like this :-
public class AnActivity extends Activity {
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mood);
context = this;
Button buttonMusic=(Button) findViewById(R.id.button5);
buttonMusic.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MyApplication myApplication = ((MyApplication)context.getApplication());//Changed "the" to "context"
Toast.makeText(MoodActivity.this, "playing music", Toast.LENGTH_SHORT).show();
}
});
}
}
Edit after question update :-
Instead of using the application class, use static objects to achieve global variables. static objects are independent of objects and can be referenced using the class that they belong to. For example, if you define a static variable in your MainActivity.class and name it testObject, then it can be accessed using the following code regardless of your current activity :-
YourObject object = MainActivity.testObject;
Unless you have a specific reason for extending the Application class in Android you probably shouldn't. For reference, look at the note in the documentation for this: https://developer.android.com/reference/android/app/Application.html .
If you are trying to create an object that you can use in your Android app, simply do that as you would in Java:
public class MyObject {
//Your stuff here
}
If there is a reason that you're specifically wanting to extend the Application class then perhaps there's more that people can do to help you if you explain what you're trying to do. I just don't necessarily see a need to go through all that complexity based on your example :)
Change this to AnActivity.this.
Inside the code below the meaning of this changes from AnActivity to View.onClickListener as it is another object and inside those braces you are in the scope of the click listener class
new View.OnClickListener() {
public void onClick(View v) {
MyApplication myApplication = ((MyApplication)this.getApplication());
Toast.makeText(MoodActivity.this, "playing music", Toast.LENGTH_SHORT).show();
}
}
So the code above should become
new View.OnClickListener() {
public void onClick(View v) {
MyApplication myApplication = ((MyApplication)AnActivity.this.getApplication());
Toast.makeText(MoodActivity.this, "playing music", Toast.LENGTH_SHORT).show();
}
}
You can read a bit more about it here
Below is the code which I'm using to return a number which should be 1 when the button is clicked. However when I try to get that number from another class, it always stays 0.
As you might recognize, I tried to change the number in the onClickListener and returned it below.
I also tried to use the onPause command so that it will return the number onPause but it still doesn't work.
public class MainActivity extends Activity {
public int number;
Button btnAngled;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
btnAngled = (Button) findViewById(R.id.btnAngled);
final Intent intent = new Intent(this, angledForeheadActivity.class);
btnAngled.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
number = 1;
startActivity(intent);
}
});
}
#Override
protected void onPause() {
super.onPause();
}
public int getNumber() {
return number;
}
}
I try to get the code in another class with:
MainActivity a = new MainActivity();
int number = a.getNumber();
Sorry for the noob question..
declare the variable as static variable. Then you can simply obtain the result you want since there is only one copy of that variable. If you want to pass the value using intent, you can call putExtra() of intent to carry information to another activity.
Intent reference page
What you actually want is getting the number from another Class. Don't mix the job with button click together. You should setup the concept of model to store data and seperate UI and data, UI just change/get the data.
I suggest you either of the two ways
Store the number in some global model, then you can get the number from another Class.
User Android Broadcast to transfer the data
Use static variable in Activity is not a good idea, it may cause memroy leak, though it can solve your problem.
So I realize that this question has been asked a lot but I wasn't able to apply any of the others to my situation in a way that I was able to. Basically I am having trouble with global objects in Java as most of my experience is in Python.
Below is my code. Bascially checkbox1 is where I would like it to be, but I don't know how to get my two methods to recognize that it is there. I could fix this by defining checkbox1 in both resetAll as well as doMath but I am sure there is a better way around this
public class MainActivity extends ActionBarActivity {
// right here is where I want my objects so that both resetAll and doMath can use them
CheckBox checkbox1 = (CheckBox)findViewById(R.id.checkBox1);
public void resetAll(View view){
// do stuff with checkbox1
}
public void doMath(View view){
// do stuff with checkbox1
}
problem:
CheckBox checkbox1 = (CheckBox)findViewById(R.id.checkBox1);
You cant just initialized a View before you inflate or set the contentView of the activity or else you'll get a NPE.
solution:
Create a global variable which you already did but dont initialized it first.
CheckBox checkbox1;
In your onCreate method of the ActionBarActivity you then initialized it after the setContentView(R.layout.your_layout_for_the_checkbox);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.internal_main);
checkbox1 = (CheckBox)findViewById(R.id.checkBox1);
}
After youve done that you can call the checkbox1 field in both of the methods as long as that method are inside your MainActivity class
If you mean you want it to be accessible throughout MainActivity, you need to declare that checkbox as a member:
public class YourActivity extends Activity{
private CheckBox mCheckBoxOne;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activty_your);
mCheckBoxOne = (CheckBox)findViewById(R.id.checkBox1);
}
public void resetAll(View view){
mCheckBoxOne.setChecked(!mCheckBoxOne.isChecked());
}
public void doMath(View view){
mCheckBoxOne.setChecked(!mCheckBoxOne.isChecked());
}
}
if you want it to be accessible from other places, you need to cast the context to MainActivity or use interface . is that what you want?
I'm writing a very basic program that aims for the text view to display the phrase "Hello" after a button is pressed on the screen, but cannot figure out why every time I run it, it says that the application has stopped unexpectedly.
This is the program I wrote:
public class EtudeActivityActivity extends Activity{
TextView tvResponse;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView tvResponse = (TextView) findViewById (R.id.tvResponse);
}
public void updateTV(View v) {
tvResponse.setText("Hello");
}
}
Also, I inserted an android:onClick = "updateTV" into my main.xml file for the button.
Thanks for any help!
It is because you don't set the tvResponse member variable. Instead you set a new local variable by the same name. So when you call setText(), you are accessing an invalid reference
You need to change
final TextView tvResponse = (TextView) findViewById (R.id.tvResponse);
to
tvResponse = (TextView) findViewById (R.id.tvResponse);
to set the member variable, so it has a valid reference later on (when updateTV() is called)
I suspect you've got an instance variable called tvResponse which you haven't shown us - that's what the updateTV method will refer to. That's entirely separate from the local tvResponse variable you've declared inside onCreate. I suspect that if you change the last line of onCreate from a local variable declaration to a simple assignment to the tvResponse variable, it may work. Otherwise, if nothing is assigning a value to the instance tvResponse variable, it will have the default value of null, causing a NullPointerException in updateTV.