Unable to get the reference of CheckBox in android - android

I am using a CheckBox in my activity layout. But I don't know why I am not getting the refrence of the CheckBox. It shows NullPointerException everytime. I have used another checkbox in my dialog fragment but it was working fine. I don't know what is the cause of NullPointerException.
Here is xml code
<CheckBox
android:id="#+id/ccb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="8dp"
android:text="Add Your Previous Amount\n with Current Amount "
android:textColor="#color/batteryChargedBlue"
android:textSize="13dp"
android:fontFamily="#font/caviardreams_bolditalic"
/>
Here is the java code where I am using the checkbox and getting NullPointerException.
public class StartActivity extends AppCompatActivity {
//Declaring the CheckBox variable globally
CheckBox scb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
//Initializing in the onCreate() method
scb = (CheckBox)findViewById(R.id.ccb);
...
}
//using it in the button clicked method to check whether checkbox is checked or not
public void setInitialMonthlyAmount(View view) {
if(scb.isChecked()) { //Getting The NullPointerException Here Don't know why ??
System.out.println("Checkbox is checked");
//Code
}else {
//Code
}
}
}
I think everything is correct. and I am using the same way to get the references of other views like TextViews, EditText etc and they are working fine. I don't what is wrong with this checkbox. Please Help!!!

Are you sure you coded Activity like this:?
public class StartActivity extends AppCompatActivity {
CheckBox scb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
scb = (CheckBox)findViewById(R.id.ccb);
setInitialMonthlyAmount(view)
}
public void setInitialMonthlyAmount(View view) {
if(scb.isChecked()) {
System.out.println("Checkbox is checked");
//Code
}else {
//Code
}
}

Make sure you are calling setContentView(R.layout.your_layout_with_checkbox); in your activitie's onCreate !

Related

Checkbox becomes redundant after returning to a view

I am trying to have a checkbox on my homepage, which when checked, should take me to an another view, else, displays an error message on the same view.
This works fine the first time only. If unchecked, it displays the error, and if checked, renders the next view.
However, when I return to this homepage using back button, this time the checkbox becomes redundant. Even unchecking it renders the next page correctly.
If I remove all the views of the ViewGroup, it removes them permanently, and the homepage is empty once I return to it.
I believe the checkbox needs to be reset every time I return to the view.
However, I am unable to do the same.
Please find my code below (I am a beginner to Android development):
public class MainActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE="com.android.AI";
public boolean isCheckBoxClicked=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//isChecked is the onClick attribute for checkbox in the main.xml here
public void isChecked(View view){
boolean isChecked = ((CheckBox) view).isChecked();
if(isChecked){
isCheckBoxClicked = true;
} else {
isCheckBoxClicked = false;
}
}
//Send message is onClick for a submit button
public void sendMessage(View view){
if(isCheckBoxClicked) {
Intent intent = new Intent(this, SeniorTeam.class);
startActivity(intent);
} else {
TextView acceptTerms = new TextView(this);
acceptTerms.setTextSize(15);
acceptTerms.setText("Please accpet terms and conditions before proceeding");
ViewGroup terms = (ViewGroup) findViewById(R.id.activity_main);
terms.addView(acceptTerms);
}
}
}
As far as I see this, you don't need to be able to go back by using the back Button, do you?
In case you don't there are 2 solutions
Easy:
Add this line to your verry last if
this.finish();
so your Activity should look like this:
public class MainActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE="com.android.AI";
public boolean isCheckBoxClicked=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//isChecked is the onClick attribute for checkbox in the main.xml here
public void isChecked(View view){
boolean isChecked= ((CheckBox) view).isChecked();
if(isChecked){
isCheckBoxClicked=true;
}
else{
isCheckBoxClicked=false;
}
}
//Send message is onClick for a submit button
public void sendMessage(View view){
if(isCheckBoxClicked) {
Intent intent = new Intent(this, SeniorTeam.class);
startActivity(intent);
this.finish();
}
else {
TextView acceptTerms = new TextView(this);
acceptTerms.setTextSize(15);
acceptTerms.setText("Please accpet terms and conditions before proceeding");
ViewGroup terms = (ViewGroup) findViewById(R.id.activity_main);
terms.addView(acceptTerms);
}
}
A little more complicated:
If you use the first method pressing back will actually kick the user out of your App so if you want you can just override the method when back is pressed in your next activity for that you want to add this code int your NEXT activity(SeniorTeam.class)
#Override
public void onBackPressed(){
//custom actions here leave blank to render back useless
}
You should completely remove the isCheckBoxClicked variable, the isChecked function (and remove it from the attributes). In the sendMessage function, just call ((CheckBox)findViewById(id)).isChecked() instead of isCheckBoxClicked.
The way you have it coded, there is too much room for disconnect between the variables and the UI. It is not necessary.

