NullPointerException in onCreate() method while handling an event - android

I created a new Android project (for android 2.3.3) using Eclipse and I modified the main.xml file in res/layout folder as follows.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:gravity="center" >
<Button android:id="#+id/button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button01_name" />
</LinearLayout>
The strings.xml file in res/values folder is as follows.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">ButtonClickDemo3</string>
<string name="button01_name">Press this button!</string>
</resources>
Finally, here is the onCreate() method of the one Activity of the project.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button button01 = (Button) findViewById(R.id.button01);
button01.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast toast = Toast.makeText(v.getContext(), "The button was pressed!", Toast.LENGTH_SHORT);
toast.show();
}
});
setContentView(R.layout.main);
}
When I run this simple application, a NullPointerException is thrown on button01.setOnClickListener(...). Indeed, if I move the setContentView(R.layout.main); instruction writing it before creating the button, that is
...
setContentView(R.layout.main);
Button button01 = (Button) findViewById(R.id.button01);
button01.setOnClickListener(...);
...
the application works successfully. Why?

You have to set the contentView first otherwise how do you expect findViewById to find the views. This is why your getting a null pointer. button01 is a View on R.layout.main therefore you must set your contentView first

It is because your activity in the time of defining button doesn't know in which layout should it search for id/button01

setContentView(R.Layout.main) is missing in your onCreate() method

Related

Android Null Button

What might be the reasons why the button is NULL?
Button press;
//...
press = (Button) findViewById (R.id.enter);
if (press != null)
press.setOnClickListener(this);
I checked the manifest, the xml file, the code... I don't have any duplicate of R.id.enter, still the button is NULL... It all happened after I introduced a new Activity...
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
press = (Button) findViewById (R.id.enter);
if (press != null)
press.setOnClickListener(this);
}
the XML here (main.xml):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/gift2"
>
<Button
android:id="#+id/enter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="415dp"
android:background="#drawable/pattern"
android:layout_gravity="center_horizontal"
android:text="Open your box now!"
android:textSize="20sp"
/>
</LinearLayout>
One possibility is that the auto-generated R.java file has somehow got out of sync or has invalid values in it.
In this case, R.id.enter may no longer be valid and as a result findViewById(R.id.enter) can no longer find a valid object to return.
If using Eclipse, try using "Project -> Clean..." - this will delete all auto-generated files and re-create them.

Android clickable layer

I have set linearlayer to become clickable and want it to act like a button and start a new activity. However i got error. Here are part of the .xml
<LinearLayout
android:id="#+id/llproduct1"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:orientation="vertical" android:clickable="true">
<ImageView .... />
<TextView .... />
</LinearLayout>
This is the .java
Button bProduct1 = (Button) findViewById(R.id.llproduct1);
bProduct1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("com.testing.PRODUCTDESCRIPTION"));
}
What went wrong?
Button bProduct1 = (Button) findViewById(R.id.llproduct1);
you cannot cast your LinearLayout to a button. But you can do:
LinearLayout bProduct1 = (LinearLayout) findViewById(R.id.llproduct1);
bProduct1.setOnClickListener(...)
see this for reference
It is wrong class casting in "bProduct1 = (Button) findViewById(R.id.llproduct1); "
'llproduct1' is LinearLayout!! not a Button.
therefore the java code cause ClassCastException.
onClick method is declared in View class.
and both of LinearLayout and Button are inheriting View class.
so why don't you fix the code below.
View bProduct1 = findViewById(R.id.llproduct1);
bProduct1.setOnClickListener(......);

Dynamic Strings and Xml

I'm new to Android (and surely I'm not an expert Java developer), so I'm sorry for the dumb question
I would like to "capture" the id of a textView and to set its text value dynamically,
here is how I'm trying to do this:
public class AndStringTestActivity extends Activity {
/** Called when the activity is first created. */
String abc = "abcabc";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = (TextView)findViewById(R.id.test);
tv.setText(abc);
setContentView(R.layout.main);
}
}
and here is the Xml from which i'm reading the id of the textview i would like to write inside
// main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="#+id/test"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
the error i receive is the usual Application stopped unexpectedly
Thanks.
Call setContentView before trying to find the TextView. The TextView does not exist before you have called setContentView (which will inflate your XML layout)
Call setContentView(R.layout.main) before you call findViewById().

Layouts in Android [ id or field cannot be resolved]

