Android Null Button - android

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.

Related

Button - Textview click event issue - Android studio

I have a list of buttons in my activity_main, Once i clicked on Button_A it is taking me to the next list of buttons layout for eg. Button_A1.
And once i clicked Button_A1 it should show me the text which i have written in text_view. But here its getting failed. Once i Clicked in Button_A1, it showing like "your app is stopped". Can you guys help me on this, as i am new on this platform.
**Button_A1.xml:**
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/textView2"
android:layout_gravity="center_vertical"
android:onClick="Button_A1" />
</LinearLayout>
**button_A1.java:**
public class Ov1 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ov1);
}
}
Do i have to give activity entry in manifest.xml. Please help me on this..
Button_A ----> Button_A1 ----> Textview
Clicked in Button_A1, it showing like "your app is stopped"
Because Button_A1 method is not available in Ov1 class. add method as:
public void Button_A1(View view) {
////
}
NOTE: To make TextView click-able need to add android:clickable="true" attribute in TextView xml

Android toggle button display wrong value after orientation change

Here is my problem.
I've got a simple activity which set a layout, and add rows in a table-layout(itself in a scroll view).
Those table-rows have a custom layout with a text-field and a toggle button.
Each toggle button has a value taken from a database, and when I first create the activity, the values are OK. But when I turn the device and then change the orientation, all the toggles-button take "false" value. I printed the values that I set in the Logcat, and the values are the good ones (those in the database).
I thought something like the layout I want is hidden behind another layout, but I made some tests and the text-fields change with new values, so I really don't understand why the toggle buttons don't work.
Here is the code :
TableRow layout :
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<RelativeLayout
android:id="#+id/relativelayout_row_parametres"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_weight="1.0">
<TextView
android:id="#+id/textview_row_parametres"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#android:color/black"
android:textStyle="bold"
android:textSize="20sp"
android:layout_marginLeft="2dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
/>
<ToggleButton
android:id="#+id/togglebutton_row_parametres"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="2dp"
android:textOn="#string/togglebutton_on"
android:textOff="#string/togglebutton_off" />
</RelativeLayout>
</TableRow>
Activity Layout :
<?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">
<ImageView style="#style/header" />
<LinearLayout
android:layout_width="fill_parent" android:layout_height="0dp"
android:layout_weight="0.8"
android:background="#drawable/gradient_bg"
android:padding="10dip"
android:orientation="vertical">
<ScrollView
android:layout_width="fill_parent" android:layout_height="0dp"
android:layout_weight="0.85"
android:fillViewport="true"
android:padding="10dip"
android:layout_gravity="center">
<TableLayout
android:id="#+id/tablelayout_parametres"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/cornered_bg"
android:paddingTop="5dip"
android:paddingBottom="5dip">
</TableLayout>
</ScrollView>
<Button
android:id="#+id/button_parametres_accept"
android:gravity="center"
android:text="#string/accept_changes"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="0.15"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</LinearLayout>
And the activity code:
public class Parameters extends Activity {
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Map<String, Boolean> changes = new HashMap<String, Boolean>();
final Context ctx = getApplicationContext();
LanguageManager.updateConfig(this);
setContentView(R.layout.parametres);
CountryDB[] countries = Database.instance(getApplicationContext()).getCountries();
TableLayout tabLayout = (TableLayout) findViewById(R.id.tablelayout_parametres);
for(int i =0; i<countries.length; i++){
TableRow newRow = (TableRow) getLayoutInflater().inflate(R.layout.row_parametres, null);
TextView textView = (TextView) newRow.findViewById(R.id.textview_row_parametres);
ToggleButton toggleButton = (ToggleButton) newRow.findViewById(R.id.togglebutton_row_parametres);
toggleButton.setChecked(countries[i].isToSynchronize());
toggleButton.setTag(countries[i]);
Log.e("setChecked",""+toggleButton.getId()+"/"+countries[i].isToSynchronize());
textView.setText(countries[i].getLabel());
toggleButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
CountryDB countryTemp = (CountryDB) v.getTag();
changes.put(countryTemp.getLabel(), ((ToggleButton)v).isChecked());
}
});
tabLayout.addView(newRow);
TableRow rowDivider = (TableRow) getLayoutInflater().inflate(R.layout.row_divider, null);
tabLayout.addView(rowDivider);
}
Button buttonValidation = (Button) findViewById(R.id.button_parameters_accept);
buttonValidation.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Iterator<String> iterator = changes.keySet().iterator();
while(iterator.hasNext()){
String stringTemp = iterator.next();
Database.instance(ctx).updateCountry(stringTemp, changes.get(stringTemp));
}
Intent intent = new Intent(ctx, Splash.class);
String result = "restart";
String from = "parameters";
Intent returnIntent = new Intent();
returnIntent.putExtra("result", result);
returnIntent.putExtra("from", from);
setResult(RESULT_OK, returnIntent);
startActivity(intent);
}
});
}
}
In the Log.e, I print the values, and they are good, the display on togglebuttons is wrong, they are just all "false".
Thanks for your help.
Between onCreate() and onResume() , Android tries to restore the old state of the toggle Buttons. Since they don't have unique ID's , Android wont succeed and everything is false again. Try to move your setChecked() calls into onResume() ( maybe onStart() works too).
Here is a pretty good answer to the same Question:
ToggleButton change state on orientation changed
you have to save data before Orientation.
Android have method onSaveImstamceState(Bundle outState) and onRestoreInstanceState(BundleInstaceState)
override these method in Activity.
There's a simpler solution: you only need to add configChanges property to your activity declaration, like stated here. This way you can prevent Activity restart when orientation changes. So in your manifest you should have something like
<activity android:name=".Parameters"
android:configChanges="orientation|keyboardHidden">
or if your buildTarget>=13
<activity android:name=".Parameters"
android:configChanges="orientation|keyboardHidden|screenSize">
Edit: Like reported on comments below, this is not an optimal solution. The main drawback is reported in a note of the document linked above:
Note: Handling the configuration change yourself can make it much more difficult to use alternative resources, because the system does not automatically apply them for you. This technique should be considered a last resort when you must avoid restarts due to a configuration change and is not recommended for most applications.