app closes during setText

I have a checkedbox that when, onClick (checked/unchecked), would setText to an activity.
When I run the application, it stopped and will return to the previous page.
What is wrong with my code?
My OrderActivity.java has:
public class OrderActivity extends ActionBarActivity {
CheckBox OrderMenuBiggDeal, OrderMenuCrispyChicken, OrderMenuExtremeBurger, OrderMenuTenderloinTips;
TextView ReceiptTextMenuBiggDeal, ReceiptTextMenuCrispyChicken, ReceiptTextMenuExtremeBurger, ReceiptTextMenuTenderloinTips;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order);
OrderMenuBiggDeal = (CheckBox) findViewById(R.id.checkBoxMenu1);
ReceiptTextMenuBiggDeal = (TextView) findViewById(R.id.textViewReceiptMenuPrice1);
and
public void onClickBiggDeal(View view){
if(OrderMenuBiggDeal.isChecked()){
ReceiptTextMenuBiggDeal.setText("" + "hello");
}
else{
ReceiptTextMenuBiggDeal.setText(R.string.default_value);
}
the application closes on the ReceiptTextMenuBiggDeal.setText("" + "hello"); line.
The setContentView is activity_order.xml.
The location of the TextView that I want to setText (ReceiptTextMenuBiggDeal) is on a different xml file, the activity_receipt.xml
You should change this
setContentView(R.layout.activity_order);
to
setContentView(R.layout.activity_receipt);
It's because your TextView with id textViewReceiptMenuPrice1 belong to activity_receipt layout and you trying to find it on activity_order layout.
You cannot set text on textview that is in other xml, just in one that is set in setcontentview

Textview.text change example

I have 2 layouts. First layout has 2 textviews. And second layout has 1 button. I want to do when i pres buton textviews.text change. But i get null error about textviews.
textviews on musicactivity, button on homeactivity.
my first activity class --> homeactivity,secon activity class --> Musicactivity,textview-->ad1,textview-->ad2,textviews on musiclayouts,Button on homeactivity.
public class HomeActivity extends Activity {
Button btn;
TextView ad1;
TextView ad2;
private MusicActivity music;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
btn=(Button)findViewById(R.id.button1);
ad1=(TextView)findViewById(R.id.textView1);
ad2=(TextView)findViewById(R.id.textView2);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
{
ad1.setText(null);
ad2.setText(null);
}
}
});
}
The error message you posted is for line 40, which is doing a close of v1. I don't know what a veritabani is, but it appears that error is happening there. I suspect the rest of the error trace might say more.
You are doing it wrong. You can't get the textViews if they are not in the layout. You say yourself they are not in the layout. You have to pass the values you want to set to the new activity (musicActivity) via an Intent. Then in musicActivity's you can get the textViews, you have the values, you set them.

Android: How can I reference layout items outside the Main Activity?

My onCreate method sets the content view and sets up an image button:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton mGetClickTime = (ImageButton) findViewById(R.id.clicker);
}
But I want to create a method that changes the background of the ImageButton:
public void mUpdateBackground() {
if (backgroundPic) {
randomImageId = R.drawable.bg1;
}
else {
randomImageId = R.drawable.bg0;
}
mGetClickTime.setImageResource(randomImageId);
}
The problem is, the mUpdateBackground method doesn't know about the layout. If I declare the layout in the method it resets all the changes made programatically in the MainActivity.
Any ideas how I can solve this problem?
the mUpdateBackground method doesn't know about the layout
I am going to translate that to mean:
the mUpdateBackground method doesn't know about the ImageButton
If that is correct, make ImageButton mGetClickTime be a data member of your activity, instead of a local variable within onCreate(), and have mUpdateBackground() be a method on that same activity.
You need to move the ImageButton declaration to your Activity scope instead of your onCreate() method scope. Try like this:
public class YourActivity extends Activity{
ImageButton mGetClickTime;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGetClickTime = (ImageButton) findViewById(R.id.clicker);
}
public void mUpdateBackground() {
if (backgroundPic) {
randomImageId = R.drawable.bg1;
}
else {
randomImageId = R.drawable.bg0;
}
mGetClickTime.setImageResource(randomImageId);
}
}