public class Page1 extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
final Button button = (Button) findViewById(R.id.welcome);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = null;
myIntent = new Intent(view.getContext(), Page1.class);
startActivity(myIntent);
}
});
}
}
I want to load contents from another XML file named welcome.xml, but i do get an error welcome cannot be resolved or is not a field
This Page1.java class is next screen of my Android Application.
My Welcome.xml
<Button android:text="#+id/Button01" android:id="#+id/welcome"
android:layout_width="wrap_content" android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android">
</Button>
It should be working.
If you don't set the handler, do you see the button in the screen?
Is the file actually named «*W*elcome.xml»? Try to remove the capital letter (rename it to welcome.xml). Then do a clean, rebuild and check if it works now...
Could you paste your complete xml file and log? my first guess is you have a case issue , your layout file is named "Welcome" and you have setContentView to "welcome" . Also dont have same names for layouts and controls , it will get confusing.
firend you are making silly mistake:see this
public class Page1 extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
final Button button = (Button) findViewById(**R.id.Button01**);//use id of button here not layout name
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = null;
myIntent = new Intent(view.getContext(), Page1.class);
startActivity(myIntent);
}
});
}
}
Is this all what your welcome.xml has?
Your button isn't under a layout. thus, the layout file itself will be throwing out exceptions.
secondly, android:text is not correct. the entry you have made there, should be under android:id
and it shouldn't be:
final Button button = (Button) findViewById(R.id.welcome);
but:
final Button button = (Button) findViewById(R.id.Button01);
The Welcome.xml contains Button with id welcome which is not an layout to setContentView
Views can be List, relative, absolute table etc .. in which you can add a button.
And also check for the Case in filename and specified R.layout.*
Sample xml file with linearlayout and a button. Save it as welcome.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="#+id/linearlayoutmain"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<Button
android:id="#+id/ButtonWelcome"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/button"
>
</Button>
</LinearLayout>
in Your Code
public class Page1 extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
final Button button = (Button) findViewById(R.id.ButtonWelcome);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = null;
**//You have called Page1.class again which is the name of this class //again**
myIntent = new Intent(view.getContext(), Page1.class);
startActivity(myIntent);
}
});
}
}
Create another activity similarly and the call that class in the intent marked bold.
Your Welcome.xml is not complete, should be something like this :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:padding="3dip"
android:orientation="vertical">
<Button android:text="#+id/Button01" android:id="#+id/welcome"
android:layout_width="wrap_content" android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android">
</Button>
</LinearLayout>
Also, if your are still having problemas, try to clean your project so the R.java get updated with new id values like welcome id (R.id.welcome),because if R.java does not contain welcome id, you will get errors like that.

first click on linearlayout doesn flash background click color, it just flash for second and next click

I try to get the effect click background color for linear layout. I've set clickable to linear layout. and from the code also I've put the click listener the setBackgroundResource.
Here it is the xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout
android:id="#+id/llinsertmem"
android:clickable="true"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="50px">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="PUSH it"
/>
</LinearLayout>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
</LinearLayout>
and the java code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout linearInsertMem = (LinearLayout)findViewById(R.id.llinsertmem);
linearInsertMem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.setBackgroundResource(android.R.drawable.list_selector_background);
Toast.makeText(testdoank.this, "succeded", Toast.LENGTH_SHORT)
.show();
}
});
}
When first time click the clickable linearlayout, the toast text is displayed but the background color click effect doesn't. The flash background click color is only work from the second click.
any idea what the problem is?
Is not necessary do anything in JAVA code.
You can only add this as attribute:
android:background="#android:drawable/list_selector_background"
And it works for me (on Android 2.2 device)
After try and error, somehow it's work.
just put the setBackgroundResource also on the onCreate.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout linearInsertMem = (LinearLayout)findViewById(R.id.llinsertmem);
linearInsertMem.setBackgroundResource(android.R.drawable.list_selector_background);
linearInsertMem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.setBackgroundResource(android.R.drawable.list_selector_background);
Toast.makeText(testdoank.this, "succeded", Toast.LENGTH_SHORT)
.show();
}
});
}
Don't know the logic explanation. if you have a thought, please.
In the onClick method you are using v as the View which is passed, but that view may not be the LinearLayout which you want to change the background.
Thus you need to create a class level variable or a final varibale and pass the handle for the LineraLayout to the onClick method.
Remove/cut from onCreate:
linearInsertMem.setBackgroundResource(android.R.drawable.list_selector_background);
and paste it into onClick or change v. into linearInsertMem.
I think that Exlipse will then demand that linearInsertMem must be final like:
final LinearLayout linearInsertMem = (LinearLayout)findViewById(R.id.llinsertmem);
Or you can define this object above onCreate like this:
LinearLayout linearInsertMem;
then in onCreate you state:
linearInsertMem = (LinearLayout)findViewById(R.id.llinsertmem);
then onClick method will know exactly which view you want to change if you use linearInsertMem.setBackgroundResource...

Categories

Resources