Force close error on setOnClickListener (Example from hello Android book section 3.5)

I am having problem in starting a new activity on clicking a button, here's my code:
package test.project;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
public class TestActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View aboutButton = findViewById(R.id.about_content);
aboutButton.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.about_content:
Intent i = new Intent(this, testit.class);
startActivity(i);
break;
// More buttons go here (if any) ...
}
}
}
Can anyone please help me correct this error
Error Line
aboutButton.setOnClickListener(this);
Main.xml file
<?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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click here" android:layout_gravity="center"
android:text="Click here" android:layout_gravity="center" android:layout_marginTop="30dip"/>
</LinearLayout>
XML file containing about_content is
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip" >
<TextView
android:id="#+id/about_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/about_text" />
</ScrollView>
about_content is already defined here
<TextView
android:id="#+id/about_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/about_text" />
Well, you didn't post your logcat output, but since this is such a common beginner's mistake, I'm going to take a wild guess and say that you are probably getting a NullPointerException.
Your call to findViewById is probably returning null, which means that the system could not find the view associated with the id given by R.id.about_content. I would double check your XML layout for typos.
Odds are you don't have anything with the id about_content in main.xml, which will create a NullPointerException.
Also, if aboutButton is supposed to be a traditional Button, then you should use this:
Button aboutButton = (Button) findViewById(R.id.about_content);
Addition
Since aboutButton is a TextView, use this:
TextView aboutButton = (TextView) findViewById(R.id.about_content);
but this TextView must be in the layout passed to setContentView() or findViewById() will return null.
That is because the "main.xml" which you have set your content view ... does not contain the about_content TextView, its in the other xml which you have posted ...
Note: You can access only those R.id's which are present in your setContentView(R.layout.yourlayout) xml ...
you make setContentView(R.layout.main); but main.xml does not include View have id = R.id.about_content. If you raplace by findViewById(R.id.button1); It will work.
This is the solution for
Button aboutButton = (Button)findViewById(R.id.about_content);
And dont forget to add testit Activity in Android Manifest

NullPointerException in onCreate() method while handling an event

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

setContentView and EditText

I have two layouts xml and can't get the second layout to work correctly.
A EditText placed on the second layout doesn't work as expected. It doesn't accept characters.
What am i missing here?
Should i use startActivity() instead?
Main.java
public class Main extends Activity implements View.OnClickListener {
EditText box1, box2;
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
showXml1();
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
String box11 = box1.getText().toString();
Toast.makeText(this, box11,Toast.LENGTH_SHORT).show();
showXml2();
break;
case R.id.button2:
String box22 = box2.getText().toString();
Toast.makeText(this, box22,Toast.LENGTH_SHORT).show();
showXml1();
break;
}
}
public void showXml2() {
setContentView(R.layout.main2);
box2 = (EditText) findViewById(R.id.editText2);
}
public void showXml1() {
setContentView(R.layout.main);
box1 = (EditText) findViewById(R.id.editText1);
}
}
main.xml
<?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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Main1" />
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1"
android:onClick="onClick"
/>
</LinearLayout>
mail2.xml
<?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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Main2" />
<EditText
android:id="#+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button2"
android:onClick="onClick"
/>
</LinearLayout>
Use a meta layout xml file with a structure similar to this one:
meta_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<ViewFlipper
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/root">
<include
layout="#layout/main" />
<include
layout="#layout/main2" />
</ViewFlipper>
And then main.java:
public class Main extends Activity implements View.OnClickListener {
EditText box1, box2;
ViewFlipper root;
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.meta_main);
box1 = (EditText) findViewById(R.id.editText1);
box2 = (EditText) findViewById(R.id.editText2);
root = (ViewFlipper) findViewById(R.id.root);
}
public void onClick(View v) {
EditText editText = null;
switch (v.getId()) {
case R.id.button1:
editText = box1;
root.showNext();
break;
case R.id.button2:
editText = box2;
root.showPrevious();
break;
}
if(editText != null) {
Toast.makeText(this, editText.getText(), Toast.LENGTH_SHORT).show();
}
}
}
Hope it helps ;)
I don't think you can load a new layout that way.
Just put the two EditTexts in one XML and put one visible and the other invisble and with a button click vice versa.
As an alternative to different activities you might want to look at ViewFlipper http://developer.android.com/reference/android/widget/ViewFlipper.html
You are only allowed to call setContentView() once in your activity.
You can either
Create a "Main" layout that just contains a parent I.E. LinearLayout, or Relative layout
setContentView() on the parent. Then acquire a reference to it with findViewById() and call .addView() on your reference passing the inflated xml from one of these two files. .removeView() will allow you to switch to the other one when you like.
or
Include all of your views in one xml layout, but make half of them Visibility.GONE and when you want to switch just make the ones that were GONE be VISIBLE and vice versa
I think it should work, you have to reinitialize references for example every findViewById needs to be called again after calling setContentView(). You are exactly doing so first you are calling showXml1() & then you are clicking button1 which is executing Case1, you are getting the value of box1 & displaying it & then you are calling showXml2() & so on. I have tried your code & it works, i am wounding why its not working on your side?
Another thing is that it may not be a good idea if you have to call findViewbyId() a LOT OF TIMES, so you should avoid it i guess.

Categories

Resources