Simple android questions

So I've been looking around for android tutorials, help questions, etc.. I keep running into questions or tutorials hard for me to understand.
Here's my questions:
When I create an item in the visual designer, piece of code will be created in the .xml.
How can I get the ID of that item to use it in the .java file later?
How can I add callbacks when let's say a button gets clicked?
Here's what I have so far:
.java
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.Button;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void Button_click_callback() // Where to add the callback in the .xml?
{
// How to get button ID and change the text of it?
//Knowing this will help me A LOT!
}
}
.xml
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="79dp"
android:layout_marginTop="32dp"
android:text="Button" />
When I create an item in the visual designer, piece of code will be created in the .xml. How can I get the ID of that item to use it in the .java file later?
Step #1: Ensure that you have assigned an ID for the widget in the designer (in your XML above, you will see this as android:id="#+id/button1)
Step #2: In Java, you can get at the Java object for that widget by calling findViewById(R.id.button1) at some appropriate time (e.g., from an Activity, sometime after you call setContentView()).
How can I add callbacks when let's say a button gets clicked?
Generally, there is a setter method for this, such as setOnClickListener() that you can call on the Button you retrieved by findViewById().
In the specific case of click events on widgets hosted by activities, there is also an android:onClick attribute you can have in the XML, which supplies the name of a method on your Activity that will get called when the widget is clicked, instead of your having to use the setter.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do something in response to button click
}
});
}
All of this is extensively documented on the Android Developer site. You should be looking their for this basic stuff.
http://developer.android.com/guide/topics/ui/controls/button.html
You can use findViewById to get view ids from XML in Java, Make sure that you should declare the ids in views, otherwise it might cause exception which results apps force close
If you want call back with xml rather than programatically
you can declare android:onClick attribute on that Views in layout XML
For example, in your case you need add android:onClick="Button_click_callback" in your
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="79dp"
android:layout_marginTop="32dp"
android:text="Button"
android:onClick="Button_click_callback"/>
then you can use Button_click_callback method for call back in your Activity
public void Button_click_callback()
{
}
if you want call back programatically with java,
first you have get the view with findViewById and then you can add click listener to that view
You need to use the onClickListener and override the onClick method.
btn.setOnClickListener.(new View.OnClickListener(){
#Override
public void onClick(View v) {
//TO DO
}
});
OnClickListener is an interface. And thats why you need to override the OnClick method.
//in oncreate method of activity
//take button id like that
Button button1 = (Button)findViewById(R.id.button1);
//then implement on click listener for performing action on button
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do something in response to button click
}
});
}
//you can also implements onclicklistener in activity.its interface;
public class MainActivity extends Activity implements View.OnClickListener
//then generate method
public void onClick(View view) {
}
public class MainActivity extends Activity {
private Button button1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = findViewById(R.id.button1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void Button_click_callback() {
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do something in response to button click
Log.e("click", "-------------button click");
}
});
}
}
Those two code snippets are equal, just implemented in two different ways.
Code Implementation
Button btn = (Button) findViewById(R.id.mybutton);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myFancyMethod(v);
}
});
// some more code
public void myFancyMethod(View v) {
// does something very interesting
}
Above is a code implementation of an OnClickListener. And this is the XML implementation.
XML Implementation
<?xml version="1.0" encoding="utf-8"?>
<!-- layout elements -->
<Button android:id="#+id/mybutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me!"
android:onClick="myFancyMethod" />
1) First Look at your XML file.In code it shows
android:id="#+id/button1.
You can edit it on your own name.Same thing you can do to change it though the GUI appear at right side of your design.
You can get your ID using findViewById(R.id.your id name); function.
For an Example:
My button id is btn1.In my code I can use that button by getting it's Id as follows:
Button btn1=findViewById(R.id.btn1);
2)You can callback after creating your Button which you have created Before as follows;
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Create your code
}
});
}
For the call backs - The android component needs to be registered in the calling device . The id of the components has to be unique in the xmls.
Using the unique id the components can be dynamically altered or the call backs can be used.

Categories

Resources